5 simple methods to test ssh connection in Linux & Unix


SSH

In this article I will share different commands and methods to Test SSH connection in Linux and Unix with real time practical examples.

 

Method 1: Use timeout with bash utility to test SSH connection

Test SSH connection in 5 simple ways Linux & Unix

/usr/bin/timeout utility is installed by default in most distros which is part of coreutils rpm in Linux

Check if coreutils is installed on your server

# rpm -q coreutils
coreutils-8.22-24.el7.x86_64

We can use bash utility with timeout to test SSH connection by checking port 22 status.
If you are using a different port for 22 then you can replace it in the below syntax

Syntax:

# timeout <value> bash -c "</dev/tcp/<server>/<port>"

Here server2 is my target host, I will execute the command with a timeout value of 5s on port 22

[root@server1 ~]# timeout 5 bash -c "</dev/tcp/server2/22"

If the exit status is 0, it means test ssh connection was successful

[root@server1 ~]# echo $?
0

Or if you get "connection refused" with non-zero exit status then test SSH connection has failed

[root@server1 ~]# timeout 5 bash -c "</dev/tcp/server2/22"
bash: connect: Connection refused
bash: /dev/tcp/10.10.10.10/22: Connection refused
[root@server1 ~]# echo $?
1

 

Shell Script Example

We can use this tool in a shell script to test SSH connection over port 22

# cat /tmp/check_connectivity.sh
#!/bin/bash

server=10.10.10.10      # server IP
port=22                 # port
connect_timeout=5       # Connection timeout

timeout $connect_timeout bash -c "</dev/tcp/$server/$port"
if [ $? == 0 ];then
   echo "SSH Connection to $server over port $port is possible"
else
   echo "SSH connection to $server over port $port is not possible"
fi

 

Method 2: Use nmap to test SSH connection

5 simple methods to test ssh connection in Linux & Unix

  • /usr/bin/nmap is provided by nmap rpm.
  • nmap is widely used to check port status so we can use nmap to check port 22 status on target host
  • nmap is not installed by default in most distros and you must install it before using it
  • On RHEL/CentOS environment use yum or dnf to install nmap
# yum -y install nmap

Syntax:

# nmap <server> -PN -p ssh | egrep 'open|closed|filtered'

Here,

-Pn		Treat all hosts as online -- skip host discovery
-p ssh		Only scan the default SSH port
open		means that an application on the target machine is listening for connections/packets on that port
closed		ports have no application listening on them, though they could open up at any time
filtered	means that a firewall, filter, or other network obstacle is blocking the port so that Nmap cannot tell whether it is open or closed.

Here server2 is my target host and we are looking for nmap port status

[root@server1 ~]# nmap server2 -Pn -p ssh | egrep -io 'open|closed|filtered'
closed

[root@server1 ~]# nmap server2 -Pn -p ssh | egrep -io 'open|closed|filtered'
open

 

Shell script Example

We can use this command in our shell script to test SSH connection over port 22

[root@server1 ~]# cat /tmp/check_connectivity.sh
#!/bin/bash

server=10.10.10.10      # server IP
port=22                 # port
connect_timeout=5       # Connection timeout

status=`nmap $server -Pn -p $port | egrep -io 'open|closed|filtered'`
if [ $status == "open" ];then
   echo "SSH Connection to $server over port $port is possible"
elif [ $status == "filtered" ]; then
   echo "SSH Connection to $server over port $port is possible but blocked by firewall"
elif [ $status == "closed" ]; then
   echo "SSH connection to $server over port $port is not possible"
else
   echo "Unable to get port $port status from $server"
fi

 

Method 3: Use netcat or nc to test SSH connection

Test SSH connection in 5 simple ways Linux & Unix

  • In my earlier article I had shared the steps to use nc and ncat to transfer files between Linux server.
  • We can also use nc and ncat utility to check port status from target hosts and test SSH connection
  • nc and ncat is provided by nmap-ncat rpm

To check if nmap-ncat is installed on your server

