I am implementing a script that checks every half hour that my server has the time correctly synchronized with ntpd
, since there is an external process that from time to time hangs and modifies the system time.
The first solution that occurred to me is this:
#!/bin/bash
#BORRAMOS LOG ANTERIOR
rm -f /root/sync_ntpd/control_restart_ntpd.log
rm -f /root/sync_ntpd/control_ntpd.log
#DECLARO VARIABLES DE CONTROL
control=0
fallo=1
#COMPROBAMOS QUE EL LOG NO CONTENGA FAILED EN EL RESTART
while [[ $control -lt 3 ]] && [[ $fallo -eq 1 ]]
do
control=$((control+1))
service ntpd restart >> /root/sync_ntpd/control_ntpd.log
echo "Reinicio servicio NTPD | Intento $control de 2" >> /root/sync_ntpd/control_restart_ntpd.log
echo "----------------------------------------------" >> /root/sync_ntpd/control_restart_ntpd.log
while read linea
do
if [[ $linea =~ "FAILED" ]]
then
echo "Ha habido un fallo al reiniciar el servicio" >> /root/sync_ntpd/control_restart_ntpd.log
echo "" >> /root/sync_ntpd/control_restart_ntpd.log
echo "" >> /root/sync_ntpd/control_restart_ntpd.log
rm -f /root/sync_ntpd/control_ntpd.log
else
fallo=0
fi
done < /root/sync_ntpd/control_ntpd.log
done
echo "Servicio reiniciado correctamente" >> /root/sync_ntpd/control_restart_ntpd.log
echo "" >> /root/sync_ntpd/control_restart_ntpd.log
echo "" >> /root/sync_ntpd/control_restart_ntpd.log
But I don't know if there is any way to check if the time is correctly synchronized so that if it isn't, it does the service ntpd restart
.
In your case, I would use the command
ntpsstat
. According to the man:You could use this command in your script. If it returns 0 everything is fine, if it returns 1 it is not synchronized, and if it returns 2 it means that it cannot connect to the ntpd server.
You could do something like:
he
$?
returns the status of the last command executed (in this case, ntpstat). According to that we make a switch (case
in bash)Adapt the script to your needs (in case you need to save the log, synchronize ntpd...) The important thing would be to execute the command and check the result with
$?
. The rest of your script I leave to your discretion.