我有这部分代码,我试图通过 ssh 重新启动远程计算机:
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
_, stdout, stderr = ssh.exec_command("sudo nohup /sbin/reboot -f > /dev/null 2>&1 &")
# Wait for the command to complete
exit_status = stdout.channel.recv_exit_status()
# If the exit status is 0, the reboot command was sent successfully
if exit_status == 0:
print("Reboot command sent successfully")
return True
else:
print("Failed to send reboot command with exit status {}".format(exit_status))
return False
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))
我设置了 exit_code = 1 来验证流程。看来我的代码恰好卡在第 4 步,因为我的代码一直在等待重新启动命令的提示。如何克服这个问题而不必等待重新启动命令的响应?
显式的
exit
应避免超时问题
ssh HOST "sudo reboot now" # Results in a ssh timeout and exitcode=255
ssh HOST "sudo reboot now; exit 42" # Returns immediately and exitcode=42