[python]Working with Palo Alto firewall API with pan-python module

This is another demonstration on the use of pan-python module. The usage documentation can be found in github.

This is a simple demonstration on using the pan.xapi module from pan-python. Only changes the device configuration time settings. The demo uses the module to set the time zone and ntp primary and secondary addresses. To reduce the number of xml tags required, the xpath is used. The commit is used after the set command is issued, this code sample can be improved with try and except loop to handle exceptions.

My personal opinion this module is actually not required, requests module can give the same result without a lot of coding, this pan-python module would be useful if it has list of xml commands and list of xpaths.

Code sample:

import pan.xapi,time
#documentation on github https://github.com/kevinsteves/pan-python/blob/master/doc/pan.xapi.rst
#xpath can be navigated on PAN OS on this path https://firewall_ip/api/
deviceconfig_system_xpath = "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system"

#define the timezone, can read from a list and enumerate in dictionary
tz = {}
tz['SG'] = 'Asia/Singapore'
tz['JP'] = 'Asia/Tokyo'
tz['US'] = 'US/Pacific'

#Palo Alto credential, can be modified by using an external encrypted list
def get_pan_credentials(username,password):
    cred = {}
    cred['api_username'] = username
    cred['api_password'] = password
    cred['hostname'] = '192.168.1.104'
    return cred

#device configuration setting only time
def set_time(timezone,ntp_primary,ntp_secondary):
    deviceconfig = """
    <timezone>{}</timezone>
    <ntp-servers>
        <primary-ntp-server>
            <ntp-server-address>{}</ntp-server-address>
        </primary-ntp-server>
        <secondary-ntp-server>
            <ntp-server-address>{}</ntp-server-address>
        </secondary-ntp-server>
    </ntp-servers>
""".format(timezone,ntp_primary,ntp_secondary)
    return deviceconfig
                
config = set_time(tz['SG'],'203.123.48.219','128.199.169.185')

#shoud use try and except, if status code is error then break exit with error code.
#this is a demo hence not as good on error handling.
xapi = pan.xapi.PanXapi(**get_pan_credentials('admin','admin'))
xapi.set(xpath=deviceconfig_system_xpath,element=config)
time.sleep(3)
print(xapi.status)
time.sleep(3)
xapi.commit(cmd="<commit></commit>",timeout=10)
print(xapi.status)

Here’s the result:
Snip20171112_8.png

Snip20171112_9

Advertisement

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 )

Facebook photo

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

Connecting to %s