Mil*_*vić 0 python linux ssh timeout
我正在通过 SSH 发送命令。这个特定的命令恰好告诉机器重新启动。不幸的是,这会挂起我的 SSH 会话并且不会返回,因此我的脚本无法继续转发到其他任务。
我尝试过修改命令本身以包含“退出”和/或转义命令的各种组合,但在这些情况下,机器都不会在重新启动和关闭 SSH 会话的命令时启动。我还尝试过 SSH 的 ConnectTimeout 和 ClientAlive 选项,但它们似乎使重新启动命令被忽略。
我在这里缺少一些明显的命令吗?
好吧,没有人发布任何与 SSH 特别相关的答案,所以我将提出一个SIGALRM像这样的解决方案:Using module 'subprocess' with timeout
class TimeoutException(Exception): # Custom exception class
pass
def TimeoutHandler(signum, frame): # Custom signal handler
raise TimeoutException
# Change the behavior of SIGALRM
OriginalHandler = signal.signal(signal.SIGALRM,TimeoutHandler)
# Start the timer. Once 30 seconds are over, a SIGALRM signal is sent.
signal.alarm(30)
# This try/except loop ensures that you'll catch TimeoutException when it's sent.
try:
ssh_foo(bar) # Whatever your SSH command is that hangs.
except TimeoutException:
print "SSH command timed out."
# Reset the alarm stuff.
signal.alarm(0)
signal.signal(signal.SIGALRM, OriginalHandler)
Run Code Online (Sandbox Code Playgroud)
这基本上将计时器设置为 30 秒,然后尝试执行您的代码。如果在时间耗尽之前未能完成,SIGALRM则会发送 a ,我们捕获它并将其转换为 a TimeoutException。这迫使你进入一个except可以继续你的程序的街区。
| 归档时间: |
|
| 查看次数: |
2886 次 |
| 最近记录: |