Need a way to test SSH with a timeout
Question: 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.

    
    
    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
    


Answer: You need to determine if it is actually a connect timeout, or if it can
connect, but the server is accepting the connection and doesn't send anything.

If you were to use telnet to manually test, telnet 22 and see if you get a
response from the server at all, you should see something like this if it
connects:

    
    
    $ telnet localhost 22
    Connected to localhost.
    Escape character is '^]'.
    SSH-2.0-OpenSSH_7.2
    

If it connects and you don't get any response, then I think you will have to
try a test using sockets in python.

You can find info here: <https://docs.python.org/3/library/socket.html>

