我正在尝试使用python将cisco运行配置转换为参数,并且我被困在使用python读取配置部分。 假设您有以下节:
!
interface Async1
no ip address
encapsulation slip
!
router bgp 65500
bgp router-id 1.1.1.1
bgp log-neighbor-changes
timers bgp 10 30
neighbor 1.2.3.4 remote-as 1234
neighbor 1.2.3.4 description Some Description
neighbor 1.2.3.4 update-source GigabitEthernet0/0
!
address-family ipv4
network 2.2.2.2 mask 255.255.255.255
network 3.3.3.0 mask 255.255.255.252
neighbor 1.2.3.4 activate
neighbor 1.2.3.4 allowas-in 3
neighbor 1.2.3.4 prefix-list PXL out
exit-address-family
!
ip forward-protocol nd
no ip http server
no ip http secure-server
!
我想从'router bgp'读取行,直到第一行以'!'开头(例如^!),然后重新读取该块以将参数提取到变量中。 示例输出为:
router bgp 65500
bgp router-id 1.1.1.1
bgp log-neighbor-changes
timers bgp 10 30
neighbor 1.2.3.4 remote-as 1234
neighbor 1.2.3.4 description Some Description
neighbor 1.2.3.4 update-source GigabitEthernet0/0
!
address-family ipv4
network 2.2.2.2 mask 255.255.255.255
network 3.3.3.0 mask 255.255.255.252
neighbor 1.2.3.4 activate
neighbor 1.2.3.4 allowas-in 3
neighbor 1.2.3.4 prefix-list PXL out
exit-address-family
!
注意:我可以使用awk或grep提取上述代码,但是我想将bash代码转换为Python。
谢谢!
答案 0 :(得分:1)
尝试一下:
from ciscoconfparse import CiscoConfParse
bgp = confparse.find_blocks(r"^router bgp 65500")
答案 1 :(得分:0)
由于有关于stackoverflow的另一篇文章,我找到了一种从运行config提取配置节的方法。帖子位于Reading a file for a certain section in python。
提取下面的“ router bgp”部分的工作代码:
bgp_found = False
bgp_section = []
with open('running-config', 'r') as f:
for line in f.readlines():
if 'router bgp' in line:
bgp_found = True
bgp_section.append(str(line).rstrip('\n')) # this will append the section start to list
continue
if bgp_found:
if line.startswith('!'): # this will test if line starts with '!'
bgp_found = False
else:
bgp_section.append(str(line).rstrip('\n'))
print (bgp_section) # just for testing purposes; list would be used to extract rest of parameters
希望对其他人也有用。