This code sample uses requests and beautifulsoup4 modules to manipulate data extracted with PA’s REST API. PA only supports xml though.
The requests is to use the GET method when calling REST API, the beautifulsoup4 is to easily extract the content of a xml element.
I encounter some issues when working with xml element that has hypen, example below:
<response status="success"> <result> <system> <hostname>PA-VM</hostname> <ip-address>192.168.1.104</ip-address> <netmask>255.255.255.0</netmask> <default-gateway>192.168.1.1</default-gateway> <is-dhcp>yes</is-dhcp> <ipv6-address>unknown</ipv6-address> <ipv6-link-local-address>fe80::5200:ff:fe01:0/64</ipv6-link-local-address> <ipv6-default-gateway/> <mac-address>50:00:00:01:00:00</mac-address> <time>Sat Nov 11 06:25:20 2017</time> <uptime>0 days, 3:25:59</uptime> <devicename>PA-VM</devicename> <family>vm</family> <model>PA-VM</model> <serial>unknown</serial> <vm-mac-base>BA:DB:EE:FB:AD:00</vm-mac-base> <vm-mac-count>255</vm-mac-count> <vm-uuid>3E304129-D98B-4BD4-A3EE-8C74A586B7BA</vm-uuid> <vm-cpuid>KVM:23060000FDFB8B07</vm-cpuid> <vm-license>none</vm-license> <vm-mode>KVM</vm-mode> <sw-version>8.0.0</sw-version>
Notice the ip-address
,default-gateway
,sw-version
, this will be a problem when executing the python code, i could not use a backslash to escape the hypen, fortunately i found beautifulsoup4 has a find method which allows me to get the data of the xml element i want.
Below is the python code sample:
import requests #use beautifulsoup to parse xml tags easily and effortlessly. Much easier than lxml module from bs4 import BeautifulSoup as bs #get the authentication key from PA response = requests.get('https://192.168.1.104/api/?type=keygen&user=admin&password=admin',verify=False) soup = bs(response.content,'html.parser') #store the data inside the <key>element key = soup.find('key').text cmd = """ <show><system><info></info></system></show> """ r = requests.get("https://192.168.1.104/api/?type=op&cmd={}&key={}".format(cmd,key),verify=False) output = bs(r.content,'html.parser') print("The hostname is " + (output.response.result.system.hostname).text) print("The management ip address and mask is " + (output.find('ip-address')).text + " " + (output.response.result.system.netmask).text) print("The default gateway is " + (output.find('default-gateway')).text) print("PAN OS version is " + (output.find('sw-version')).text)
So here’s the output:
The hostname is PA-VM
The management ip address and mask is 192.168.1.104 255.255.255.0
The default gateway is 192.168.1.1
PAN OS version is 8.0.0