Search code examples
bashtimeout

The timeout command does not work when reading from /dev/tcp/$server/ssh, how can I make this timeout command work?


I'm trying to write a bash function to test SSH connections :

$ echo $0
-bash
$ time timeout 20s cat < /dev/tcp/$server/ssh;test $? = 124 && echo "WARNING: Could not connect to $server on ssh."
-bash: connect: Connection timed out
-bash: /dev/tcp/X.Y.Z.T/ssh: Connection timed out

real    1m3.000s
user    0m0.000s
sys     0m0.000s
WARNING: Could not connect to X.Y.Z.T on ssh.

How can I make this timeout command work ?


Solution

  • $ server="google.com"; timeout=20; 
    
    $ time timeout "$timeout" bash -c "</dev/tcp/${server}/22" || echo "WARNING: Could not connect to $server on ssh."
    
    real    0m20.002s
    user    0m0.003s
    sys     0m0.000s
    WARNING: Could not connect to google.com on ssh.
    

    Using netcat (nc)

    $ time nc -z -w "$timeout" "$server" 22 || echo "WARNING: Could not connect to $server on ssh."
    
    real    0m20.059s
    user    0m0.003s
    sys     0m0.001s
    WARNING: Could not connect to google.com on ssh.