You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

优化Netmiko+TextFSM检测Cisco IOSXE端口VLAN合规性输出

优化Cisco IOSXE端口VLAN合规性检测代码

需求说明

原本代码执行show int status并通过TextFSM解析后,会针对每个端口单独输出"Compliant"或"Not compliant"。现在需要修改为:

  • 若所有端口均不在默认VLAN1(比如都在VLAN2),仅输出一行Compliant
  • 只要存在任意数量端口在VLAN1,仅输出一行Not compliant

修改思路

  • 执行命令并解析输出后,不再逐个输出结果,而是先遍历所有端口的VLAN信息
  • 设置一个标记变量,用来记录是否存在VLAN1的端口
  • 遍历过程中一旦发现VLAN1的端口,立即标记并终止遍历(提升效率)
  • 最后根据标记值输出全局合规状态

代码示例

原代码逻辑(供对比)

from netmiko import ConnectHandler
from textfsm import TextFSM

device = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
}

conn = ConnectHandler(**device)
output = conn.send_command('show int status')
conn.disconnect()

template = TextFSM(open('cisco_ios_show_int_status.template'))
parsed_data = template.ParseText(output)

# 逐个端口输出结果
for port in parsed_data:
    port_name = port[0]
    vlan = port[3]  # 索引根据实际模板调整
    if vlan == '1':
        print(f"{port_name}: Not compliant")
    else:
        print(f"{port_name}: Compliant")

修改后的代码

from netmiko import ConnectHandler
from textfsm import TextFSM

device = {
    'device_type': 'cisco_ios',
    'ip': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
}

# 连接设备获取命令输出
conn = ConnectHandler(**device)
output = conn.send_command('show int status')
conn.disconnect()

# TextFSM解析输出
template = TextFSM(open('cisco_ios_show_int_status.template'))
parsed_data = template.ParseText(output)

# 全局合规性判断
has_vlan1 = False
for port in parsed_data:
    vlan = port[3]  # 注意:需根据你的TextFSM模板调整VLAN字段的索引
    if vlan == '1':
        has_vlan1 = True
        break  # 找到VLAN1端口后直接终止遍历

# 输出最终结果
print("Not compliant" if has_vlan1 else "Compliant")

关键说明

  • 必须确认TextFSM模板中VLAN字段的索引位置,不同模板的字段顺序可能不同,需对应调整port[3]的数字
  • 使用break提前终止遍历可以减少不必要的计算,尤其是在端口数量较多的设备上

内容的提问来源于stack exchange,提问作者Jimmy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:41:55