Created
May 25, 2018 17:23
-
-
Save btorresgil/0fa16f2e67de67e313e2f66f401c7c4b to your computer and use it in GitHub Desktop.
Palo Alto Networks: Export security rules to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
from collections import OrderedDict | |
from pandevice import firewall, policies | |
# CHANGE THESE: | |
FIREWALL = '10.0.1.1' | |
USERNAME = 'admin' | |
PASSWORD = 'mypassword' | |
CSVFILE = 'myrules.csv' | |
# Create firewall object with rulebase for connection | |
fw = firewall.Firewall(FIREWALL, USERNAME, PASSWORD) | |
rulebase = fw.add(policies.Rulebase()) | |
# Pull all security rules from the firewall | |
rules = policies.SecurityRule.refreshall(rulebase) | |
# Process the security rules into a list of dictionaries | |
rule_dicts = [OrderedDict(sorted(rule.about().items(), key=lambda t: t[0])) for rule in rules] | |
# Export the security rule dictionaries to a csv file | |
if rule_dicts: | |
with open(CSVFILE, 'w') as csvfile: | |
fieldnames = list(rule_dicts[0].keys()) | |
try: | |
# Put name at the beginning of the csv file, other fields are alphabetical | |
fieldnames.insert(0, fieldnames.pop(fieldnames.index('name'))) | |
except ValueError: | |
# There was no name field, so just move on | |
pass | |
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) | |
writer.writeheader() | |
for rule in rule_dicts: | |
writer.writerow(rule) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment