A Simple Python Script to Backup a Palo Alto

We can have a scheduled Palo Alto backup with Panorama. But this is a costly solution, especially if you only have one or two firewalls.

The alternative is to access the firewall’s API. Of course, the best way to do this is with a script.

Getting an Authentication Key

Before you do anything, you need an authentication key from the firewall. You could use a script or postman to do this, but the simplest way to do this is through a web browser:

https://<IP or URL>/api/?type=keygen&user=USERNAME&password=PASSWORD

Update the link above to use the hostname or IP address of your firewall, and enter the username and password. You will receive a response that looks something like this:

<response status="success">

This is the key that you will need to pass to the firewall along with every request you make. This is as good as a password, so keep it safe.

In this example, we’ll be storing this key in the Operating System’s environment variables.

The Script

This script uses the requests module, so make sure you install it using pip.

import os
import requests

# The FQDN of the device: Update as needed
device = "YOUR-DEVICE"

# Get the API Key from OS environment variables
key = os.environ.get('API_Key')

# Build the URL
api = "https://" + device + "/api/"
type = "export"
category = "configuration"
url = api + "?type=" + type + "&category=" + category + "&key=" + key

# Send a GET to the Palo Alto (assuming you have a valid certificate)
response = requests.get(url)
print ("Response: ", response.status_code)

# Save the backup (relative to the location the script is run)
print ("Saving backup...")
file = open("pa-backup.xml", "wb")

The general flow of the script is:

  1. Get the IP/FQDN of your device, and the API Key
  2. Using those details, build the URL that we need to access
  3. Send a GET request to the URL, and store the response
  4. Open a file in “wb” mode, and save the contents there

This could be improved by adding a date stamp to the filename and using a custom location for the backup file.