无法正确解析cisco cli命令输出

时间:2016-08-01 07:35:12

标签: python regex parsing

我试图通过逐行读取来解析来自txt文件的Cisco // api.ts import { Foo as MyFoo } from "./lib/foo"; import { Bar as MyBar } from "./lib/bar"; export namespace MyModule { export const Foo = MyFoo; export type Foo = MyFoo; export namespace MySubModule { export const Bar = MyBar; export type Bar = MyBar; } } 命令输出。

输出结果为:

show ip interface vrf all

等等。

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

IP Interface Status for VRF "default"
loopback1, Interface status: protocol-up/link-up/admin-up, iod: 212,
IP address: 10.1.0.1, IP subnet: 10.1.0.0/30
...

Ethernet1/1, Interface status: protocol-up/link-up/admin-up, iod: 278,
  IP address: 10.0.0.1, IP subnet: 10.0.0.0/30

IP Interface Status for VRF "TEST"
Vlan99, Interface status: protocol-up/link-up/admin-up, iod: 147,
  IP address: 172.16.0.1, IP subnet: 172.16.0.0/24
  ...
Vlan888, Interface status: protocol-up/link-up/admin-up, iod: 115,
  IP address: 172.16.1.1, IP subnet: 172.16.1.0/24
...

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

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

default vrf

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

1 个答案:

答案 0 :(得分:0)

您可以使用以下表达式:

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

<小时/> 在Python代码中:

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

<小时/> 请参阅a demo on regex101.com