Linux Administrator

Bash Script : Get Email Alert When Cronjob Fail

Email-Alert
mm
Written by Santosh Prasad

In this article, I will give you bash content which encourages you to set an email caution for the Cronjob fail. This content will continue alarming you when your cronjob fail in light of any issues on server.

Conditions

I will check the status code “200” if status does not comes 200 then send email alert for cron fails.

You will get email notification when above conditions are true.

Please make sure you have email server configured on the server.

Create A Script

Download/create the below script.

# vim cron_status.sh

#!/bin/bash

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

# Variable Definations

CRONFILES="[email protected]"

MAIL=$(which mail)

WGET=$(which wget)

MAILTO='[email protected]'

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

Set Executable Permission

Make this script executable.

# chmod +x cron_status.sh

Setup Script In Crontab

Now you have to use this script file with the cron URL.

# crontab -e

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

Save and close the file.

You can alter above content as indicated by your prerequisite. In the event that regardless you confront any issues to setup this content at that point remarks down beneath in comments box.

Thanks:)

Thank you! for visiting Look Linux.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at Look Linux Submit Article. Stay connected to Facebook.

About the author

mm

Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment