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

Cisco UCS服务器SSH执行命令:Paramiko发送Enter键无效,手动正常

解决Paramiko执行Cisco UCS确认命令无响应的问题

问题核心

用Paramiko的invoke_shell登录Cisco UCS服务器后,执行power on命令时需要输入y回车确认,但通过sendall("y\r\n")无法触发服务器的确认操作——手动终端操作完全正常,换用\n/\r也没效果。

问题根源

固定的time.sleep()不可靠,服务器返回确认提示符的时间会受网络延迟、负载影响,导致发送y时服务器还没准备好接收输入,等于白发。

解决方案

别用固定sleep,改成等目标提示符出现后再发指令,确保服务器处于可接收输入的状态。

修改后的代码

import paramiko
import time

def wait_for_prompt(shell, prompt, timeout=30):
    shell.settimeout(timeout)
    output = b""
    while True:
        try:
            data = shell.recv(1024)
            output += data
            if prompt.encode() in output:
                return output
        except paramiko.SSHException:
            break
    return output

ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password)
ucs = ssh.invoke_shell()

# 等初始提示符(比如hostname#)出现
wait_for_prompt(ucs, "#")

# 执行scope chassis,等进入chassis上下文的提示符
ucs.sendall('scope chassis\r\n')
wait_for_prompt(ucs, "/chassis #")

# 执行power on,等确认提示符出现
ucs.sendall('power on\r\n')
wait_for_prompt(ucs, "Do you want to continue?[y|N]")

# 发送确认指令,等回到chassis上下文提示符
ucs.sendall('y\r\n')
wait_for_prompt(ucs, "/chassis #")

# 执行show命令,等输出返回
ucs.sendall('show\r\n')
time.sleep(2)
output = ucs.recv(4096)

# 保存输出
with open("Output.txt", "ab") as text_file:
    text_file.write(output)
with open("temp2", "wb") as text_file:
    text_file.write(output)

ssh.close()

关键改进点

  • 新增wait_for_prompt函数,循环接收输出直到目标提示符出现,确保服务器准备好接收下一条指令
  • 取消固定sleep,改成基于提示符的触发式操作,适配不同网络和服务器状态
  • 分阶段等待每个步骤的提示符,避免指令发送时机错误

额外排查方向

  1. 指定终端类型:有些设备对终端类型敏感,连接时可以指定vt100或xterm
    ucs = ssh.invoke_shell(term='vt100')
    
  2. 分开发送指令:先单独发y,再发回车,不要合并成y\r\n
    ucs.sendall('y')
    time.sleep(0.5)
    ucs.sendall('\r\n')
    
  3. 开启调试日志:查看Paramiko底层交互细节,定位问题
    import logging
    logging.basicConfig(level=logging.DEBUG)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:50:25