2014-11-25 49 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