将命令的输出保存在 python 字典中

Save the output of the command in python dictionary

我创建了一个 class 来解析命令的输出,并且 return 所需的 string.I 已使用正则表达式来获取所需的字符串。当前形式的 class 服务于此目的。但是,我想通过解析整个命令输出并将其存储在字典中来提高效率。

本质上,我想根据“:”拆分输出,并将整个输出以键值对的形式存储。

输出如下所示:

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 导入 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)
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)