Need a way to test SSH with a timeout
<p>This is my current code to test if a host is SSH-able. It works just fine when the host is up with or without SSH service running. However, it seems to just hang when the host crashes, which is the unique usecase that I need to depend on it giving me a quick True/False response. Due to OS and other dependencies, we need to keep the Python version to 2.6 for now. So I need a way to get this function to work and with a timeout of 1-2s.</p>

<pre><code>import commands

def test_ssh(host):
    output = commands.getstatusoutput("ssh " + host + " hostname")
    if output[0] == 0:
        return True
    else:
        print(host + " not accessible via SSH!")
        return False
</code></pre>

<p>If you want to be sure that an SSH connection (including authentication) can be established correctly, the best way probably is to connect in batch mode with a small timeout (<code>-o BatchMode=yes -o ConnectTimeout=2</code>).</p>

python ssh