使用Paramiko的SSHClientInteraction发送SSH命令是否存在长度限制?
问题原因
该问题由APC UPS嵌入式SSH服务端的交互式输入缓冲区限制导致:设备单次接收输入的缓冲区上限为20字节,你通过send()方法一次性发送超过20字节的命令时,缓冲区溢出触发输入超时错误。手动SSH连接时,系统自带的SSH客户端会自动将长命令拆分为逐字符的小包发送,适配了设备的限制,因此不会出现该问题。
解决方案
你可以选择以下任意一种方案解决:
方案1:逐字符发送命令适配缓冲区限制
将一次性发送命令改为逐字符发送,每发送一个字符增加10ms延迟等待设备处理,最后单独发送回车符触发命令执行:
import paramiko import time from paramiko_expect import SSHClientInteraction host = "xxx.xxx.xxx.xxx" # UPS ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=host, username='e164468', password='********', banner_timeout=60) chan = SSHClientInteraction(ssh, timeout=2, display=True) prompt = 'apc>' command = 'cipher -rsake disable' chan.expect(prompt) # 逐字符发送命令 for char in command: chan.send(char) time.sleep(0.01) # 发送回车触发执行 chan.send('\n') chan.expect(prompt) output_raw = chan.current_output_clean chan.close() ssh.close() print ("Here is your output - ") print(output_raw)
方案2:使用sendline方法代替send
paramiko_expect提供的sendline()方法会自动在命令末尾追加换行符,且部分版本内置了长命令拆分逻辑,直接替换chan.send(command)为chan.sendline(command)即可在大多数场景下解决问题:
# 替换原有send逻辑 chan.sendline(command)
方案3:显式指定PTY参数
初始化SSHClientInteraction时主动指定终端类型和窗口宽度,避免设备按默认小窗口参数截断输入:
chan = SSHClientInteraction(ssh, timeout=2, display=True, term='vt100', width=100, height=50)
内容的提问来源于stack exchange,提问作者Flyersfan72
相关产品推荐
相关产品推荐

