Python ciscoconfparse 查找关闭接口和整个接口块?

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

以下示例将使用此配置,该配置取自 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

这是同样取自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)

输出

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

代码运行良好。但是,除了显示 Shutdown: interface GigabitEthernet 1/1,是否可以在输出中显示整个 interface GigabitEthernet 1/1 块,即:

interface GigabitEthernet 1/1
 switchport mode trunk
 shutdown

我猜你要找的是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

查看包含示例的 Ciscoconfparse API Documentation

所以我想它看起来像这样:

from ciscoconfparse import CiscoConfParse

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

for intf_obj in parse.find_blocks(r'^\sshutdown'):
      print(intf_obj)