[python]Exception handling with pan-python

pan.xapi has its own error handling, so on previous post i updated the code with exception handling.

I actually tested with wrong credential, I could see the http 403 forbidden error raised. Which is good, as I would know what went wrong…

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')

#below code modified with exception handling, by using pan-python own error
try:
    xapi = pan.xapi.PanXapi(**get_pan_credentials('admin','admin'))
except pan.xapi.PanXapiError as PE:
    print(PE)

try:
    xapi.set(xpath=deviceconfig_system_xpath,element=config)
    time.sleep(3)
    print(xapi.status)
except pan.xapi.PanXapiError as PE:
    print(PE)

time.sleep(3)
try:
    xapi.commit(cmd="<commit></commit>",timeout=10)
    print(xapi.status)
except pan.xapi.PanXapiError as PE:
    print(PE)

This is how it looked like:
Snip20171112_11

Advertisements
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