Saturday, May 29, 2010

Yum Check or Install Updates Script

SkyHi @ Saturday, May 29, 2010
Here's a quick script that will check yum updates and email you when there are new updates available.

Split into two sections, one script is for all package updates, and the other script is for letting us know if we need to reboot when a new kernel package has been installed.

Script to check for updates:

check-yum-updates.sh

#!/bin/bash
#
# check-yum-updates.sh
#
# checks for yum updates and emails if there are any available
#
#
# Eric Thern
# Zoidial Incorporated
# http://www.zoidial.com
#
# last update:
# Dec 30, 2008
#

#
# change this to your email
#
email="youremail@youremail.com"

#
# no need to change anything below here
#

yumtmp="/tmp/yum-check-update.$$"
yum="/usr/bin/yum"

$yum check-update >& $yumtmp

yumstatus="$?"

hostname=$(/bin/hostname)

case $yumstatus in
0)
# no updates!
exit 0
;;
*)
date=$(date)
number=$(cat $yumtmp | egrep '(.i386|.x86_64|.noarch|.src)' | wc -l)
updates=$(cat $yumtmp | egrep '(.i386|.x86_64|.noarch|.src)')
echo "
There are $number updates available on host $hostname at $date

The available updates are:
$updates
" | /bin/mail -s "UPDATE: $number updates available for $hostname" $email
;;
esac

# clean up

rm -f /tmp/yum-check-update.*

Script to check kernel (here we use 'ovzkernel' since we're running with an openvz kernel, if you have a stock centos kernel, change this to 'kernel')

check-yum-kernel.sh

#!/bin/bash
email=youremail@youremail.com
latestkernel=$(rpm -q ovzkernel |tail -n1|sed -e 's/kernel-//')

echo "$latestkernel"

if uname -a | grep -qv "$latestkernel"; then
echo "Running Kernel is" `uname -r` "but latest installed rpm is ${latestkernel}" |\
mail -s "UPDATE: ${HOSTNAME} reboot required" $email
fi;

Crontab entries:

30 21 * * * /root/bin/check-yum-updates.sh >/dev/null 2>&1
30 21 * * * /root/bin/check-yum-kernel.sh >/dev/null 2>&1

Run at 9:30 every night. Change times and paths to suit.

REFERENCES
http://thern.org/linux-and-freebsd/yum-update-check-script-runs-via-crontab-and-emails-when-new-updates-are-available/