Python Paramiko exec_command 超时不起作用?

4 python timeout paramiko

我得到以下 ssh 命令,

    try:
        print 'trying to restart'
        self.ssh.exec_command(RR_CMD % (self.path_ext, self.rport), timeout=1)
        print 'restarted'
    except:
        self.ssh.close()
        self.ssh = ssh.create_ssh_client(self.ip, self.port, self. username, self.password)
        self.restart()
Run Code Online (Sandbox Code Playgroud)

基本上我正在尝试重新启动远程 perl 脚本。但有时,比如假设 2000 年中有 1 个 - 我的 python 程序在 exec_command 行上冻结有时长达几分钟!

我想使用超时功能,我将其设置为 1 秒,但由于某种原因它不起作用。

Wyr*_*ood 5

我遇到了 exec_command 超时的问题,但没有按照我的预期进行。例如,我将超时设置为 60 并发现一个挂起的命令整夜运行。我之前在做的是

response = client.exec_command(command, timeout=60)
returncode = response[0].channel.recv_exit_status()
Run Code Online (Sandbox Code Playgroud)

但是超时为 None 或任何值时,它一直挂着recv_exit_status,现在,相反,我只是自己管理超时,因为它exec_command是非阻塞的,通过轮询channel.exit_status_ready

start = time.time()
while time.time() < start + timeout:
    if response[0].channel.exit_status_ready():
        break
    time.sleep(1)
else:
    raise TimeoutError(f'{command} timed out on {hostname}')
returncode = response[0].channel.recv_exit_status()
Run Code Online (Sandbox Code Playgroud)