Auto-update Ubuntu server with email notifications

It’s useful to have a script to keep the packages on your server up to date. On the desktop there is a GUI auto-update tool which is active by default. The caveat is that you don’t want updates to break your server without you realising.

This script is adapted slightly from the Ubuntu wiki to do a ‘safe-upgrade’ and to mail directly rather than using an external SMTP server. It also tails the output of the update since it’s pretty long. Use at your own risk etc., script is below. Copy to /etc/cron.weekly and chmod +x.

#!/bin/bash
#
# use aptitude to automatically install updates. log and email any
# changes.
#

#
# variables to change
#

# address to send results to
MAILTO=[email protected]

#
# script is below here (do not change)
#

tmpfile=$(mktemp)

#
# actually run aptitude to do the updates, logging its output
#

echo -e "aptitude update\r\n..." >> ${tmpfile}
aptitude update | tail >> ${tmpfile} 2>&1
echo "" >> ${tmpfile}
echo "aptitude safe-upgrade" >> ${tmpfile}
aptitude -y safe-upgrade >> ${tmpfile} 2>&1
echo "" >> ${tmpfile}
echo "aptitude clean" >> ${tmpfile}
aptitude clean >> ${tmpfile} 2>&1

#
# i get a lot of escaped new lines in my output. so the following
# removes them. this could be greatly improved

tmpfile2=$(mktemp)
cat ${tmpfile} | sed 's/\r\r/\n/g'|sed 's/\r//g' > ${tmpfile2}
mv ${tmpfile2} ${tmpfile}

#
# now send the email (and ignore output)
#
mail -s "Aptitude Upgrade $(date)" ${MAILTO} < ${tmpfile} &> /dev/null

#
# and remove temp files
#

rm -f ${tmpfile}

comments powered by Disqus