2017-06-21 96 views
0

我創建了一個類來解析命令的輸出並返回所需的字符串。我使用了正則表達式來獲取所需的字符串。目前形式的班級服務於此目的。但是,我想通過解析整個命令輸出並將其存儲在字典中來提高效率。將命令的輸出保存在Python字典中

本質上,我想根據「:」分割輸出,並以鍵值對的形式存儲整個輸出。

輸出看起來象下面這樣:

Interface: gig1 
Profile: 
Session status: ACTIVE 
Peer: x.x.x.x port 7500 
    Session ID: 5 
    v2 SA: local x.x.x.x/4500 remote x.x.x.x/4500 Active 
    FLOW: permit 47 host 2.2.2.2 host 1.1.1.1 

從test.ssh進口噓 進口重新

class crypto: 
    def __init__(self, username, ip, password ,router): 
     self.user_name = username 
     self.ip_address = ip 
     self.pass_word = password 
     self.machine_type = router 

    def session_status(self, interface): 
     command = 'show session '+interface 
     router_ssh = Ssh(self.ip_address) 
     result = router_ssh.cmd(command) 
     search_obj = re.search("Session status:\s+(.*)", result, flags=0) 
     return search_obj.group(1) 

測試腳本

from test.networks.router_parser import * 

routerobj = crypto('user', 'ip', 'password', 'cisco') 
status = routerobj.session_status('interface_name') 
print (status) 
+0

如果你想以':'字典的形式存儲'result',我們可能需要另一個splitter來鍵值對嗎? –

+0

@be_good_do_good是的,我想根據下面的內容在表單字典中存儲命令輸出的結果: – mike

回答

0
resultDict = dict(line.split(':', 1) 
    for line in result.split('\n') if ':' in line) 

爲了擺脫尾隨的和領先空間:

resultDict = dict(map(str.strip, line.split(':', 1)) 
    for line in result.split('\n') if ':' in line) 
+0

您能告訴我如何從測試腳本訪問字典。例如,我想在測試腳本中打印會話狀態,我該怎麼做?另外,session_status()應該返回什麼? – mike

+0

'print resultDict ['Session status']''和'return resultDict ['Session status']'。 – Alfe

+0

謝謝,我想以字典的形式返回整個輸出並訪問測試腳本中的鍵值對。所以我可以返回整個字典,返回resultDict []。它是否正確 ? – mike