#!/bin/bash # Adds date to output for simple logging log_date() { echo "$(date +%m/%d/%Y\ %H:%M:%S) $1" } help() { echo "yum-autoupdate is a cron job script to automatically update system packages on CWP servers. The cron job that runs this script exists in /etc/cron.d/yum_autoupdate USAGE: yum-autoupdate [--disable|--enable] --disable Touches /etc/disable-auto-updates file to stop script from running updates --enable Remove /etc/disable-auto-updates file to resume automatic updates via cron -h --help Show this message and exit " } disable_update() { if ! [[ -f /etc/disable-auto-updates ]]; then touch /etc/disable-auto-updates && \ echo "Disabled automatic yum updates" else echo "Automatic yum updates are already disabled" fi } enable_update() { if [[ -f /etc/disable-auto-updates ]]; then rm -f /etc/disable-auto-updates && \ echo "Enabled automatic yum updates" else echo "Automatic yum updates are already enabled" fi } # Run yum updates and log results with time stamps run_update () { log_date "Beginning automatic yum updates cron..." pid_file=yum_autoupdate.pid pid=$(grep -oP '\d+' $pid_file 2>/dev/null) pid=${pid:=-1} # Make sure this script isn't already running if grep -Eq 'yum-autoupdate' /proc/$pid/cmdline 2>/dev/null; then log_date "Existing $pid_file process found with PID $pid" exit 1 fi echo $$ > $pid_file if ! yum clean expire-cache &>/dev/null; then log_date "Failed to 'yum clean expire-cache" fi log_date "Initiating package updates..." if ! yum -y update -d 1; then log_date "Routine yum updates failed" else log_date "Routine yum updates completed." fi } # Command line options while [[ "${#}" -gt 0 ]]; do case "${1}" in -h|--help) help exit ;; --disable) disable_update exit ;; --enable) enable_update exit ;; *) echo -e "Invalid argument '${1}'\n" help exit ;; esac done # Run updates unless disabled if ! [[ -f /etc/disable-auto-updates ]]; then run_update else log_date "Automatic yum updates are currently disabled. Exiting." fi