# rpm -q nmap-ncat
nmap-ncat-6.40-19.el7.x86_64

Syntax:

# nc --wait <value> <server> <port> < /dev/null &> /dev/null

Here we have defined a connection timeout period of 5 second which you can change based on your environment

Check the exit status of nc command in this command. For 0 exit status we know that port 22 is open and SSH connection will be successful.

[root@server1 ~]# nc --wait 5 server2 22 < /dev/null &> /dev/null
[root@server1 ~]# echo $?
0

For non-zero exit status we know that SSH connection will fail for respective target host

[root@server1 ~]# nc --wait 5 server2 22 < /dev/null &> /dev/null
[root@server1 ~]# echo $?
1

 

Shell Script Example

We can use this command in our shell script example to automate the verification

# cat /tmp/check_connectivity.sh
#!/bin/bash

server=10.10.10.10      # server IP
port=22                 # port
connect_timeout=5       # Connection timeout

nc --wait $connect_timeout $server $port < /dev/null &> /dev/null
if [ $? == 0 ];then
   echo "SSH Connection to $server over port $port is possible"
else
   echo "SSH connection to $server over port $port is not possible"
fi

 

Method 4: Use SSH to check SSH connection

Test SSH connection in 5 simple ways Linux & Unix

  • I know we are looking for SSH alternatives to check SSH connection but if you have a setup configured with password less connection then you can also use SSH for this verification
  • We will use ConnectTimeout to make sure our SSH don't get stuck waiting for connection to become active
  • StrictHostKeyChecking is used to avoid any security and fingerprint prompt
  • If BatchMode is yes then passphrase/password querying will be disabled
NOTE:
If you are not using password less authentication then this method will not be very helpful as the command will prompt for password and cannot be automated unless you use some hack use as sshpass or expect script

Here we are using 'exit 0' as the remote command to be called on successful SSH

[root@server1 ~]# ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no -o ConnectTimeout=5 server2 'exit 0'
[root@server1 ~]# echo $?
0

While if the output exit status is non-zero so we know the test SSH connection has failed

[root@server1 ~]# ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no -o ConnectTimeout=5 server2 'exit 0'
[root@server1 ~]# echo $?
255

 

Shell Script Example

We can use this command in our existing shell script for automation purpose:

# cat /tmp/check_connectivity.sh
#!/bin/bash

server=10.10.10.10      # server IP
port=22                 # port
connect_timeout=5       # Connection timeout

ssh -q -o BatchMode=yes  -o StrictHostKeyChecking=no -o ConnectTimeout=$connect_timeout $server 'exit 0'
if [ $? == 0 ];then
   echo "SSH Connection to $server over port $port is possible"
else
   echo "SSH connection to $server over port $port is not possible"
fi

 

Method 5: Use telnet to test SSH connection

Test SSH connection in 5 simple ways Linux & Unix

  • telnet is another very handy tool to check port status
  • /usr/bin/telnet is provided by telnet rpm which is part of default repositories and you do not need any third party repository

Check if telnet is installed

# rpm -q telnet
telnet-0.17-65.el7_8.x86_64

Syntax:

# telnet <server> <port>

But since our end goal is to automate so we will tweak the syntax

# echo quit | telnet <server> <port> 2>/dev/null | egrep -qi Connected

Let us use this to test SSH connection in Linux. if we are able to grep for "Connected" then port 22 is reachable and SSH connection is possible

[root@server1 ~]# echo quit | telnet server2 22 2>/dev/null | egrep -qi Connected
[root@server1 ~]# echo $?
0

If we get a non-zero exit status, this means that we were unable to grep "Connected" in the output hence SSH connection is not possible

[root@server1 ~]# echo quit | telnet server2 22 2>/dev/null | egrep -qi Connected
[root@server1 ~]# echo $?
1

 

Shell Script Example

We will use telnet with our existing sample shell script to test SSH connection

# cat /tmp/check_connectivity.sh
#!/bin/bash

