简体   繁体   中英

Python - Regex get Print only Interface name and status

I'm writing a script that runs a show interface status command on a cisco device, I then need to collect just the "connected" "notconnect" and display this next to their interface name

I am using the following code so far to print the "connected" and "notconnect" status, however i need the interface name

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)

Sample output without applying any python code to the data

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

So i would like to print for example:

Et1 - connected
Et2 - connected
Et9 - notconnect

I suggest not using regexps at all. A much simpler way is:

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

You could modify your code to use regex like this:

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}")

This way you can benefit from the short-circuiting evaluation with the or boolean operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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