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

Python遍历接口列表执行Cisco IOS命令的技术求助

问题需求

需要用Python完成以下操作:

  1. 执行第一条命令,筛选出符合指定描述的网络接口并加入列表
  2. 遍历该列表,对每个接口单独执行第二条命令

目前已完成第一步,但不清楚如何实现逐条调用列表项的逻辑,猜测需要用for循环,请求技术帮助。


现有Python代码

#!/usr/bin/env python3.4
from os.path import expanduser
import sys
import subprocess


# 定义变量
home = expanduser("~")
logincfg = home+"/.cloginrc"
source_device = input("Please enter network ID: ")
hub_vlans = home+"/"+"hub_vlans"+".cfg"


# 拉取设备配置,用于提取目标接口
cmd_one = "show interfaces description | include METRO - Ring"


# 通过clogin执行命令
output=subprocess.check_output(['clogin', '-f', logincfg, '-c', cmd_one, source_device])
file=open(home+"/"+"hub_vlans"+".cfg", "w")
for i in output.splitlines():
    i=i.decode("utf-8")
    file.write(i+"\n")
file.close  # 注意:这里缺少括号,正确写法是file.close()

# 提取RING接口并存入列表
ring_int_list = []
with open(hub_vlans) as file_out:
    for interface in file_out:
        if interface.startswith("Gi") or interface.startswith("Te"):
            i=interface.split(" ")
            print(i[0])
            ring_int_list.append(i[0])
print()
print('-' * 232)

# 打印接口列表
print(ring_int_list)
# 复制列表用于后续命令
interface_list = ring_int_list


# 此处为未完成的逻辑
cmd_two = "show run interface " + str(interface_list)
# let's utilie interface_list to run second command against for VLANs
# for int in list:
#     for interface in interface_list:
#         if ()
# this is where I'm lost on how to accomplish this

跳板机执行输出

[jsanch24@nlan scripts]$ "1.0 hub vlan script.py"
Gi2/10
Gi2/11
Gi2/13
Gi2/14
Gi2/15
Gi2/16
Gi2/17
Gi2/18
Gi2/19
Gi2/20
Gi2/21
Gi2/22
Gi2/23
Gi2/24
Gi3/10
Gi3/11
Gi3/13
Gi3/14
Gi3/15
Gi3/16
Gi3/17
Gi3/18
Gi3/19
Gi3/20
Gi3/21
Gi3/22
Gi3/23
Gi3/24

-------------------------------------------------------------------------------------------------------  ---------------------------------------------------------------------------------------------------------------------------------
['Gi2/10', 'Gi2/11', 'Gi2/13', 'Gi2/14', 'Gi2/15', 'Gi2/16', 'Gi2/17', 'Gi2/18', 'Gi2/19', 'Gi2/20', 'Gi2/21', 'Gi2/22', 'Gi2/23', 'Gi2/24', 'Gi3/10', 'Gi3/11', 'Gi3/13', 'Gi3/14', 'Gi3/15', 'Gi3/16', 'Gi3/17', 'Gi3/18', 'Gi3/19', 'Gi3/20', 'Gi3/21', 'Gi3/22', 'Gi3/23', 'Gi3/24'] 

解决方案

你猜测的for循环是正确的,直接遍历接口列表,为每个接口单独拼接并执行命令即可。把代码中未完成的部分替换为以下内容:

# 遍历接口列表,逐个执行查询命令
for interface in interface_list:
    # 为当前接口拼接专属命令(Python3.4不支持f-string,用format替代)
    cmd_two = "show run interface {}".format(interface)
    print("正在查询接口 {} 的配置...".format(interface))
    
    try:
        # 执行命令并获取输出
        output = subprocess.check_output(['clogin', '-f', logincfg, '-c', cmd_two, source_device])
        # 解码输出并打印
        print(output.decode("utf-8"))
        
        # 可选:将结果写入文件保存
        # with open(home+"/interface_configs.log", "a") as log_file:
        #     log_file.write("=== 接口 {} 配置 ===\n".format(interface))
        #     log_file.write(output.decode("utf-8") + "\n\n")
    except subprocess.CalledProcessError as e:
        print("查询接口 {} 失败: {}".format(interface, e))

额外优化点

  1. 原代码中file.close缺少括号,正确写法是file.close(),更推荐用with open语法自动管理文件:
# 替换原文件写入代码
with open(hub_vlans, "w") as file:
    for i in output.splitlines():
        i = i.decode("utf-8")
        file.write(i + "\n")
  1. 增加异常处理,避免单个接口查询失败导致整个脚本终止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:58:17