pythoncisconetmikopython-textfsm

Question with Netmiko and TextFSM against cisco IOSXE


Trying to do a check against Cisco IOSXE to see if any ports are still configured in the default VLAN.

Output = net_connect.send_command ('show int status', use_textfsm=true)
for i in output:
  if i["vlan"] == "1":
    print ('Not compliant')
  else:
    print ('Compliant')

This does work, but for a 48 port switch, I get 48 lines saying Compliant or Not Compliant. How can I change this so that if all ports are in a different vlan, lets say vlan 2, I get one line saying Complaint. And if ANY number of ports are in VLAN 1 , whether is be 1 port or 10 ports, I get one line saying "Not complaint", instead of 48 lines.


Solution

  • You have many options here. I will try to name some:

    def check_complaint(output):
      for i in output:
        if i["vlan"] == "1":
          return False
      return True
    
    output = net_connect.send_command ('show int status', use_textfsm=true)
    if check_complaint(output):
      print("Compliant")
    else:
      print("Not Compliant")
    

    Using the return statement in the functions allows the code to stop at the first interface in vlan 1

    output = net_connect.send_command ('show int status', use_textfsm=true)
    compliant = True
    for i in output:
      if i["vlan"] == "1":
        compliant = False
        break
    
    if compliant:
        print("Compliant")
    else:
        print("Not Compliant")
    

    Thanks to the break statment we will exit the for loop at the first vlan 1 match.

    output = net_connect.send_command ('show int status', use_textfsm=true)
    if any(i["vlan"] == "1" for i in output):
        print("Not Compliant")
    else:
        print("Compliant")
    

    The any function will also stop at the first match of Vlan 1.


    The code is not tested and not perfect but should give you some ideas how to solve your problem