如何在python脚本中解析列格式的文本以给出特定的输出

时间:2018-09-16 18:02:37

标签: python python-3.x

我是python脚本的新手,试图解析以下以列格式显示的命令输出以显示:

要解析的文本:

    Neighbor        V           AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
10.0.10.101     4         1024      80      87        1    0    0 01:17:25        0
10.0.11.101     4         1024      92      91        1    0    0 down        0

输出格式:

Neighbor:10.0.10.101 is up
Neighbor:10.0.11.101 is down

编辑-1 感谢您的建议,我在前面的注释中提到的代码是cisco switch中命令的动态输出,这是下面的代码,当我运行此脚本时,它需要动态读取列格式的输出并显示给我如果邻居状态为up或down,则邻居状态不是恒定的,它将从up或down更改,如果状态为up,则将显示时间(示例-01:17:25)或为down字符串'down'将显示在输出中

from __future__ import print_function
from netmiko import ConnectHandler

import sys
import time
import select
import paramiko
import re
status = open(r'E:\\Python-Scripts\\bgp-status.txt','w')
old_stdout = sys.stdout
sys.stdout = status
host = '10.0.10.100'
platform = 'cisco_ios'
username = 'javed'
password = 'cisco'
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
output = device.send_command('enable')
bgp_status = device.send_command('show ip bgp summary | be N')


for neighbor_status in bgp_status.split('\n'):
    if 'down' in neighbor_status:
        print(f"{neighbor_status} is down")
    else:
        print('All neighbors are up')
        break
status.close()

1 个答案:

答案 0 :(得分:0)

感谢所有评论了他们建议的人,我经过一些研究后编写了该脚本,希望该脚本将来对像我这样的网络工程师有所帮助:

import pandas as pd
data = pd.read_csv('E:\\Python-Scripts\\bgp-status.txt', delim_whitespace=True , header=None)
for index, row in data.iterrows():
    if row[8] == 'Down':
        print (f"Neighbor {row[0]} is down")
    else:
        pass

如果关闭,将给出BGP邻居的输出:

示例:

邻居10.0.11.101关闭

邻居10.0.10.103关闭