Send Email on Startup and Shutdown Process on Linux Server

Send Email on Startup and Shutdown Process on Linux Server

It is always nice to have notification when a server reboots, especially when you are on vacation, away from the office, or just hanging around! In order to send an email on reboot, we can easily create a cron job to run on reboot. This means for a single reboot the Administrator will receive two emails. This solution will not send out an email if the system loses power, however an email will still be sent on reboot. This should indicate to the Administrator that something went wrong with the shutdown. The tips below are for a RedHat based system but should be similar in other architectures.
First thing we need is to create a new script "NotifyEmail"
Paste the following code into that document .


#!/bin/sh
EMAIL="example@example.com"
RESTARTSUBJECT="["`hostname`"] - System Startup"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"
RESTARTBODY="This is an automated message to notify you that "`hostname`" started successfully.
Start up Date and Time: "`date`
SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.
Shutdown Date and Time: "`date`
LOCKFILE=/var/lock/subsys/NotifyEmail
RETVAL=0

# Source function library.
. /etc/init.d/functions

stop()
{
echo -n $"Sending Shutdown Email: "
echo "${SHUTDOWNBODY}" | mutt -s "${SHUTDOWNSUBJECT}" ${EMAIL}
RETVAL=$?
if [ ${RETVAL} -eq 0 ]; then
rm -f ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}
start()
{
echo -n $"Sending Startup Email: "
echo "${RESTARTBODY}" | mutt -s "${RESTARTSUBJECT}" ${EMAIL}
RETVAL=$?
if [ ${RETVAL} -eq 0 ]; then
touch ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}
case $1 in
stop)
stop
;;
start)
start
;;
*)
esac
exit ${RETVAL}

Save the document by CTRL+O (To Write) and then press CTRL+X (To exit the Editor)
First, we need to make it executable:


chmod u+x NotifyEmail

Now we want to set this up to run at start up and shut down. Copy the script from your home directory to the init.d directory.


cp NotifyEmail /etc/init.d/

Last thing we do is set this up to run automatically by configuring it via chkconfig.


chkconfig --levels 3 NotifyEmail on

The code goes into a file under /etc/init.d
Then you go into /etc/rc.d folder and edit rc.local file. There you add:
Code:


/etc/init.d/NotifyEmail start

Also make a file called rc.local_shutdown in /etc/rc.d/ folder. In that file you add:
Code:


/etc/init.d/NotifyEmail stop

Now using these steps you will receive two mails during startup and shutdown process

Alternative Simple Way for Email Alert on Reboot:

Edit your crontab:


crontab –e

Add the following:


@reboot echo "Server has restarted "`hostname` | mail -s "System Restart" your@email.address

Now using these simple steps you will receive mail whileserver reboot.

0 comments:

Post a Comment