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

如何用Paramiko执行需二次输入密码的命令?代码修改求助

问题分析与解决方案

你的问题核心在于:执行pcoip-list-licenses后,服务器需要交互式输入密码,但你用第二个exec_command("Password1!")是在SSH会话里执行新命令,而非给前一个命令的输入流传递密码,所以输入操作完全无效。

正确的做法是直接使用exec_command返回的stdin对象,将密码写入该命令的输入流,模拟终端输入密码并回车的操作。

修改后的代码

import paramiko

Host = "192.168.3.1"
port = 22
ID = "root"
PASSWD = "password1!"
COMMAND_PASSWD = "Password1!"

try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh.connect(Host, port=port, username=ID, password=PASSWD)
    
    print("ssh connect")
    print("Start verify License")
    
    # 执行许可证查询命令,获取对应的输入、输出流
    stdin, stdout, stderr = ssh.exec_command('pcoip-list-licenses')
    
    # 向命令的输入流写入密码,加上换行符模拟终端回车
    stdin.write(f"{COMMAND_PASSWD}\n")
    # 刷新输入流,确保数据发送到服务器
    stdin.flush()
    
    # 读取命令执行结果
    list_install_result = stdout.readlines()
    for line in list_install_result:
        print(line.strip())
    
    # 检查是否有错误输出
    error_output = stderr.read().decode()
    if error_output:
        print(f"错误信息: {error_output}")

except Exception as err:
    print(f"发生异常: {err}")
finally:
    # 确保SSH连接关闭
    if 'ssh' in locals() and ssh.get_transport().is_active():
        ssh.close()

关键修改点

  • 移除了无效的第二个exec_command调用,复用第一个命令返回的stdin对象传递密码
  • 写入密码时添加\n,模拟终端输入密码后的回车操作,让服务器识别输入完成
  • 调用stdin.flush()强制发送缓冲区内容,避免数据滞留导致服务器收不到密码
  • 增加了错误输出读取和连接自动关闭的逻辑,提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:32:11