Skip to content
Advertisement

How to find if remote host is reachable over SSH without actually doing ssh

I have multiple remote hosts connected to my local host (server-A). TO ensure/filter the list of hosts which are genuinely reachable to localhost , I do ping test.

ping -c1 <remotehost-IP> 

if [ "$?" != "0" ];then
echo "Not reachable.Exiting..."
exit 1;
fi

However ping test could not provide me any check to ensure that filtered remotehost-IPs are reachable over SSH connection /port 22.

    non-root-user@localhost>ssh 172.26.192.15
    ssh: connect to host 172.26.192.15 port 22: Connection refused
 non-root-user@localhost>echo $?
 1

non-root-user@localhost>ssh -v  172.26.192.15
OpenSSH_3.9p1, OpenSSL 0.9.7a Feb 19 2003
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 172.26.192.15 [172.26.192.15] port 22.
debug1: connect to address 172.26.192.15 port 22: Connection refused
ssh: connect to host 172.26.192.15 port 22: Connection refused

Query:

Above check work for me if connection is refused. However, if SSH connection is possible then I enter into the remote host or proceed to password prompt. Which cause barrier to check return code.

So I wanted to know if there is any way to check if the remote IP WOULD be reachable or not reachable over SSH beforehand. ?

Advertisement

Answer

A Bash-Specific Solution

If you are using the Bash shell specifically, then you have access to TCP and UDP sockets. For example:

if (exec 3<>/dev/tcp/74.207.252.238/22) 2> /dev/null; then
    echo open
else
    echo closed
fi

This won’t tell you if the actual protocol in use is really SSH, but is often sufficient to determine that a given port is listening. Your mileage may vary.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement