Ping Tool to check if server is online

bash

Solution

Your code won't work at all, this is a revised version:

#!/bin/bash
# ping checker tool

FAILS=0
EMAIL_ADDRESS="example@example.com"
SERVER="192.168.1.1"
SLEEP=60

while true; do
    ping -c 1 $SERVER >/dev/null 2>&1
    if [ $? -ne 0 ] ; then #if ping exits nonzero...
        FAILS=$[FAILS + 1]
    else
        FAILS=0
    fi
    if [ $FAILS -gt 4 ]; then
        FAILS=0
        echo "Server $SERVER is offline!" \
            | mail -s "Server offline" "$EMAIL_ADDRESS"
    fi
    sleep $SLEEP #check again in SLEEP seconds
done

Change `example@example.com` and `192.168.1.1` for your email address and the IP address of the server you are testing. I recommend using and IP address instead of a hostname to prevent mixing name resolution errors with connection errors.

Please be advised that although this will work I would recommend running a slightly different script from cron instead of having it running continuously like you seem to want, when running from cron you would not need to monitor that the script is running since if it stops for some reason the monitoring of the server stops as well.

Something like this run from crontab every minute.

#!/bin/bash
# ping checker tool

TMP_FILE="/tmp/ping_checker_tool.tmp"
if [ -r $TMP_FILE ]; then
    FAILS=`cat $TMP_FILE`
else
    FAILS=0
fi
EMAIL_ADDRESS="example@example.com"
SERVER="192.168.1.1"

ping -c 1 $SERVER >/dev/null 2>&1
if [ $? -ne 0 ] ; then #if ping exits nonzero...
    FAILS=$[FAILS + 1]
else
    FAILS=0
fi
if [ $FAILS -gt 4 ]; then
    FAILS=0
    echo "Server $SERVER is offline!" \
        | mail -s "Server offline" "$EMAIL_ADDRESS"
fi
echo $FAILS > $TMP_FILE

Problem

Is this tool that I created from various SOF threads valid? Will it work? I want to have a ping test done to a server every minute. If it fails 5 times in a row it sends an email out. It then flushes and resets the script pretty much to check again. ``` #!/bin/bash # ping checker tool numOfFails=0 incrememnt=1 EMAILMESSAGE="/tmp/emailmessage.txt" while true; do if ! ping -c 1 google.com ; then #if ping exits nonzero... numOfFails=$(($num + $increment)) else numOfFails=0 fi if ((numOfFails > 4)); then numOfFails=0 echo "SAN is offline!" > $EMAILMESSAGE mail -s "SAN offline" "test@test.com" < $EMAILMESSAGE fi sleep 60 #check again in one minute done ```

Original source