fosfik
fosfik

Reputation: 83

How to ping webpage and send email when status change?

I have a code where bash script ping host and send email if the host don't respond.

HOSTS="google.pl"
COUNT=1

SUBJECT="Ping failed"
EMAILID="[email protected]"
for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then

   echo "Host : $myHost is down (ping failed) at $(date)" | mail -s "$SUBJECT" $EMAILID
  fi
done

Its ok to make a crontab with this to check it every hour etc. But I need a script to ping my server every 5 minutes and send email if it doesn't ping (maybe 3 packet loss) only ONCE when server is down and send second email when it starts working. Maybe save some status to file and if changed send email? Any one have idea how to do it? I found few ideas at stackoverflow but no one send email at packet loss and next one only when is starts working again.

Upvotes: 0

Views: 1857

Answers (2)

tripleee
tripleee

Reputation: 189397

Here's a quick and dirty attempt which stores the timestamp of each failure in a log file, and checks if the latest one is recent.

I also took the liberty to refactor a number of shell programming antipatterns.

#!/bin/bash

# Don't use uppercase for your private variables
hosts="google.pl"
count=1

subject="Ping failed"
emailid="[email protected]"

# Start up correctly the first time
test -s fail.log || echo 0 >fail.log

if (($(tail -n 1 fail.log) + 3600 < $(date +%s)); then
    # Last failure is too recent, abandoning
    exit 0
fi

for myHost in $hosts
do
    if ! ping -c "$count" "$myHost" |
        awk -F , '/received/ { split($2, s); r=1-s[1] } END { exit r }'
    then
        echo "Host : $myHost is down (ping failed) at $(date)" |
        mail -s "$subject" "$emailid"
        date +%s >>fail.log
    fi
done

The logic to get Awk to return 1 on failure and then invert the result code from that is somewhat tortured, but coincidentally also illustrates how to use if properly.

This will stop checking all the sites in hosts for an hour if one of them fails. Maybe you want the logic to work differently, or tweak the timing, or etc.

Upvotes: 1

Roopak A Nelliat
Roopak A Nelliat

Reputation: 2541

Monit is a good open source and free tool which helps you do this. I personally use it in my projects and this has a simple and nice dashboard also.

Try this - https://mmonit.com/monit/documentation/monit.html#Remote-host

Upvotes: 0

Related Questions