[python]Trying the operation command api in Palo Alto Firewall

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">
<time>Sat Nov 11 06:25:20 2017</time>
<uptime>0 days, 3:25:59</uptime>

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('',verify=False)
soup = bs(response.content,'html.parser')
#store the data inside the <key>element
key = soup.find('key').text
cmd = """

r = requests.get("{}&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
The default gateway is
PAN OS version is 8.0.0

This entry was posted in Python, Scripting and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s