【问题标题】:Python Paramiko exec_command timeout doesn't work?Python Paramiko exec_command 超时不起作用?
【发布时间】:2016-05-25 23:44:26
【问题描述】:

我得到了以下 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()

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

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

【问题讨论】:

    标签: python timeout paramiko


    【解决方案1】:

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

    response = client.exec_command(command, timeout=60)
    returncode = response[0].channel.recv_exit_status()
    

    但是由于超时为 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()
    

    【讨论】:

    • 谢谢!一个问题:在哪里导入TimeoutError
    • @FaithReaper - 它是内置的
    • 是的。内置在 Py3 中,但不在 Py2 中。我刚刚发现。如果您使用的是 Python 2,请参阅此内容。*.com/questions/24210792/…
    【解决方案2】:

    你的paramiko版本怎么样?

    最新版paramiko支持参数timeout

    Paramiko Changelogv1.10.0:

    在 SSHClient.exec_command 中添加超时参数,以便于设置命令的内部通道对象的超时时间。感谢 Cernov Vladimir 提供的补丁。

    【讨论】:

    • 我的版本是1.16,我确实用了timeout命令,根本没有超时...