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)