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

使用Netmiko连接Cisco 2960X交换机遇Pattern Not Detected错误求助

解决Netmiko连接Cisco 2960X时的提示符匹配错误

问题原因

从session_log可以看到,执行configure terminal后交换机已进入配置模式,提示符变为Switch(config)#,但Netmiko默认仍在等待特权模式的Switch#提示符,导致匹配失败。另外代码中已通过connect.enable()进入特权模式,重复执行send_command('enable')属于冗余操作,会干扰提示符匹配逻辑。

解决方案

  • 移除冗余的send_command('enable')调用
  • 优先使用Netmiko的send_config_set方法执行配置命令,该方法会自动处理模式切换、提示符匹配和退出流程
  • 若坚持使用send_command,需手动指定expect_string参数匹配对应模式的提示符

修改后的代码示例(推荐方案)

from netmiko import ConnectHandler

network_device = {
    "host": "192.168.xxx.xxx",
    "username": "xxxx",
    "password": "xxxx",
    "device_type": "cisco_ios",
    "session_log": "netmiko_session.log"
}

connect = ConnectHandler(**network_device)
connect.enable()

interface_name = "GigabitEthernet1/0/10"

try:
    # send_config_set自动处理配置模式的进入与提示符匹配
    output = connect.send_config_set('configure terminal')
    print(output)
    # 可继续添加其他配置命令,例如:
    # connect.send_config_set(f'interface {interface_name}')
    # connect.send_config_set('switchport mode access')
except Exception as e:
    print(e)
    print("Failed!")
finally:
    # 记得断开连接
    connect.disconnect()

备选方案(手动指定提示符)

from netmiko import ConnectHandler

network_device = {
    "host": "192.168.xxx.xxx",
    "username": "xxxx",
    "password": "xxxx",
    "device_type": "cisco_ios",
    "session_log": "netmiko_session.log"
}

connect = ConnectHandler(**network_device)
connect.enable()

interface_name = "GigabitEthernet1/0/10"

def send_command_with_prompt(command, expect_prompt):
    return connect.send_command(command, expect_string=expect_prompt)

try:
    # 手动指定预期的配置模式提示符
    send_command_with_prompt('configure terminal', r'Switch\(config\)#')
    print("Successfully entered config mode")
except Exception as e:
    print(e)
    print("Failed!")
finally:
    connect.disconnect()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:10:50