orig: 2021-05-15
updated: 2022-08-28
Introduction
Description: I was using the PaloAltoNetworks Github project, but wanted to customize it and also was looking at adding it to some internal projects and try to understand what I was doing. My original code was built around Palo Alto’s XML API, so I’ve been updating it against Palo Alt’s newer version since updating their API (begining in PanOS 9.0 release see PAN-OS Documents
) to use REST API Request and Response Structure, which, I feel, made it a lot easier to interact with.
You can find most of Palo Alto apporved Repositories on their github page
. I am a fan of it, but I found I had to massage some of the incoming data to the way I wanted/needed it. So, I created my own.
You can find my personal Palo Alto SDK my github page
or just download it using
python -m pip install paloaltoapi
for more info on this see Palo Alto Module
Resources
Code
A simple function to retrieve an API Key taken from my my panorma.py module (certstore is ‘assumed’ valid if passed; there are checks done elsewhere). My url.py module holds a list of the URL’s required to interact with Palo Alto.
url.py module
# Collection of URLs
def key_gen(device):
return f'https://{device}/api/'
def get_baseurl(device, version='9.0'):
return f"https://{device}/restapi/v{version}/"
panorma.py module
import requests, json
from requests.exceptions import HTTPError, SSLError
from bs4 import BeautifulSoup as BS
from .url import *
from .exceptions import *
def get_key(device, username, password, certstore='None'):
"""
Get API Key from Palo Alto Device
Args:
----
device: Deivce FQDN
username: Device Username
password: Device Password
certstore: Used to add Enterprise CA if necessary
"""
url = key_gen(device)
params = {
'type': 'keygen',
'user': username,
'password': password
}
if certstore == 'None':
certstore = True
try:
r = requests.get(url, params=params, verify=certstore)
r.raise_for_status()
except SSLError:
raise CertificateError
except HTTPError as err:
raise HTTPError('ERROR:\tHTTPError Invalid Credential')
except Exception as err:
raise Exception(err)
soup = BS(r.text,features='html.parser')
if r.status_code == 200:
return soup.find('key').text
else:
raise HTTPErrorCode(soup.find('msg').text)
From here I can leverage the API Key to take care of any task I need done. I leverage this to then update, remove and manipulate objects.