This code checks if a host on a network is reachable via ping; if not, it sends an email through ssmtp (which needs to be configured beforehand). All parameters are declared in the first few lines.
TODO: remove duplicate code
#!/bin/bash
NUMBER_OF_PINGS=3
HOST_NAME="myhostname.local"
FLAG_FILE=/home/pi/$HOST_NAME.isdead
EMAIL_SENDER=foo@gmail.com
EMAIL_RECEIVER=bar@gmail.com
#ping returns 0 if target could be reached
if ping -c $NUMBER_OF_PINGS $HOST_NAME &> /dev/null
then # host is reachable
if test -f $FLAG_FILE # flag file exists
then
{ echo To: $EMAIL_RECEIVER
echo From: $EMAIL_SENDER
echo Subject: 👍 $HOST_NAME is alive again
echo Congrats! $HOST_NAME is alive again.
} | /usr/sbin/ssmtp $EMAIL_RECEIVER
rm $FLAG_FILE # delete flag file and send email
else # nothing to do
:
fi
else # host is NOT reachable
if test -f $FLAG_FILE # flag file exists, which means that an email has already been sent
then # nothing to do
:
else # send an email otherwise and create flag file
{ echo To: $EMAIL_RECEIVER
echo From: $EMAIL_SENDER
echo Subject: ☠️ $HOST_NAME is dead
echo My condolences. I tried to ping $HOST_NAME $NUMBER_OF_PINGS times, but did not get a response.
} | /usr/sbin/ssmtp $EMAIL_RECEIVER
touch $FLAG_FILE
fi
fi
No comments:
Post a Comment