For a few months now, I have been getting more and more interested in network-based differential comparison. This comes in extremely useful for:
- Troubleshooting - The network is not working; what are the differences from the last known working state.
- Maintenances - What are the differences in the network after completing a maintenance.
- Security - Were any changes made on the network between now and x outside of change control.
- System Synchronization - What is configured within my source of truth, compared to my network? Based on the results, make the required updates to the network.
Within this multi-part post, we will cover the different tools that we can use to perform differential comparison — ranging from
difflib for text block comparison to
diffsync, which allows you to compare and perform full synchronization of your datasets.
The first tool we will cover is
This module provides classes and functions for comparing sequences. For example, it can be used for comparing files and can produce information about file differences in various formats, including HTML and context and unified diffs.
Think, fetching the configuration via Netmiko and then performing a comparison, for example. Let's look at a quick example on comparing 2 configs,
import difflib config1 = open("config1.txt").readlines() config2 = open("config2.txt").readlines() diff = difflib.ndiff(config1, config2) print(''.join(diff),) === transceiver qsfp default-mode 4x10G ! hostname eos-access3 ! spanning-tree mode mstp ! no aaa root ! - vlan 30 ? ^ + vlan 10 ? ^ - name VLAN30 ? ^ + name VLAN10 ? ^ ! interface Port-Channel30 switchport mode trunk - switchport trunk allowed vlan 30 ? ^ + switchport trunk allowed vlan 10 ? ^
Great. But what if we want some colour and to output this as an HTML table? For this we use
htmlDiff(). Like so
import difflib config1 = open("config1.txt").readlines() config2 = open("config2.txt").readlines() diff_html = difflib.HtmlDiff().make_file(config1, config2) with open('diff_results.html', 'w') as opened_file: opened_file.write(diff_html)
The written HTML file would then look like this when opened. Nice!