如何在python中解析CLI命令输出(表)?

时间:2014-11-25 14:53:51

标签: python parsing

我是解析新手。

switch-630624 [standalone: master] (config) # show interface ib status

Interface      Description                                Speed                   Current line rate   Logical port state   Physical port state
---------      -----------                                ---------               -----------------   ------------------   -------------------
Ib 1/1                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/2                                                    14.0 Gbps rate          56.0 Gbps           Initialize           LinkUp
Ib 1/3                                                    2.5 Gbps rate only      10.0 Gbps           Down                 Polling

假设我有一个引擎在开关上注入命令,并将上面的输出作为一个巨大的字符串放在一个名为“output”的变量中。

我想返回一个只包含端口号的字典,如下所示:

{'Ib1/11': '1/11', 'Ib1/10': '1/10', ... , }

我想我应该使用Python的Subprocess模块​​和正则表达式。

端口数量可以变化(可以是3,10,20,30,60 ......)。

我会欣赏任何方向。

谢谢,

的Qwerty

1 个答案:

答案 0 :(得分:1)

# Did this in Python 2.7
import re

# Assume your input is in this file
INPUT_FILE = 'text.txt'

# Regex to only pay attention to lines starting with Ib
# and capture the port info
regex = re.compile(r'^(Ib\s*\S+)')
result = [] # Store results in a list
with open(INPUT_FILE, 'r') as theFile:
  for line in theFile:
    match = regex.search(line)
    if not match: continue
    result.append(match.group())
print result