Shell script to check whether a server is reachable?

Balaswamy Vaddeman picture Balaswamy Vaddeman · Jan 20, 2012 · Viewed 77.3k times · Source

I have 5 Solaris servers present across different locations. Sometimes some of these servers are not reachable from my location due to various reasons (either because of network problems or the server itself goes down suddenly).

So I would like to write a Bash shell script to check wether they are reachable. What I have tried is:

ssh ipaddress "uname -a"

Password less authentication is set. If I don't get any any output I will generate a mail.

  1. Are there any otherways to check server reachability?
  2. Which one is the best way?
  3. Is what I have tried correct?

Answer

flying sheep picture flying sheep · Dec 18, 2015

The most barebones check you can do is probably to use netcat to check for open ports.

to check for SSH (port 22) reachability, you can do

if nc -z $server 22 2>/dev/null; then
    echo "$server ✓"
else
    echo "$server ✗"
fi

from the manpage:

-z   Specifies that nc should just scan for listening daemons, without sending any data to them.