0

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 ?

3
  • 1
    @jhnc I had to leave the office in a hurry because of the heat wave we are currently having in France. Just added my question. Commented Jul 18, 2022 at 19:07
  • 1
    The reason it fails is that timeout is not buit in to bash. This means the redirection is set up before timeout even executes. Commented Jul 18, 2022 at 19:29
  • consider: set -vx; timeout 1 echo main 11< <(echo 1 >/dev/tty) 12< <(echo 2 >/dev/tty) </dev/tcp/$server/22 13< <(echo 3 >/dev/tty). Note that first and last echo don't happen because tcp redirect caused termination Commented Jul 18, 2022 at 19:35

1 Answer 1

1
$ 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.
Sign up to request clarification or add additional context in comments.

1 Comment

Can you also explain in the beginning of your answer why my command didn't work ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.