Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...