问题
I've been reading about https://pypi.org/project/ciscoconfparse/ and found that it can do this.
Which interfaces are missing a critical command?
Here is my scenario. First of all, I will try to find interface block that has shutdown
in it.
Second script is the other way around which is to find interface block that doesn't has shutdown
in it.
Sample of Cisco config file.
$ cat exampleswitch.conf
! filename:exampleswitch.conf
!
hostname ExampleSwitch
!
no ip domain lookup
!
interface GigabitEthernet 1/1
switchport mode trunk
no ip address
!
interface GigabitEthernet 1/2
no cdp enable
shutdown
!
interface GigabitEthernet 1/3
ip address 192.0.2.1 255.255.255.0
!
interface GigabitEthernet 1/4
switchport mode access
shutdown
!
$
The first script will find all interfaces which has been explicitly "shutdown".
$ cat script1.py
from ciscoconfparse import CiscoConfParse
parse = CiscoConfParse('exampleswitch.conf', syntax='ios')
for intf_obj in parse.find_blocks(r'^\sshutdown'):
print(intf_obj)
$
It works just fine.
$ python script1.py
interface GigabitEthernet 1/2
no cdp enable
shutdown
interface GigabitEthernet 1/4
switchport mode access
shutdown
$
Then, I decided to try second script to find all interfaces which has NOT been explicitly "shutdown".
$ cat script2.py
from ciscoconfparse import CiscoConfParse
print('print all interfaces without shutdown')
parse = CiscoConfParse('exampleswitch.conf', syntax='ios')
for intf_obj in parse.find_blocks(r'^((?!sshutdown).)*$'):
print(intf_obj)
$
Output
$ python script2.py
! filename:exampleswitch.conf
!
hostname ExampleSwitch
!
no ip domain lookup
!
interface GigabitEthernet 1/1
switchport mode trunk
no ip address
!
interface GigabitEthernet 1/2
no cdp enable
shutdown
!
interface GigabitEthernet 1/3
ip address 192.0.2.1 255.255.255.0
!
interface GigabitEthernet 1/4
switchport mode access
shutdown
!
$
However, it didn't really work as expected. What I wanted is only interfaces configuration without "shutdown" keyword in it's interface block and not the whole configuration file like the output below.
Desired Output
$ python script3.py
interface GigabitEthernet 1/1
switchport mode trunk
no ip address
interface GigabitEthernet 1/3
ip address 192.0.2.1 255.255.255.0
$
来源:https://stackoverflow.com/questions/65698628/python-ciscoconfparse-to-find-all-interfaces-block-which-has-not-been-shutdown