我创建了一个类来解析命令的输出并返回所需的字符串。我使用了正则表达式来获取所需的字符串。当前形式的类服务于此目的。但是,我希望通过解析整个命令输出并将其存储在字典中来提高效率。
基本上,我想基于"分割输出。 :"并以键值对的形式存储整个输出。
输出如下所示:
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)
答案 0 :(得分: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)