How to create a bash script to check the SSH connection? How to create a bash script to check the SSH connection? bash bash

How to create a bash script to check the SSH connection?


You can check this with the return-value ssh gives you:

$ ssh -q user@downhost exit$ echo $?255$ ssh -q user@uphost exit$ echo $?0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):

$ a=`nmap uphost -PN -p ssh | grep open`$ b=`nmap downhost -PN -p ssh | grep open`$ echo $a22/tcp open ssh$ echo $b(empty string)

But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).

EDIT2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered':

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.


You can use something like this

$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

This will output "ok" if ssh connection is ok


ssh -q -o "BatchMode=yes" -i /home/sicmapp/.ssh/id_rsa <ID>@<Servername>.<domain> "echo 2>&1" && echo $host SSH_OK || echo $host SSH_NOK