pythonciscocisco-iosciscoconfparse

Python ciscoconfparse to find shutdown interfaces and the whole interface block?


The following examples will use this configuration which is taken from http://pennington.net/tutorial/ciscoconfparse/ccp_tutorial.html#slide3

! filename:exampleswitch.conf
!
hostname ExampleSwitch
!
interface GigabitEthernet 1/1
 switchport mode trunk
 shutdown
!
interface GigabitEthernet 1/2
 switchport mode access
 switchport access vlan 20
 switchport nonegotiate
 no cdp enable
!
interface GigabitEthernet 1/3
 no switchport
 ip address 192.0.2.1 255.255.255.0

This is the code which is also taken from http://pennington.net/tutorial/ciscoconfparse/ccp_tutorial.html#slide7

from ciscoconfparse import CiscoConfParse

parse = CiscoConfParse('exampleswitch.conf', syntax='ios')

for intf_obj in parse.find_objects_w_child('^interface', '^\s+shutdown'):
    print("Shutdown: " + intf_obj.text)

Output

$ python script.py 
Shutdown: interface GigabitEthernet 1/1
$ 

The code is working just fine. But instead of just displaying Shutdown: interface GigabitEthernet 1/1, would it be possible to display the whole interface GigabitEthernet 1/1 block in the output which is:

interface GigabitEthernet 1/1
 switchport mode trunk
 shutdown

Solution

  • I guess what you are looking for is find_blocks.

    find_blocks(linespec, exactmatch=False, ignore_ws=False). Find all siblings matching the linespec, then find all parents of those siblings. Return a list of config lines sorted by line number, lowest first

    Have a look at the Ciscoconfparse API Documentation which includes an Example.

    So I guess it would look something like this:

    from ciscoconfparse import CiscoConfParse
    
    parse = CiscoConfParse('exampleswitch.conf', syntax='ios')
    
    for intf_obj in parse.find_blocks(r'^\sshutdown'):
          print(intf_obj)