Python正则表达式获取仅打印接口名称和状态

2024-10-02 00:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,在cisco设备上运行show interface status命令, 然后我只需要收集“connected”“notconnect”,并将其显示在接口名称旁边

到目前为止,我使用以下代码打印“已连接”和“未连接”状态,但是我需要接口名称

for host in hostlist:
    hostlist = host.strip()
    device = ConnectHandler(device_type=platform, ip=hostlist, username=username, password=password)
    output = device.send_command("show interface status")
    connectedregex = re.findall(r"connected", output)
    notconnectregex = re.findall(r"notconnect", output)
    print(host, connectedregex, notconnectregex)

不向数据应用任何python代码的示例输出

Port       Name                                           Status       Vlan
Et1                                                       connected    tap
Et2                                                       connected    tap
Et3                                                       connected    tap
Et4                                                       connected    tap
Et5                                                       connected    tap
Et6                                                       connected    tap
Et7                                                       connected    tap
Et8                                                       connected    tap
Et9                                                       notconnect   tap
Et10                                                      connected    tap
Et10/1                                                    notconnect   tap
Et10/2                                                    notconnect   tap

因此,我想打印例如:

Et1 - connected
Et2 - connected
Et9 - notconnect

Tags: 代码名称hostoutputdevicestatusshowusername
2条回答

您可以修改代码以使用regex,如下所示:

for host in hostlist:
    hostlist = host.strip()
    device = ConnectHandler(device_type=platform, ip=hostlist, username=username, password=password)
    output = device.send_command("show interface status")
    status = re.findall(r"connected", output) or re.findall(r"notconnect", output)
    print(f"{host} - {status}")

通过这种方式,您可以从使用or布尔运算符的短路计算中获益

我建议根本不要使用regexp。更简单的方法是:

for line in output.splitlines()[1:]:
    items = line.strip().split()
    print('{} - {}'.format(*items[:2]))

相关问题 更多 >

    热门问题