How to check if NTPD updates machine’s time successfully using shell

ntpdtime

I'm trying to use NTPD to update my Linux machine's time to a specified NTP server.
Here is the scenario:

Each time the Linux machine starts up, I want to update the time from NTP server and if it's not successful, I want to try again every 5 minutes until successfully (max is 2 hours).

I searched around and find that I should(?) use NTPD and use some command like:

#ntpdate ntp.server.com (before starting NTPD)
#ntpd some_options_to_start

The questions are:

  1. How can I know if the time was successfully updated by these commands?
  2. Can I set the interval to update time from ntpd? (or I have to use something like sleep and loop with do..while/for in shell?)

Note that I want to execute the above commands in a shell script and will put the shell in a web server. Then clients (with a web browser browser) will execute the script on the website. So I need to check if the update is successful or not to send result to the client (over the web).

Best Answer

Using a script to monitor ntpd is not commonly done. Usually a monitoring tool like nagios or munin is used to monitor the daemon. The tool can send you an alert when things go wrong. I have munin emailing me if the offset exceeds 15 milliseconds.

Normally, you should use an odd number of servers so that the daemon can perform an election among the servers if one goes off. Three is usually adequate, and more than five is excessive. Clients on your internal network should be able to get by with one internal server if you monitor it. Use legitimate servers or your ISPs NTP or DNS servers as clock sources. There are public pools as well as public servers.

ntpd is self tuning and you should not need to adjust it once it is configured and started. With recent ntpd implementations you can drop use of ntpdate entirely as they can do the initial setting of the date.

The following script will parse the offsets in the output of ntpd and report an excessive offset. You could run it from cron to email you if there are problems. The script defaults to alerting on an offset of 0.1 seconds.

#!/bin/bash
limit=100   # Set your limit in milliseconds here
offsets=$(ntpq -nc peers | tail -n +3 | cut -c 62-66 | tr -d '-')
for offset in ${offsets}; do
    if [ ${offset:-0} -ge ${limit:-100} ]; then
        echo "An NTPD offset is excessive - Please investigate"
        exit 1  
    fi  
done
# EOF
Related Question