#!
/bin/bash
# time-offset_check.sh
#
# Checks computer clock against specified NTP server. Issues a warning
# on stdout, if the time difference exceeds limit. Requires ntpdate, bc
# and egrep in path. Run from cron as often as you like.
### Options
DATE=`date +%Y%m%d`
LOGFILE=/var/log/ntpstats/time_sync_${DATE}
if [[ `ps -ef | grep ntpd | grep -v grep | wc -l` -eq 0 ]]; then
systemctl start ntpd
fi
SERVER=$(/sbin/ntpq -p |grep '*' | awk '{print $1}' | cut -d\* -f2)
NTPSERVER=${SERVER} # i.e. random server from pool.ntp.org
LIMIT='1.000000' # i.e. 1.000000 (= 1 second)
OLD_OFFSET=`ntpdate -q $NTPSERVER \
| egrep -o -m 1 -e "offset ((-)?[0-9]+\.[0-9]+)" \
| egrep -o -e "[0-9]+\.[0-9]+"`
RESULT=`echo "$OLD_OFFSET >= $LIMIT" | bc`
if (("$RESULT" == 1)); then
systemctl stop ntpd
sleep 1
/usr/sbin/ntpdate -s -b -p 8 -u $NTPSERVER
sleep 1
systemctl start ntpd
if [[ `ps -ef | grep ntpd | grep -v grep | wc -l` -eq 0 ]];
then
logger -p local6.warn -t WARNING NTP: NTP Process
did not startup after attempting to sync. Please start ntp process.
fi
# Checking date for auto adjustment...
NEW_OFFSET=`ntpdate -q $NTPSERVER \
| egrep -o -m 1 -e "offset ((-)?[0-9]+\.[0-9]+)" \
| egrep -o -e "[0-9]+\.[0-9]+"`
RESULT=`echo "$NEW_OFFSET >= $LIMIT" | bc`
if (("$RESULT" == 1)); then
logger -p local6.warn -t WARNING NTP: Local
clock offset ${NEW_OFFSET}, deviation is greater than ${LIMIT} second.
else
logger -p local6.warn -t WARNING NTP: Local
clock offset ${NEW_OFFSET} is below ${LIMIT} second. Auto-adjustment completed
successfully. Offset prior to adjustment ${OLD_OFFSET}. User interven tion is
not required. This is an informational message.
fi
fi
ntpstat | {
while read line; do
if [[ `echo $line |grep synchronised | wc -l` -eq 1 ]]; then
FLAG=1
fi
if [[ $FLAG -eq 1 ]]; then
echo "`date` $line" >> $LOGFILE
fi
done
}
exit 0