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

如何通过SSH重启远程机器,避免命令阻塞等待?

解决SSH执行远程重启命令时的阻塞问题

你的问题出在执行reboot命令后,远程机器会立刻断开SSH连接,导致stdout.channel.recv_exit_status()一直阻塞等待无法获取的退出状态。要解决这个问题,不需要等待命令的响应,只要确认命令成功发送即可,具体修改如下:

修改后的代码

def check_and_reboot(ssh, hostname):
    # if not ssh_connect(ssh, hostname):
    #     print("SSH failed, restarting {}".format(hostname))
    # Step 2: If connection fails, reboot the machine
    if not reboot_machine(ssh, hostname):
        print("Failed to reboot machine {}. Exiting.".format(hostname))
        # return

    # Step 3: Run the command over SSH
    command = "ls -asl /raid/dfs/aiceph"
    ssh_connect(ssh, hostname)
    output, exit_code = execute_remote_command(ssh, command)

    # Step 4: If the command returns an error code, reboot the machine
    if exit_code != 0:
        try:
            # Execute the reboot command - 后台执行并断开输出关联
            ssh.exec_command("sudo nohup /sbin/reboot -f > /dev/null 2>&1 &")
            
            # 无需等待退出状态,直接确认命令发送成功
            print("Reboot command sent successfully")
            return True

        except Exception as e:
            # If there is an exception, print the error and return False
            print("Error sending reboot command: {}".format(str(e)))
            return False

    # Step 5: Validation successful
    print("Validation successful for machine {}".format(hostname))

关键修改说明

  1. 移除阻塞的状态等待:删掉exit_status = stdout.channel.recv_exit_status()这一行,因为远程机器重启会直接断开SSH连接,永远无法获取到这个状态
  2. 简化命令发送逻辑:只要exec_command没有抛出异常,就说明命令已经成功发送到远程机器,reboot -f会强制触发重启,不需要再等待响应
  3. 保留异常处理:依然捕获发送命令时的异常,比如sudo权限不足、命令路径错误等场景的错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:35:10