2014-11-25 82 views
0

我是一个新手解析。如何在python中解析CLI命令输出(表)?

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 

假设我有喷射开关上的命令的发动机,并把上述输出作为1个巨大串在名为“输出”变量。

我想返回一个字典,其中包括唯一的端口号如下:

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

我想我应该用Python`s子流程模块和正则表达式。

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

我会欣赏任何一种方向。

感谢,

Qwerty全

+0

为什么一本字典?如果你只有端口,那么为什么不使用一个集合或(更简单)的列表? – cdarke 2014-11-25 14:59:29

+0

我不太关心返回的数据结构。我不知道的是如何使用正则表达式和字符串函数来忽略/删除所有不相关的文本(不相关的标题名称,不相关的---,不相关的列值等)。 – Qwerty 2014-11-25 15:01:53

回答

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