如何在Python中解析输出并在循环中使用它

时间:2018-05-22 10:51:39

标签: python paramiko

我需要提取' xe-1/2/0'来自以下UPD.result输出:

interface xe-1/2/0.0;
interface ge-1/2/1.0;
interface lo0.0 {

(这是从列表中的一个框中输出' show configuration protocols ospf | match int'命令)。

我使用netmiko库连接到网络设备并找到一些特定于OSPF协议的接口,然后我想检查这些接口上的错误计数。

import getpass
import sys
import time
import textfsm
import os
from tabulate import tabulate
import re


from netmiko import ConnectHandler

USER = raw_input("Login:")
PASSWORD = getpass.getpass()
FILENAME = raw_input("Name of file with results:")
GETPATH= os.getcwd()
GETPATH2 = (GETPATH+'/IP-ADD.txt')
GETPATH3 = (GETPATH+'/template-desc.template')

BOXES_IP = [line.strip() for line in open(GETPATH2, 'r')]
print(BOXES_IP)

for IP in BOXES_IP:
    print('CONNECTION TO DEVICE {}'.format(IP))
    try:
       DEVICE_PARAMS = {'device_type': 'juniper_junos',
                        'ip': IP,
                        'username':USER,
                        'password':PASSWORD,
                        'verbose': True}
        with ConnectHandler(**DEVICE_PARAMS) as sss:
            sss.enable()

            result = sss.send_command('show configuration protocols ospf| match int')
            hostname = sss.send_command('show configuration system host-name')
            print(result)
    except:
        print('CONNECTION TO DEVICE FAILS {}'.format(IP))
        continue

    f = open(FILENAME+'.txt', 'a')
    for row in hostname:
        f.write(row)
    for row in result:
        f.write(row)
    f.close()

    regex = re.compile(r'^(xe.[0-9].[0-9].[0-9])')
    results_list = [] 

    b = open(FILENAME+'.txt', 'r')
    print b
    for line in b:
        match = regex.search(line)
        if not match: continue
        results_list.append(match.group())
    print results_list

我需要解析命令'show configuration protocols ospf| match int'的输出并找到xe(例如xe-0/0/1)接口,然后输入'show interface xe-*** extensive'命令并将结果打印在文件中。

我该怎么做?

我试图用编译解析输出文件,但它不起作用。

更新。

print(result)

输出:

interface lo0.0 {
interface xe-1/3/1.0;
interface ge-1/2/0.0;
interface xe-1/3/0.0;

分裂的结果

    for l in result.split("\n"):
    l = l.split(" ")
    print l

[u'']
[u'', u'', u'', u'', u'interface', u'lo0.0', u'{']
[u'', u'', u'', u'', u'interface', u'xe-1/3/1.0;']
[u'', u'', u'', u'', u'interface', u'ge-1/2/0.0;']
[u'', u'', u'', u'', u'interface', u'xe-1/3/0.0;']
[u'']

2 个答案:

答案 0 :(得分:2)

恕我直言,regexp过度杀戮并且容易出错。 我会做类似的事情:

result ="""interface xe-1/2/0.0;
interface ge-1/2/1.0;
interface lo0.0 {
"""

for l in result.split("\n"):
    l = l.split(" ")
    if l[0] == "interface": # cause grep on "int"
        iface = l[1]
        if iface[0:3] == "xe-":
            arg=iface.split(".")[0]
            # do something with arg
            print(arg)

产生:

xe-1/2/0

答案 1 :(得分:1)

如果您想使用re,请执行此操作:

import re

output = '''interface xe-1/2/0.0;
interface ge-1/2/1.0;
interface lo0.0 {'''

print(re.findall('xe-\d/\d/\d', output))
#['xe-1/2/0']

要获得所需的输出,您可以使用:

for found in re.findall('xe-\d/\d/\d', output):
    print('show interface {} extensive'.format(found))