Sharing a simple cron job to check if one of my VMs is running

kernalzero

Dabbler
Joined
Apr 26, 2018
Messages
16
This morning I noticed my pihole DNS running on an ubuntu server VM was down and I figured this would be a good time to make a cron job to email me when that server fails.

swap out your details and modify the code where you want.

Some things to know:
1) I keep my scripts in /mnt/freenas/resources/scripts
2) I made a temp folder in this directory to save the log file that is emailed to me
3) Thanks to Hazimil for some of the code below - original post https://www.ixsystems.com/community/resources/how-to-install-clamav-on-freenas-v11.66/

Code:
#!/bin/bash
HOSTS="PUT THE IP ADDRESS HERE"

COUNT=1

for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
 #   echo "Host : $myHost is down (ping failed) at $(date)"
 
### email address ###
    to_email="YOUREMAIL@WHATEVER.COM"

### prepare the email ###
## Set email headers ##
    (
        echo "To: ${to_email}"
        echo "Subject: pihole is DOWN $(date)"
        echo "MIME-Version: 1.0"
        echo "Content-Type: text/html"
        echo -e "\\r\\n"
    ) > /mnt/freenas/resources/scripts/tmp/piholeemail.tmp

# Set email body ##
    (
        echo "<pre style=\"font-size:14px\">"
        echo "${started}"
        echo ""
        echo ""
        echo "--------------------------------------"
        echo "Host : $myHost is down (ping failed) $(date)"
        echo "--------------------------------------"
        echo "</pre>"
    ) >> /mnt/freenas/resources/scripts/tmp/piholeemail.tmp
    
## email the log ##
sendmail -t < /mnt/freenas/resources/scripts/tmp/piholeemail.tmp

## Delete the log file ##
rm /mnt/freenas/resources/scripts/tmp/piholeemail.tmp
    
    fi
done
 
Top