Python Can';无法正确分析cisco cli命令输出

Python Can';无法正确分析cisco cli命令输出,python,regex,parsing,Python,Regex,Parsing,我试图通过逐行读取循环中的内容来解析txt文件中的Cisco显示ip接口vrf all命令输出 输出为: VRF“默认”的IP接口状态 环回1,接口状态:协议启动/链路启动/管理启动,iod:212, IP地址:10.1.0.1,IP子网:10.1.0.0/30 ... Ethernet1/1,接口状态:协议启动/链路启动/管理启动,iod:278, IP地址:10.0.0.1,IP子网:10.0.0.0/30 VRF“测试”的IP接口状态 Vlan99,接口状态:协议启动/链路启动/管理员启动

我试图通过逐行读取循环中的内容来解析txt文件中的Cisco
显示ip接口vrf all
命令输出

输出为:

VRF“默认”的IP接口状态 环回1,接口状态:协议启动/链路启动/管理启动,iod:212, IP地址:10.1.0.1,IP子网:10.1.0.0/30 ... Ethernet1/1,接口状态:协议启动/链路启动/管理启动,iod:278, IP地址:10.0.0.1,IP子网:10.0.0.0/30 VRF“测试”的IP接口状态 Vlan99,接口状态:协议启动/链路启动/管理员启动,iod:147, IP地址:172.16.0.1,IP子网:172.16.0.0/24 ... Vlan888,接口状态:协议启动/链路启动/管理员启动,iod:115, IP地址:172.16.1.1,IP子网:172.16.1.0/24 ... 等等

我只需要提取具有VLAN和子网的VRF。 例如,从这个输出中,我应该在每次迭代中都有变量:

vrf -> vlan -> subnet (TEST -> 99 -> 172.16.0.0/24)
vrf -> vlan -> subnet (TEST -> 888 -> 172.16.1.0/24)
但是我不需要来自
默认vrf
的信息,因为它没有VLAN

我编写了一些正则表达式来查找此信息:

   vrf = re.findall( r'VRF "(.*)"', line)
   vlan = re.findall( r'Vlan(\d+)', line)
   subnet= re.findall( r'IP address.*subnet:\s(.*)$', line)

但我不知道如何忽略没有VLAN的VRF。

您可以使用以下表达式:

^(Vlan\d+).+[\n\r]
.+?subnet:\ (.+)

Python
code中:

import re
rx = re.compile("""
    ^(Vlan\d+).+[\n\r] # capture Vlan, followed by digits at the beginning of line
    .+?subnet:\ (.+)   # match anything lazily, followed by subnet and capture the address
    """,re.MULTILINE|re.VERBOSE)

for match in rx.finditer(your_string_here):
    print match.group(1) # Vlan99
    print match.group(2) # the subnet ip


请参见。

您可以使用以下表达式:

^(Vlan\d+).+[\n\r]
.+?subnet:\ (.+)

Python
code中:

import re
rx = re.compile("""
    ^(Vlan\d+).+[\n\r] # capture Vlan, followed by digits at the beginning of line
    .+?subnet:\ (.+)   # match anything lazily, followed by subnet and capture the address
    """,re.MULTILINE|re.VERBOSE)

for match in rx.finditer(your_string_here):
    print match.group(1) # Vlan99
    print match.group(2) # the subnet ip


请参阅。

您希望得到的最终结果是什么?我需要在遍历行时将所有vrf及其vlan编号和子网插入mysql。您希望得到的最终结果是什么?在遍历行时,我需要将所有vrf及其vlan编号和子网插入mysql。这是可行的,但我还需要提取vrf名称。我试图更改此表达式:VRF\“(.*)”[\n\r]Vlan(\d+)+[\n\r]。+?子网:\(.+),但它只找到VRF、第一个Vlan和第一个子网,但在上有两个或更多VlanVRF@Jegor:请提供准确的输出(即编辑您的原始问题)。它正在工作,但我还需要提取vrf名称。我试图更改此表达式:VRF\“(.*)”[\n\r]Vlan(\d+)+[\n\r]。+?子网:\(.+),但它只找到VRF、第一个Vlan和第一个子网,但在上有两个或更多VlanVRF@Jegor:请提供准确的输出(即编辑原始问题)。