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

如何用Python批量读取Cisco设备IP并保存命令输出?

批量处理Cisco设备SSH连接并保存命令输出的实现方法

核心思路是把单台设备的操作逻辑封装成可复用的函数,遍历从devices.txt读取的IP列表,逐个执行操作并将结果写入同一个文件,同时加入异常处理避免单个设备出错导致程序中断。

完整实现代码

import paramiko

def get_route_output(device_ip, username, password, command="sh ip route"):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    output_content = f"=== 设备 {device_ip} 的路由表输出 ===\n"
    
    try:
        # 连接设备,设置10秒超时避免长时间等待
        ssh.connect(device_ip, username=username, password=password, timeout=10)
        # 执行指定命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 读取命令输出并转成字符串(适配Cisco设备的字符编码)
        command_output = stdout.read().decode('utf-8')
        # 读取错误信息(如果命令执行出错)
        error_output = stderr.read().decode('utf-8')
        
        if command_output:
            output_content += command_output
        if error_output:
            output_content += f"\n错误信息:{error_output}"
            
    except Exception as e:
        output_content += f"\n连接/执行命令失败:{str(e)}"
    finally:
        # 确保无论成功失败都关闭连接
        if ssh.get_transport() and ssh.get_transport().is_active():
            ssh.close()
            output_content += "\n连接已关闭\n"
        # 用分隔线区分不同设备的输出
        output_content += "\n" + "-"*50 + "\n\n"
        return output_content

if __name__ == "__main__":
    # 替换为你的实际登录信息
    USERNAME = "cisco"
    PASSWORD = "xxxxxxx"
    # 结果保存的文件名
    OUTPUT_FILE = "all_routes.txt"
    
    # 读取devices.txt中的IP列表,自动过滤空行
    try:
        with open("devices.txt", "r") as f:
            device_ips = [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        print("错误:未找到devices.txt文件,请确保该文件和脚本在同一目录")
        exit()
    
    # 打开输出文件(覆盖写入,若需要追加可改为"a")
    with open(OUTPUT_FILE, "w", encoding="utf-8") as output_f:
        for ip in device_ips:
            print(f"正在处理设备 {ip}...")
            device_result = get_route_output(ip, USERNAME, PASSWORD)
            output_f.write(device_result)
    
    print(f"所有设备处理完成,结果已保存至 {OUTPUT_FILE}")

关键说明

  • 函数封装:将单台设备的SSH连接、命令执行、结果收集逻辑封装成函数,便于复用和维护。
  • IP列表读取:通过列表推导式读取devices.txt,自动过滤空行和多余的换行符,避免处理无效IP。
  • 异常处理:捕获连接超时、认证失败、命令执行错误等异常,保证单个设备出错时程序能继续处理其他设备,同时记录错误信息。
  • 输出格式化:每个设备的输出前添加标识,用分隔线区分,方便后续查看不同设备的结果。
  • 连接管理:在finally块中确保连接关闭,避免资源泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:35:33