Thursday, 14 November 2019

Automatic Patch And Reboot on CentOS Server 6 7 or 8

CentOS seems to lack easy commands for automatically patching a server and then rebooting it if anything needs restarting.

Basically I want to run a script via /etc/cronttab at regular intervals to patch a system and reboot if necessary.  Obviously this might cause an outage (very rarely, some service won't restart), so we do it early in the morning, and we don't patch paired systems at the same time.

My script for Centos 6, 7 or 8 is attached below but it's a bit scrappy!   Does anyone have a better way?

(UPDATED 19.6.20: Added 2>&1 stderr redirection to fix issue seen when running from /etc/cronttab on CentOS 8.)


/usr/bin/yum -y -q upgrade

# The needs-restarting util was moved into Yum for Centos 8...
if [[ -e /usr/bin/needs-restarting ]]
     needs_restarting="/usr/bin/yum needs-restarting"

if [[ "`${needs_restarting} 2>&1 | /bin/grep -v 'Failed to read PID' | /usr/bin/wc -l`" != "0" ]]
     /bin/sync ; /bin/sleep 2 ; /sbin/reboot

# If we get here, needs-restarting flagged no stale services...
# ... but we need to see if kernel has been updated!
running=`/bin/uname -r | /bin/sed -e 's/el[6789].*x86_64//'`
installed=`/bin/rpm -q kernel | /bin/sed -e 's/el[6789].*x86_64//' | /bin/sort -V | /usr/bin/tail -n 1 | /bin/sed -e 's/kernel-//'`
#echo In_RAM: ..${running}..
#echo On_DSK: ..${installed}..
if [[ $running != $installed ]]
    /bin/sync ; /bin/sleep 2 ; /sbin/reboot

No comments:

Post a comment

Spammers: please stop wasting my time. All comments are moderated before publication.