Bash script SSH is a common tool for Linux users. It is needed when you want to run a command from a local server or a Linux workstation. SSH is also used to access local Bash scripts from a local or remote server.
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 $a
22/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
Complementing the response of @Adrià Cidre
you can do:
status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)
if [[ $status == ok ]] ; then
echo auth ok, do something
elif [[ $status == "Permission denied"* ]] ; then
echo no_auth
else
echo other_error
fi
Below ssh
command should have an exit code of 0
on a successful connection and a non-zero value otherwise.
ssh -q -o BatchMode=yes [email protected] exit
if [ $? != "0" ]; then
echo "Connection failed"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With