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

使用Paramiko获取Cisco交换机配置遇无效自动命令报错

Cisco交换机SSH配置获取报错分析与优化方案

报错原因解析

你遇到的Line has invalid autocommand "show running-config\r\n"错误,核心原因是Cisco IOS/IOS-XE的SSH服务对paramiko.exec_command的执行模式兼容性差,具体有几点:

  • Cisco设备的SSH默认将exec_command传入的命令当作autocommand执行,而autocommand不允许包含换行符,也不支持需要交互式环境的命令(比如需要先进入特权模式的操作)。
  • 不同厂商设备的SSH命令执行逻辑差异:H3C设备支持直接通过exec_command执行一次性命令,但Cisco更依赖交互式shell会话,而非一次性命令执行。
  • 即使调整换行符为\r\n,也无法改变exec_command的执行模式,因此报错无法解决。

解决方向

  1. 采用交互式shell会话:使用paramiko.invoke_shell()模拟手动登录设备的交互流程,这是适配Cisco设备的标准方式。
  2. 避免固定时间等待:替换time.sleep()为检测设备提示符(比如#或>),确保命令执行完成后再读取输出,避免因设备响应慢导致输出不完整。
  3. 简化输出处理:无需手动解析转义字符,直接处理原始字节流,转换为字符串后按换行分割即可。
  4. 使用专业网络自动化库:比如Netmiko(基于Paramiko封装),它内置了不同厂商设备的交互逻辑,能大幅简化代码。

优化后的代码示例

方案1:优化Paramiko交互式代码

import paramiko

sw_ip = "****"
sw_username = "****"
sw_password = "****"
enable_password = "****"  # 如果需要特权模式密码
port = 22

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=sw_ip, username=sw_username, password=sw_password, port=port, look_for_keys=False, allow_agent=False)

# 启动交互式shell
shell = ssh.invoke_shell(height=1000)

# 等待用户模式提示符出现
while not shell.recv_ready():
    pass
output = shell.recv(65535).decode()

# 进入特权模式
if ">" in output:
    shell.send("enable\n")
    # 等待输入enable密码的提示
    while not "Password:" in output:
        output += shell.recv(65535).decode()
    shell.send(f"{enable_password}\n")
    # 等待特权模式提示符#出现
    while not "#" in output:
        output += shell.recv(65535).decode()

# 发送获取配置命令
shell.send("show running-config\n")
# 等待命令执行完成,直到再次出现特权提示符
while not "#" in output:
    output += shell.recv(65535).decode()

ssh.close()

# 处理输出,提取配置内容
config_start = output.find("!")
config_end = output.rfind("#")
config_content = output[config_start:config_end].strip()

# 保存到文件
with open("cisco_config.txt", "w") as f:
    f.write(config_content)

print("配置已成功保存!")

方案2:使用Netmiko简化代码

先安装Netmiko:pip install netmiko

from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "ip": sw_ip,
    "username": sw_username,
    "password": sw_password,
    "secret": enable_password,  # 特权模式密码
}

# 连接设备并获取配置
with ConnectHandler(**device) as conn:
    conn.enable()  # 进入特权模式
    config = conn.send_command("show running-config")

# 保存配置
with open("cisco_config.txt", "w") as f:
    f.write(config)

print("配置已成功获取并保存!")

关键优化点

  • 用提示符检测替代固定time.sleep,保证输出完整且效率更高。
  • 直接通过字节流解码处理输出,避免手动解析转义字符的繁琐操作。
  • Netmiko方案完全封装了厂商交互逻辑,代码简洁且稳定性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:45:38