Created
July 9, 2020 16:24
-
-
Save Dapacruz/722ef16261e142687f57a21209bbb335 to your computer and use it in GitHub Desktop.
Sorts PAN-OS address/service group object members in XML formatted configurations
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| '''PAN-OS Group Object Sorter | |
| pan-group-sort.py | |
| Author: David Cruz (davidcruz72@gmail.com) | |
| Python version >= 3.6 | |
| Required Python packages: | |
| none | |
| Features: | |
| Sorts PAN-OS address/service group object members in XML formatted configurations | |
| ''' | |
| import xml.etree.ElementTree as ET | |
| class PanGroupSorter(object): | |
| def __init__(self, tree): | |
| self.tree = tree | |
| self.elements = [("shared/address-group", "static"), ("shared/service-group", "members")] | |
| def sort(self): | |
| for elem, node in self.elements: | |
| for i in self.tree.find(elem): | |
| data = [] | |
| # Get address/service group members | |
| members = i.find(node) | |
| # Dynamic groups have a different parent node (dynamic). Sorting is not needed, so they are skipped. | |
| if members: | |
| for member in members: | |
| key = member.text | |
| # Skip duplicate members | |
| if [i for i, v in enumerate(data) if v[0] == key]: | |
| continue | |
| data.append((key, member)) | |
| data.sort(key=lambda i: i[0]) | |
| members[:] = [item[-1] for item in data] | |
| # ET.dump(container) | |
| def main(): | |
| configs = ["Running_Config", "Candidate_Config"] | |
| print("Sorting ... ", end="") | |
| for config in configs: | |
| tree = ET.parse(f"source/{config}.xml", parser=ET.XMLParser(encoding="iso-8859-5")) | |
| sorter = PanGroupSorter(tree) | |
| sorter.sort() | |
| tree.write(f"output/{config}_Sorted.xml") | |
| print("completed!") | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment