Check if paramiko ssh connection is still alive

MRocklin picture MRocklin · Feb 3, 2015 · Viewed 20k times · Source

Is there a way to check if a paramiko SSH connection is still alive?

In [1]: import paramiko

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

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

In [4]: ssh.connect(hostname)

I want to mimic something like this (which doesn't currently exist)

In [5]: ssh.isalive()
True

Answer

user2488286 picture user2488286 · Oct 28, 2015

I had observed is_active() returning false positives.

I would recommend using this piece:

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