Example Usage: Build configuration diffs

Let’s suppose we need to find all serial interfaces in a certain address range and configure them for the MPLS LDP protocol. We will assume that all serial interfaces in need to be configured with LDP.

Baseline Configuration

This tutorial will run all the queries against a sample configuration, which is shown below.

 1! Filename: /tftpboot/bucksnort.conf
 3policy-map QOS_1
 4 class GOLD
 5  priority percent 10
 6 class SILVER
 7  bandwidth 30
 8  random-detect
 9 class default
11interface Ethernet0/0
12 ip address
13 no cdp enable
15interface Serial1/0
16 encapsulation ppp
17 ip address
19interface Serial1/1
20 encapsulation ppp
21 ip address
22 service-policy output QOS_1
24interface Serial1/2
25 encapsulation hdlc
26 ip address
28class-map GOLD
29 match access-group 102
30class-map SILVER
31 match protocol tcp
33access-list 101 deny tcp any any eq 25 log
34access-list 101 permit ip any any
36access-list 102 permit tcp any host eq 443
37access-list 102 deny ip any any

Diff Script

The script below will build a list of serial interfaces, check to see whether they are in the correct address range. If so, the script will build a diff to enable LDP.

from ciscoconfparse import CiscoConfParse

# Parse the original configuration
parse = CiscoConfParse('/tftpboot/bucksnort.conf')

# Build a blank configuration for diffs
cfgdiffs = CiscoConfParse([])

# Iterate over :class:`~IOSCfgLine` objects
for intf in parse.find_objects("^interface Serial"):

   ## Search children of the interface for 1.1.1
   if (intf.re_search_children(r"ip\saddress\s1\.1\.1")):
      cfgdiffs.append_line(intf.text)  # Add the interface text
      cfgdiffs.append_line(" mpls ip")


>>> cfgdiffs.ioscfg
['interface Serial1/0', ' mpls ip', 'interface Serial1/1', ' mpls ip', 'interface Serial1/2', ' mpls ip']
>>> for line in cfgdiffs.ioscfg:
...     print(line)
interface Serial1/0
 mpls ip
interface Serial1/1
 mpls ip
interface Serial1/2
 mpls ip