【问题标题】:Check if paramiko ssh connection is still alive检查 paramiko ssh 连接是否仍然存在
【发布时间】:2015-04-02 00:52:06
【问题描述】:

有没有办法检查paramiko SSH 连接是否仍然存在?

In [1]: import paramiko

In [2]: ssh = paramiko.SSHClient() 

In [3]: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

In [4]: ssh.connect(hostname)

我想模仿这样的东西(目前不存在)

In [5]: ssh.isalive()
True

【问题讨论】:

  • isalive 有什么问题?
  • 刚刚编辑以澄清isalive 实际上并不存在。这是我想要的行为。

标签: python ssh paramiko


【解决方案1】:
 if ssh.get_transport() is not None:
     ssh.get_transport().is_active()

应该这样做....假设我阅读了docs 对。

【讨论】:

  • 太棒了!对SFTPClient有什么想法吗?
  • 看来你还需要检查ssh.get_transport() is not None
【解决方案2】:

我观察到 is_active() 返回误报。

我会推荐使用这件作品:

  # use the code below if is_active() returns True
  try:
      transport = client.get_transport()
      transport.send_ignore()
  except EOFError, e:
      # connection is closed

【讨论】:

  • 这是正确的答案。您可以从 client.get_transport().is_active() 获得 True 响应,然后从 client.exec_command 获得连接错误。
【解决方案3】:

对我来说,上面的答案不起作用,所以我通过发送带有超时的 exec_command() 来完成:

self.ssh.exec_command('ls', timeout=5)

例如,完整的方法如下:

def check_connection(self):
    """
    This will check if the connection is still availlable.

    Return (bool) : True if it's still alive, False otherwise.
    """
    try:
        self.ssh.exec_command('ls', timeout=5)
        return True
    except Exception as e:
        print "Connection lost : %s" %e
        return False

我每隔 5 秒左右调用一次。

【讨论】:

  • transport.is_active() / transport.is_alive() / transport.isAlive() 对我不起作用,花了很多时间来检测连接丢失并且有时从未检测到它(而另一台计算机甚至断电)
  • is_alive 和 is_active 对我不起作用,即使我断开网络,它们也会返回 true,发送命令并让它失败是一种更可靠的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 2015-08-27
  • 2012-11-30
  • 2016-05-21
相关资源
最近更新 更多