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.

difflib

The first tool we will cover is difflib.

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!

difflib HTML output
Master Network Automation
Join today and get access to:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 Multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Monthly online meetups

100% Satisfaction Guaranteed!
Cancel your membership at any time.


Join Today