Open ssh connection when available

January 19, 2026

When I’m installing a new server, it’s not unusual that I’m waiting for the machine to reboot before I can reestablish my ssh connection. Historically I would just ping the server until I get a response and then just try ssh a couple of times until the server was able to be reached by ping AND sshd started.

I like this solution a bit more. It uses netcat to check the given SSH_PORT until that port is open. Here is the script.

/usr/src/scripts.d/local-$HOSTNAME/ssh.when.ready.sh
#!/bin/bash
SSH_PORT=22
WAIT=2s # how long between attempts
if [ $# -eq 0 ]
  then
    echo "please provide a hostname [and options]"
fi
echo " * waiting for $1 to become available"
echo -n "   "
until nc -vzw 2 "$1" $SSH_PORT >/dev/null 2>&1; do sleep "$WAIT"; echo -n "."; done
echo -e "\n * ready!"
ssh "$1"
exit 0

Remember to mark the script as executable.

chmod 755 /usr/src/scripts.d/local-$HOSTNAME/ssh.when.ready.sh
Now, we can execute the script.
ssh.when.ready.sh test
 * waiting for test to become available
   ...

You can use [ctrl-c] to stop the process at any point. Otherwise, ssh will connect with the system is up.