Skip to content

Instantly share code, notes, and snippets.

@fuzzmz
Created March 30, 2013 22:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fuzzmz/5278709 to your computer and use it in GitHub Desktop.
Save fuzzmz/5278709 to your computer and use it in GitHub Desktop.
Script to send email on Debian based server at shutdown and restart.
#!/bin/sh
### BEGIN INIT INFO
# Provides: SystemEmail
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Send email
# Description: Sends an email at system start and shutdown
### END INIT INFO
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/SystemEmail
RETVAL=0
# Source function library.
. /lib/lsb/init-functions
stop()
{
echo -n $"Sending Shutdown Email: "
echo "${SHUTDOWNBODY}" | mail -s "${SHUTDOWNSUBJECT}" ${EMAIL}
sleep 4
RETVAL=$?
sleep 4
if [ ${RETVAL} -eq 0 ]; then
rm -f ${LOCKFILE}
sleep 4
success
else
failure
fi
echo
return ${RETVAL}
}
start()
{
echo -n $"Sending Startup Email: "
echo "${RESTARTBODY}" | mail -s "${RESTARTSUBJECT}" ${EMAIL}
RETVAL=$?
if [ ${RETVAL} -eq 0 ]; then
touch ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
echo "Not applied to service"
;;
restart)
stop
start
;;
reload)
echo "Not applied to service"
;;
condrestart)
#
echo "Not applied to service"
;;
probe)
;;
*)
echo "Usage: SystemEmail{start|stop|status|reload|restart[|probe]"
exit 1
;;
esac
exit ${RETVAL}
@fuzzmz
Copy link
Author

fuzzmz commented Mar 30, 2013

Then all you have to do is run the following commands as root (or elevate with sudo):

  1. make it executable with chmod u+x email.sh
  2. copy it to init.d with cp email.sh /etc/init.d/
  3. make root have ownership of the file with chown root:root email.sh
  4. set it to run automatically via update-rc.d email.sh start 98 2 3 4 5 . stop 02 0 1 6 .

If you want to remove the script you can do so by using sudo update-rc.d -f email.sh remove

You can also test that it is running after step 1 by running ./email.sh start and ./email.sh stop

@chiluap
Copy link

chiluap commented Jan 27, 2016

success and failure are not default debian init-functions.
You might want to use log_success_msg / log_failure_msg.

suggestion:

      log_success_msg "Success sending startup mail: ${RETVAL}"
      log_failure_msg "FAIL: sending startup mail failed with: ${RETVAL}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment