从开关输出中提取python

时间:2010-04-15 07:50:56

标签: python text parsing

我从LAN交换机获得了一些信息,如下所示

Vlan 1 is administratively down, line protocol is down  
Vlan 2 is up, line protocol is up  
  Helper address is 192.168.0.2  
Vlan 3 is up, line protocol is up  
  Helper address is not set  
Vlan 4 is up, line protocol is up  
  Helper address is 192.168.0.2  
Vlan 5 is down, line protocol is down  
  Helper address is 192.168.0.2  
Vlan 6 is down, line protocol is down  
  Helper address is not set  
  Helper address is not set

我正在尝试的输出是

Vlan 1,admin down,n/a
Vlan 2,up/up, 192.168.0.2
Vlan 3, up/up, not set
Vlan 4, up/up, 192.168.0.2
Vlan 5, down/down, 192.168.0.2
Vlan 6, down/down, not set

所以助手并不总是在那里(第1行)有时它的设置有时它不是,有时候有两行(最后一个Vlan - 我只需要1个)

并且Vlan可以具有admin down,up / up,up / down(不是这里)和down down状态。

所以使用Python和pexpect我可以获得上面的输出,但是我在解析连续的行时遇到了困难。我已经尝试枚举,然后使用键+ 1作为下一行,但事实是Vlan后面可能有0或2行螺丝我。 有什么想法吗?

4 个答案:

答案 0 :(得分:1)

import re

x="""
Vlan 1 is administratively down, line protocol is down  
Vlan 2 is up, line protocol is up  
  Helper address is 192.168.0.2  
Vlan 3 is up, line protocol is up  
  Helper address is not set  
Vlan 4 is up, line protocol is up  
  Helper address is 192.168.0.2  
Vlan 5 is down, line protocol is down  
  Helper address is 192.168.0.2  
Vlan 6 is down, line protocol is down  
  Helper address is not set  
  Helper address is not set
"""

x=x.replace(" is administratively down, line protocol is down  ",", admin down, n/a")
x=x.replace(" line protocol is ","")
x=x.replace(" is down,",", down/")
x=x.replace(" is up,",", up/")
x=re.sub("(?:\s*Helper address is (.*))+",", \\1",x)

print x

Vlan 1, admin down, n/a
Vlan 2, up/up, 192.168.0.2
Vlan 3, up/up, not set
Vlan 4, up/up, 192.168.0.2
Vlan 5, down/down, 192.168.0.2
Vlan 6, down/down, not set

答案 1 :(得分:0)

区分感兴趣的行(以'Vlan'开头;或不是):

for line in lines:
    if line.startswith("Vlan"):
        # parse Vlanline
        # ...
    else:
        # parse data from helper line
        # ...

答案 2 :(得分:0)

这是一种方式,

import re    
data=open("file").read()
r=re.split("\n[^ \t]+",data)
for i in r:
  print "-->",i.split("\n")

$ ./python.py
--> ['Vlan 1 is administratively down, line protocol is down  ']
--> [' 2 is up, line protocol is up  ', '  Helper address is 192.168.0.2  ']
--> [' 3 is up, line protocol is up  ', '  Helper address is not set  ']
--> [' 4 is up, line protocol is up  ', '  Helper address is 192.168.0.2  ']
--> [' 5 is down, line protocol is down  ', '  Helper address is 192.168.0.2  ']
--> [' 6 is down, line protocol is down  ', '  Helper address is not set  ', '  Helper address is not set', '']

现在您可以操作每个项目,因为它们已经组合在一起

答案 3 :(得分:0)

ghostdog给了我一个解决方案的线索

首先,我将表枚举成字典 然后一步一步。如果该行以VLAN开头,那么我可以测试行+ 1等以查看它是否是帮助行

然后将它们全部输出为一行并根据需要将其切片

不是最干净的方式,但是工作并感谢所有人的帮助