【问题标题】:Question with Netmiko and TextFSM against cisco IOSXENetmiko 和 TextFSM 针对 cisco IOSXE 的问题
【发布时间】:2022-10-15 01:51:46
【问题描述】:

尝试对 Cisco IOSXE 进行检查,以查看默认 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')

这确实有效,但对于 48 端口交换机,我得到 48 行表示符合或不符合。我怎样才能改变这一点,以便如果所有端口都在不同的 vlan 中,比如说 vlan 2,我会得到一行说投诉。如果 VLAN 1 中有任意数量的端口,无论是 1 个端口还是 10 个端口,我都会收到一行“不投诉”,而不是 48 行。

【问题讨论】:

    标签: python cisco netmiko python-textfsm


    【解决方案1】:

    你在这里有很多选择。我将尝试列举一些:

    • 将 for 循环移动到函数中
    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")
    

    在函数中使用return语句可以让代码停在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")
    

    感谢break 声明,我们将在第一个 vlan 1 匹配时退出 for 循环。

    • any 与生成器表达式一起使用
    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")
    

    any 函数也会在 Vlan 1 的第一个匹配时停止。


    该代码未经测试且不完美,但应该为您提供一些解决问题的想法

    【讨论】:

      【解决方案2】:

      如果在默认 VLAN (VLAN 1) 中配置了任何端口,上面的代码将打印出“Not Compliant”。要更改代码使其只打印一行,您可以使用条件语句:

      if any(i["vlan"] == "1" for i in output):
        print('Not Compliant')
      else:
        print('Compliant')
      

      【讨论】:

        猜你喜欢
        • 2020-05-08
        • 1970-01-01
        • 2018-09-20
        • 2021-11-12
        • 1970-01-01
        • 2016-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多