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?

#!/bin/bash

/usr/bin/yum -y -q upgrade

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

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


# 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 ]]
then
    /bin/sync ; /bin/sleep 2 ; /sbin/reboot
fi

No comments:

Post a Comment

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