Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to check whether a server is reachable?

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?
like image 265
Balaswamy Vaddeman Avatar asked Jan 20 '12 06:01

Balaswamy Vaddeman


People also ask

How do you check server is reachable or not in Linux?

The ping command is a simple network utility command-line tool in Linux. It's a handy tool for quickly checking a host's network connectivity. It works by sending an ICMP message ECHO_REQUEST to the target host. If the host reply with ECHO_REPLY, then we can safely conclude that the host is available.

How do you check server is up or not in Unix?

First, open the terminal window and then type: uptime command – Tell how long the Linux system has been running. w command – Show who is logged on and what they are doing including the uptime of a Linux box. top command – Display Linux server processes and display system Uptime in Linux too.


Video Answer


2 Answers

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.

like image 144
flying sheep Avatar answered Oct 10 '22 01:10

flying sheep


Your ssh command will test for more than if the server is reachable - for it to work, the ssh server must be running, and everything must be right with authentication.

To just see if the servers are up, how about just a simple ping?

ping -c1 -W1 $ip_addr && echo 'server is up' || echo 'server is down'
like image 35
gcbenison Avatar answered Oct 09 '22 23:10

gcbenison