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 1.1.1.0/24 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
 2!
 3policy-map QOS_1
 4 class GOLD
 5  priority percent 10
 6 class SILVER
 7  bandwidth 30
 8  random-detect
 9 class default
10!
11interface Ethernet0/0
12 ip address 1.1.2.1 255.255.255.0
13 no cdp enable
14!
15interface Serial1/0
16 encapsulation ppp
17 ip address 1.1.1.1 255.255.255.252
18!
19interface Serial1/1
20 encapsulation ppp
21 ip address 1.1.1.5 255.255.255.252
22 service-policy output QOS_1
23!
24interface Serial1/2
25 encapsulation hdlc
26 ip address 1.1.1.9 255.255.255.252
27!
28class-map GOLD
29 match access-group 102
30class-map SILVER
31 match protocol tcp
32!
33access-list 101 deny tcp any any eq 25 log
34access-list 101 permit ip any any
35!
36access-list 102 permit tcp any host 1.5.2.12 eq 443
37access-list 102 deny ip any any
38!

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("!")
      cfgdiffs.append_line(intf.text)  # Add the interface text
      cfgdiffs.append_line(" mpls ip")

Result:

>>> 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
>>>