简体   繁体   English

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

[英]Save the output of the command in python dictionary

I have created a class to parse the output of the command and return the desired string.I have used regex to get the required string. 我创建了一个类来解析命令的输出并返回所需的字符串。我使用了正则表达式来获取所需的字符串。 The class in its current form servers the purpose. 当前形式的类用于目的。 However, I'd like to make it more efficient by parsing the entire command output and storing it in a dictionary. 但是,我想通过解析整个命令输出并将其存储在字典中来提高效率。

Essentially,I want to split the output based on " : " and store the entire output in the form of key value pair. 本质上,我想基于“:”分割输出,并以键值对的形式存储整个输出。

Output looks like below : 输出如下:

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

from test.ssh import Ssh import re 从test.ssh import Ssh import re

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)

test script 测试脚本

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)

To get rid of trailing and leading spaces: 要摆脱尾随和前导空格:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM