Bash Script: Email Alert When CronJob Fails

OVERVIEW

In this article, I am going to provide you bash script which helps you to set an email alert for the Cronjob fails. This script will keep alerting you when your cronjob fails because of any issues on server.

CONDITION USE:

Check for the Statuscode '200' if statuscode not 200 then send email alert for cron fails.

This is complete automated script which will send you an email notification when above conditions are true.

Make sure you have a mail server configured on your server. if not then follow below link which helps you to configure a mail server.

READ : STEPS TO INSTALL POSTFIX SERVER ON LINUX

vim CronLogChecker.sh

#!/bin/bash

###############################################################
# Title         : CronChecker.sh                              #            
# Version       : 1.0v                                        #            
# Usage         : ./CronChecker.sh                            #            
###############################################################

# Variable Definations

CRONFILES="$@"

MAIL=$(which mail)

WGET=$(which wget)

MAILTO='emailid@gmail.com'

CRONURL="$1"

CRONLOGFILE="$2"

# Check for Cron URL and Logfile.

if [ -z "${CRONFILES}" ]; then

       echo -e "Please provide Cron URL and Log File path.nUsage: $0 ......"

       exit 1

fi

# Execute the Cron

$WGET -O - $CRONURL > $CRONLOGFILE 2>&1

# Check for Logfile.

if [[ -s "${CRONLOGFILE}" ]]; then

STATUSCODE=$(cat $CRONLOGFILE | grep 'HTTP request sent'| sed 's/[^0-9]//g' | head -n1)

       BODY="nnFor more information please check $CRONLOGFILE.nnnThanks,n$0"

       if [ "$STATUSCODE" -ne 200 ]; then

               echo $STATUSCODE

               echo -e "Hi SysAdmin, nnThe Cron execution gives error $STATUSCODE on CronURLnn" $BODY | $MAIL -s "Cron Error in $CRONURL" $MAILTO

       fi

else

       echo -e "Cron Log File is empty"

       exit 1

fi

PERMISSIONS :

Once you save the script, provide executable permission to run the script.

$ chmod +x CronLogChecker.sh

How to use the script with the cron:

Now you need to use this script file with the cron url. Use this script as per the below instructions.

crontab -l

30 1 * * * root /bin/bash /opt/CronLogChecker.sh http://your-cron-url /tmp/cron-url-log.tmp

Save and close the file.

This is well-tested script and provides you data without using more memory on the server.

You can modify above script according to your requirement. If you still face any issues to setup this script then comments down below in comment box. Stay connected & subscribe with techthings.org for more such articles.

Leave a Reply

Your email address will not be published. Required fields are marked *