[python]Create firewall objects with Palo Alto API

This is a code example to demonstrate the use of Palo Alto API. Suppose I need to create pool.ntp.org firewall objects. Here’s the code sample:

import dns.resolver, requests
from bs4 import BeautifulSoup as BS

address_group_xpath = "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address-group"
address_xpath = "/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address"


def create_object(hostname,ip_address):
    create_address = """
    <entry name="{}">
        <ip-netmask>{}</ip-netmask>
    </entry>
    """.format(hostname,ip_address)
    return create_address


def get_key(username,password):
    response = requests.get('https://192.168.1.104/api/?type=keygen&user={}&password={}'.format(username,password), verify=False)
    soup = BS(response.content, 'html.parser')
    # store the data inside the <key>element
    pa_key = soup.find('key').text
    return pa_key


key = get_key("admin","admin")
answers = dns.resolver.query("pool.ntp.org", "A")
fw_objects = []
for rdata in answers:
    hostname = "pool.ntp.org" + "-" + str(rdata)
    fw_objects.append(create_object(hostname,rdata))

for i in range(0,fw_objects.__len__()):
    #print(fw_objects[i])
    requests.post('https://192.168.1.104/api/?type=config&action=set&key={}&xpath={}&element={}'.format(key,address_xpath,fw_objects[i]),verify=False)

The result look like this:
Snip20171112_5.png

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s