How to test ssh connection using bash script in Linux

There can be multiple scenarios due to which ssh connection may fail, some of them can be

  • network issues
  • password incorrect
  • passphrase incorrect
  • and many more..

so we will try to rule out all the possible failed scenarios with some pre-checks before we do the actual task to make sure my ssh doesn't get hang

Ping Test

_HOST=192.168.100.10
ping -q -W 5 -c 1 $_HOST >/dev/null 2>&1

Here I am doing a ping test with a timeout for 5 seconds and will send one packet to the target host to make sure my network is proper between client and server.

Check port connectivity

You can use multiple tools to check the port based connectivity to make sure target port is available

${_PORT}=22
${_HOST}=192.168.100.10

timeout 5 bash -c "</dev/tcp/$_HOST/${_PORT}"

OR

On distributions with netcat rpm

# netcat -w 5 ${_HOST} ${_PORT}
_RETCODE=$?

if [ $_RETCODE -ne "0" ];then
    echo "Port 22 not available"
fi

Test ssh connectivity

Here we will try to do a quick ssh and validate the return code

ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no -i /export/home/sufuser/.ssh/id_rsa $_HOST 'exit 0'
_RCODE=$?
if [ $_RCODE -ne 0 ]
then
    log_and_print_red "unable to ssh, host is not accessible"
    continue
fi

I hope the article was useful.