Before:
hostname Foo
!
interface GigabitEthernet 1/1
switchport mode trunk
switchport trunk allowed vlan 10,20,30
!
interface GigabitEthernet 1/2
ip address 192.0.2.1 255.255.255.128
no ip proxy-arp
!
After:
hostname Foo
!
interface GigabitEthernet 1/1
switchport mode trunk
switchport allowed vlan 10,20,30,40
!
interface GigabitEthernet 1/2
ip address 192.0.2.1 255.255.255.128
!
I know I can diff these two strings with difflib
, but difflib does not understand Cisco IOS syntax.
Difflib example
import difflib
before = open('before.txt').readlines()
after = open('after.txt').readlines()
# Find and print the diff:
for line in difflib.unified_diff(
before, after, fromfile='before.txt',
tofile='after.txt', lineterm=''):
print(line)
When I run this I get:
--- before.txt
+++ after.txt
@@ -2,9 +2,8 @@
!
interface GigabitEthernet 1/1
switchport mode trunk
- switchport trunk allowed vlan 10,20,30
+ switchport allowed vlan 10,20,30,40
!
interface GigabitEthernet 1/2
ip address 192.0.2.1 255.255.255.128
- no ip proxy-arp
!
This is not a diff that will work with Cisco IOS. Most importantly, the interface
names are not included in the diff set for the interface commands (such as no ip proxy-arp
); however, the interface command is required for a proper Cisco IOS diff.
Required output
Using python, how do I get diff output similar to this, which understands a Cisco configuration format?
interface GigabitEthernet 1/1
switchport allowed vlan 10,20,30,40
interface GigabitEthernet 1/2
ip proxy-arp
Notice how each interface command diff is preceded by the interface name; furthermore, the ip proxy-arp
command is added because no ip proxy-arp
was removed from the original configuration.
Assume your configs are stored in files named before.txt
and after.txt
import os
from ciscoconfparse2 import Diff
diff_lines = Diff('before.txt', 'after.txt').get_diff()
print(os.linesep.join(diff_lines))
That will be really close to your desired output:
$ python diff.py
interface GigabitEthernet 1/1
no switchport trunk allowed vlan 10,20,30
switchport allowed vlan 10,20,30,40
interface GigabitEthernet 1/2
ip proxy-arp
There are a few things to note:
- The library will negate the
switchport trunk allowed vlan 10,20,30
command, which you did not have in your original. However, that’s allowable since it’s still a valid Cisco IOS command - The diff double-spaces the child commands. Again this is allowable since Cisco IOS ignores whitespace in front of the command
FWIW, you can also store the configurations in variables within the diff script, but that’s more work for the script itself in this case.