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

如何通过Netmiko实现SSH连接网络设备时自动输入Yes/No以完成命令执行

解决Netmiko执行命令时自动响应Yes/No确认的问题

这个问题我之前写网络自动化脚本时也碰到过,Netmiko处理这种交互式确认其实有几种靠谱的方案,你可以根据场景选:

方法1:用send_command的expect_string精准匹配确认提示

这种方法最可靠,它会主动匹配命令执行后出现的确认字符串,再自动发送响应,适合你明确知道确认提示格式的场景。

示例代码:

from netmiko import ConnectHandler

# 替换成你的设备实际信息
device = {
    'device_type': 'cisco_ios',  # 比如huawei、juniper等,根据设备类型调整
    'ip': '192.168.1.1',
    'username': 'admin',
    'password': 'your_password',
}

with ConnectHandler(**device) as conn:
    # 执行需要确认的命令,匹配大小写不敏感的Yes/No提示
    initial_output = conn.send_command(
        command_string='show running-config',
        expect_string=r'[Yy][Ee][Ss]/[Nn][Oo]',
        strip_prompt=False,
        strip_command=False
    )
    # 发送"Yes"响应,匹配设备提示符(比如#、>)
    final_output = initial_output + conn.send_command(
        command_string='Yes',
        expect_string=r'#',  # 换成你的设备实际提示符
        strip_prompt=False,
        strip_command=False
    )

print(final_output)

方法2:用send_command_timing基于时间等待处理交互

如果不确定确认提示出现的准确时机,或者设备提示格式不太固定,send_command_timing会在发送命令后等待一段时间,检查输出里的确认提示后再发送响应。

示例代码:

from netmiko import ConnectHandler

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

with ConnectHandler(**device) as conn:
    # 发送命令并等待输出
    output = conn.send_command_timing('show running-config')
    # 检查输出是否包含常见确认提示
    if any(confirm in output for confirm in ['Yes/No', 'yes/no', 'Are you sure']):
        # 发送"Yes"获取后续输出
        output += conn.send_command_timing('Yes')

print(output)

方法3:提前配置设备关闭确认提示

如果脚本需要长期执行,或者很多命令都有确认提示,最省心的方式是先给设备发送关闭确认的命令,后续执行命令就不会再弹出Yes/No提示了。

不同设备的关闭命令不一样,举几个常见例子:

  • Cisco IOS:terminal no confirm
  • Huawei:undo terminal prompt
  • Juniper:set cli confirm off

示例代码:

from netmiko import ConnectHandler

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

with ConnectHandler(**device) as conn:
    # 先关闭设备的确认提示(根据你的设备修改命令)
    conn.send_command('terminal no confirm')
    # 现在执行任何需要确认的命令都不会有交互了
    output = conn.send_command('show running-config')

print(output)

小提醒

不同设备的确认提示格式可能有差异,比如有些是Are you sure? [yes/no],你需要调整正则或者判断条件来匹配;用正则的话,尽量写得通用些,比如r'[Yy]es/[Nn]o'能匹配大小写混合的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:58:15