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

通过Paramiko提交远程输入时如何为变量值添加换行符

问题原因

代码存在两个直接导致enable密码校验失败、返回"bad secrets"报错的问题:

  1. 发送enable密码时传入的是字符串字面量'passwordE',并非通过getpass获取到的存储密码的变量passwordE,相当于向路由器发送了固定字符"passwordE"作为密码,必然校验不通过。
  2. 发送密码内容时没有在末尾追加\n换行符,思科路由器的交互shell无法收到密码提交的完成信号,不会触发校验流程。
修复方案

修正变量引用方式,在发送的密码内容末尾拼接换行符即可。建议在每条命令发送后增加短暂等待时间,避免设备响应延迟导致命令发送错位,修复后的完整可运行代码如下:

#!/bin/python3
import paramiko
import time
import getpass

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

password = getpass.getpass('Enter SSH login password: ')
# port参数改为整数类型,避免Paramiko版本兼容问题
router = {'hostname': '192.168.142.132', 'port': 22, 'username':'user', 'password': password}

print(f"Connecting to {router['hostname']} ")
ssh_client.connect(**router, look_for_keys=False, allow_agent=False)
shell = ssh_client.invoke_shell()
# 等待登录后初始欢迎信息加载完成
time.sleep(1)
shell.send('enable\n')
# 等待设备返回enable密码输入提示
time.sleep(0.5)
passwordE = getpass.getpass('Enter the enable password:')
# 直接传入密码变量,末尾拼接换行符,注意不要给变量加引号
shell.send(passwordE + '\n')

# 可选:验证是否成功进入特权模式
time.sleep(1)
shell.send('show privilege\n')
time.sleep(0.5)
print(shell.recv(65535).decode('utf-8'))

ssh_client.close()
补充说明
  • 如果需要直接把换行符存在密码变量中,也可以在getpass赋值时直接拼接:passwordE = getpass.getpass('Enter the enable password:') + '\n',后续直接调用shell.send(passwordE)即可,效果完全一致。
  • Paramiko的交互式shell不会自动等待设备返回响应,网络设备运维场景下,每条命令发送后加0.5-1秒的等待是通用写法,等待时长可根据设备实际响应速度调整。
  • 不要给传入send()方法的变量加单/双引号,加引号后Python会将其识别为固定字符串,而非预先定义的变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:06:32