server=10.10.10.10      # server IP
port=22                 # port
connect_timeout=5       # Connection timeout

echo quit | telnet $server $port 2>/dev/null | egrep -qi "Connected"
if [ $? == 0 ];then
   echo "SSH Connection to $server over port $port is possible"
else
   echo "SSH connection to $server over port $port is not possible"
fi

 

Conclusion

In this tutorial guide we learned about different internal tools within Linux and Unix which can be used to test and verify SSH connection before actually attempting the SSH. We do not need to rely on additional third party tools for such verification. It is always a good idea to first check the network connectivity and port 22 availability before performing the SSH to avoid un-necessary wait time and timeout scenarios

Lastly I hope the commands from this article to test SSH connection on Linux and Unix was helpful. So, let me know your suggestions and feedback using the comment section.

 

References

I have used below external references for this tutorial guide
How to create a bash script to check the SSH connection?

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

15 thoughts on “5 simple methods to test ssh connection in Linux & Unix”

  1. For mthod 5, I use this command:

    echo *quit | telnet -e* localhost 7722 2>/dev/null | egrep -qi 'Connected to localhost.'
    Reply
  2. Found this useful. Thanks for the detailed tutorial.

    Can u give a few examples to check the SSH connection possibility on Windows 10 PC to a Raspberry Pi?

    Reply
  3. What would be a good test for ssh over an Socky5 proxy? I have docker image that proxies a vpn connection. I can test it’s web proxy function with “curl” as that utility supports proxies and the container doesn’t have to have a user account to get a response.

    For ssh, the docker image needs to make sure it can connect to a remote server over its own proxy( on port 9000 in my example ). Something like this would work if the container had an account to use to login, but it doesn’t ( in my environment, only people have accounts, service accounts are not permitted)

    E.g. ssh -q -o BatchMode=yes -o StrictHostKeyChecking=no -o ProxyCommand=”nc -x localhost:9000 %h %p” -o ConnectTimeout=3 remote_ssh_host ‘exit 0’

    What might be a good alternative?

    Reply
    • I am afraid, I am also not familiar with such environment and possible solution. Although we wouldn’t need a service account to execute SSH. SA is used when we intend to connect source host for some activity but your usecase is only to execute ssh client. In Kubernetes + docker we defined runAsUser which we use to perform SSH. In docker also we can define –user but I am not sure if this is allowed in your environment.

      Reply
      • We use ssh keys, so the docker image / container would need to have those keys as well. However, the issue I encountered was that Alpine linux image had the Busybox version of netcat, which does not support the “-x” proxy parameter.

        I found the netcat-bsd package for Alpine that supports the “-x” proxy parameter. I installed that to my image and was able to use “timeout 3 nc -zvx localhost:9000 hostname 22” to test access to the remote port 22 using the proxy as a relay.

        so curl --fail --proxy is used to Web proxy tests, and the netcat command tests the socks proxy connection.

        Reply
    • ssh-keyscan is another utility similar to SSH which performs connection to remote host. So the problem may remain the same if the utility gets stuck so ssh-keyscan has it’s own timeout argument (-T).

      It all actually depends on end user’s requirement.

      Reply
  4. Here is an improved version that scans a range of ip’s, checks for ssh password-less auth and prints hostname as well

    #!/bin/bash
    username="username"
    for server in "192.168.0."{200..214}
    do
            ssh -q -o ConnectTimeout=2 -o NumberOfPasswordPrompts=0 -l $username -i ~/.ssh/id_rsa "$server" 'exit 0'
            inc=$?
            ns=$(nslookup $server| awk '/1:/{print $4}')
            if [ $inc -eq 0 ]; then
                echo "$server + $ns"
                    else
                        echo "$server - $ns"
                            fi
    done
    Reply
    • My view is rather than using SSH just to verify the connectivity would be resource intensive and time consuming. SSH method is well suited only when we plan to do SSH and as a pre-check we use this method to make sure SSH session doesn’t get stuck forever waiting for the connection.

      Reply

Leave a Comment