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

如何用Python Paramiko模拟Enter键?解决apt升级交互问题

使用Paramiko执行apt upgrade时无法处理交互式选择窗口的问题

我用Python的Paramiko库写了一段代码,想在服务器上执行apt update和apt upgrade命令。执行apt upgrade时,我通过stdin.write("Y" + '\n')确认安装,但遇到了问题:手动在服务器操作时会弹出一个选择窗口(截图1),但用Python执行时显示的内容如截图2所示。我尝试发送stdin.write("1" + '\n')命令,却没有任何效果。

截图1:
手动操作时的选择窗口

截图2:
Paramiko执行时的输出

我的代码如下:

def sendCommand(command):
    print("Sending command")
    if (client):
        stdin, stdout, stderr = client.exec_command(command)
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata += stdout.channel.recv(1024)

                print(str(alldata, "utf8"))

def sendCommand_Text(command, text):
    print("Sending command")
    if (client):
        stdin, stdout, stderr = client.exec_command(command)
        stdin.write(text + '\n')
        stdin.flush()

        stdin.write("1" + '\n')
        stdin.flush()

        stdin.write('\n')
        stdin.flush()
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata += stdout.channel.recv(1024)

                print(str(alldata, "utf8"))

sendCommand("apt update\n")

sendCommand_Text('apt upgrade\n', "Y")

解决方法

问题核心在于apt upgrade的选择窗口是基于ncurses的交互式界面,并非简单的标准输入输出交互,直接用stdin.write无法识别这种复杂的终端场景。推荐两种可行方案:

方案1:用非交互式参数跳过所有选择(优先推荐)

修改apt upgrade命令,添加参数让命令自动完成所有操作,无需手动交互:

sendCommand("apt update")
sendCommand("apt upgrade -y --force-confdef --force-confold")

参数说明:

  • -y:自动对所有确认提示回复"yes"
  • --force-confdef:新配置文件与原有文件无差异时,自动使用默认配置
  • --force-confold:配置文件有差异时,保留原有文件,不弹出选择窗口

方案2:使用模拟终端会话处理交互

如果必须处理交互式窗口,可使用Paramiko的invoke_shell()建立模拟终端,模拟手动操作流程:

import time

def interactive_upgrade():
    if client:
        shell = client.invoke_shell()
        # 执行apt update
        shell.send("apt update\n")
        time.sleep(5)  # 等待命令执行完成,可根据实际输出调整时长
        # 执行apt upgrade
        shell.send("apt upgrade\n")
        time.sleep(2)
        shell.send("Y\n")
        time.sleep(3)
        shell.send("1\n")
        # 持续读取输出直到会话结束
        while not shell.closed:
            if shell.recv_ready():
                print(shell.recv(1024).decode("utf8"))
            time.sleep(1)

interactive_upgrade()

注意:这种方式需要根据服务器实际响应速度调整sleep时间,或者监听输出内容触发对应输入,复杂度较高,仅在无法使用非交互式参数时采用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:55:38