Category Archives: monitoring

A script to monitor servers via Ping

Here is a code to check some servers from time to time.
I’ve used this script to run in a cron job every 10mins to check each server listed on the hostfile.txt

All the log files are copied to a web directory ready for viewing or I can send an email when any server is down.

#!/bin/sh
#
# Monitor all servers via Ping.
#

# contains hostname for each line.
HOST_FILE=$HOME/mon_scripts/hostfile.txt

LOGFILE=$HOME/www_webdir/logs/
COUNT=4
DOWN_SERVER=0

echo "———- $(date) Checking Servers ———–" >> $LOGFILE/$(date +%F).log

for myHost in `/bin/cat $HOST_FILE`
do
echo -n " HOST: $myHost ">> $LOGFILE/$(date +%F).log
count=$(ping -w2 -c$COUNT $myHost | grep ‘received’ | awk -F’,’ ‘{ print $2 }’ | awk ‘{ print $1 }’)
if [ $count -eq 0 ]; then
# 100% failed
DOWN_SERVER=`expr $DOWN_SERVER + 1 `
echo " is down (ping failed) at $(date)" >> $LOGFILE/$(date +%F).log
#echo "Host : $myHost is down (ping failed) at $(date)"
else
echo " is reachable."  >> $LOGFILE/$(date +%F).log
fi
done

# send email to author if server is down.
#
if [ "$DOWN_SERVER" -ne 0 ]; then
#echo "Number of down servers:  $DOWN_SERVER" | mail -S "DOWN SERVERS!!! $(date)" somebody@somewhere.com
echo "============= Waring Report ==============" >> $LOGFILE/$(date +%F).log
echo "Number of down servers:  $DOWN_SERVER"  >> $LOGFILE/$(date +%F).log
else
echo "—————————–"  >> $LOGFILE/$(date +%F).log
echo " All server are active."  >> $LOGFILE/$(date +%F).log
echo "—————————–"  >> $LOGFILE/$(date +%F).log

fi

exit 0;