ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Linux for Users: Keeping Time with NTP

Updated on November 23, 2011

The Network Time Protocol is one of those Internet services that many casual and small business users don't think they'll need--until the data on their computer needs to be synchronized with the data on another machine.

Fortunately, the NTP service is easy to implement, even on notebooks that have an intermittent network connection. Adding the service can save you headaches in the future, when your files need to be synchronized with those of another system, which, of course, often occurs when you least expect that you'll need one or more systems' clocks to be in sync.

Briefly, the NTP daemon on a computer connects periodically with one or more Internet time servers, which in turn are connected to a primary server (called a, "Stratum 1," server) that itself is connected directly to a reference clock at places like the National Institute of Standards and Technology or the U.S. Naval Observatory, and is synchronized with other reference clocks. The NTP daemon compares your computer's time against the server's time, and adjusts your computer's system clock to the reference clock's time, and measures the amount by which your system's clock varies from the reference clock.

Operating systems measure time in Coordinated Universal Time (UTC). Linux, like most operating systems, have a lot of software for translating UTC into local time. But the system's clock is not necessarily the actual time, as we'll discuss a little further on.

The first thing to do is make sure that the NTP daemon is running. Most Linux distributions provide a NTP package, which you can install it if it isn't already present.

To find out if the NTP client is running, check for its entries in the system's log.

# grep ntpd /var/log/daemon.log

If you're using Ubuntu, superuser commands get executed using, "sudo."

$ sudo grep ntpd /var/log/daemon.log

If you see log entries from, "ntpd," or the, "ntpdate," programs, then you're already set. If, however, you need to install the NTP client package, it's called, simply, "ntp," in the Debian/GNU, Red Hat, and Ubuntu distributions, and you can install it with aptitude, yum, or whatever package utility your Linux version uses. If your operating system doesn't provide a NTP package, you can find the source code at http://www.ntp.org/ and install that by following the directions in the package.

Configuring NTP from Scratch

If you install the NTP daemon yourself, then you'll need to provide a configuration for it. The primary configuration file is named, "/etc/ntp.conf," and most distributions provide a separate manual page for it. If you need to write a configuration file, the first step is to find at least two, or preferably three, public time servers on the Internet. Again, ntp.org maintains a list of public time servers, at http://support.ntp.org/bin/view/Servers/WebHome/.

Because the NTP daemon can itself act as a server, in a basic configuration you probably want to make sure that your other systems can query it, but not modify the local time. The NTP daemon provides statements that restrict what other systems can do with the NTP daemon.

So here's a brief, "/etc/ntp.conf," file, from my Debian/GNU Linux system.

# Public time servers from the Debian/GNU pool.
server 0.debian.pool.ntp.org iburst dynamic
server 1.debian.pool.ntp.org iburst dynamic
server 2.debian.pool.ntp.org iburst dynamic
server 3.debian.pool.ntp.org iburst dynamic

# Allow our machine to query and modify its own time.
restrict 127.0.0.1
restrict ::1

# Allow other systems access to the server, but don't
# allow queries or modifications.
restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery

You also want to make sure that the service is enabled, by providing the following entries in, "/etc/services." As is usual for Internet services, these entries comply with Internet conventions, and you should not need to modify them.

ntp   123/tcp
ntp   123/udp

Starting the NTP Daemon

Most Linux distributions use a standard UNIX System V startup configuration. That means the scripts that start and stop services reside in, "/etc/init.d," and have a common interface. To start the NTP daemon, enter a command like this one.

# /etc/init.d/ntp start

There is often a, "README," file in the, "/etc/init.d," directory, which describes the details of how to automatically start services like the NTP daemon during system initialization. If there isn't, then your Linux distribution should provide the information somewhere within its documentation, and you can search for it.

Using NTP with an Intermittent Internet Connection

The, "ntpd," daemon, like most Internet servers, is designed to be used with desktop machines that have a permanent connection to the Internet. But if you travel and use a notebook that connects to wireless networks, there are alternative methods for finding the time. The, "ntpd," daemon also provides options for interactive use. For example, if you just want to set the time, enter a command like this.

# /usr/sbin/ntpd -q         # Use the actual path to ntpd.
ntpd: time slew +0.053562s

On a system that is operating normally, the NTP daemon limits the amount by which it adjusts the system clock. If you want a report of what, "ntpd," is doing, you can specify a different log file to print reports to. That makes it easy to provide regular reports of, "ntpd's," activities, if you happen to like receiving system reports via e-mail.

# /usr/sbin/ntpd -q -l /tmp/ntp.log && cat /tmp/ntp.log | \
  mailx -s "NTP Update" root@localhost; rm -f /tmp/ntp.log

You can, of course, put this into a script and add an entry to the root, "crontab," to execute it in the background. But since the system's Internet connection is intermittent, we'll also add a check to make sure that we're connected. So a more complete script would look like this.

#!/bin/bash

# Actual paths of the programs the script uses.
NTPD=/usr/sbin/ntpd     
IFCONFIG=/sbin/ifconfig 
GREP=/bin/grep          
MAIL=/usr/bin/mailx

# The inteface that you connect to the Internet with.
IFACE=wlan0 

LOGFILE=/tmp/ntp.log      # Temp files should go in /tmp.
NTPDOPTS="-q -l $LOGFILE" # The ntpd daemon's options.

if [ ! -z "`$IFCONFIG $IFACE | $GREP UP`" ]; then
    $NTPD $NTPDOPTS && cat $LOGFILE | \
	$MAIL -s "NTP Update" root@localhost; \
	rm -f $LOGFILE
fi

Place this script in a convenient directory, as for example, "/usr/local/bin/ntp.sh." (Remember to, "chmod +x ntp.sh.") Then add a line like the following to the root crontab.

0 0,6,12,18 * * * /usr/local/bin/ntp.sh

This runs the script every six hours. If the machine is connected to the Internet, then, "ntpd," updates the system time and mails you a report of the activity.

By the way, you might find yourself receiving another e-mail message, from the, "cron," daemon itself. If you find this is too much reporting, then you can adjust which messages you receive. Consult the crontab(5) manual page to find out how the daemon itself notifies you of background tasks (type, "man 5 crontab," for the manual page).

The System Clock and the Hardware Clock

Above, I mentioned briefly that both the Network Time Protocol and UNIX-type systems like Linux keep time in Coordinated Universal Time (UTC). The system clock in its most basic form is simply an integer that increments every second--plus or minus a millisecond or so.

As you're probably aware, the computer's hardware also contains its own clock and maintains the time with a CMOS battery when the system is powered down. When the operating system boots, it sets its clock from the hardware clock.

As you're probably also aware, batteries can degrade with age, causing the hardware clock's accuracy to become questionable or even cause the clock to fail completely. And as you may not be aware, computer's clocks, even those of high end servers, can drift by a second or two daily, even with new equipment.

But because we have NTP running on the system, we can also use it to set the hardware clock. Most Linux distributions provide a utility, called, "hwclock," that allows the administrator to set and read the system's hardware clock. The, "hwclock," program has many options, but because, "ntpd," has already done the work of setting the system clock, we can use its value directly.

So to simply set the hardware clock from the system clock, use the following command.

# hwclock -w  # Or, hwclock --systohc

How often you want to do this depends on the system's accuracy and the nature of, "ntpd's," connection with Internet time servers. Since we don't want to modify the system's startup scripts unnecessarily, we'll simply add this to our, "ntp.sh," script from the previous section, so when, "ntpd," updates the system clock, the, "ntp.sh," script updates the hardware clock also, with a line similar to the command above. So a, "ntp.sh," script that also updates the hardware clock after consulting a time server and adds its output to the, "ntpd," log report, looks like this.

#!/bin/bash

# Actual paths of the programs the script uses.
NTPD=/usr/sbin/ntpd     
IFCONFIG=/sbin/ifconfig 
GREP=/bin/grep          
MAIL=/usr/bin/mailx
HWCLOCK=/sbin/hwclock

# The inteface that you connect to the Internet with.
IFACE=wlan0 

LOGFILE=/tmp/ntp.log      # Temp files should go in /tmp.
NTPDOPTS="-q -l $LOGFILE" # The ntpd daemon's options.
HWCLOCKSETOPTS="-w"
HWCLOCKSHOWOPTS="--show"

if [ ! -z "`$IFCONFIG $IFACE | $GREP UP`" ]; then
    $NTPD $NTPDOPTS ;
    $HWCLOCK $HWCLOCKSETOPTS;
    echo "Hardware clock adjustment:" >>$LOGFILE;
    $HWCLOCK $HWCLOCKSHOWOPTS >>$LOGFILE;
    cat $LOGFILE | \
	$MAIL -s "NTP and Hardware Clock Update" root@localhost;
    rm -f $LOGFILE;
fi


working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)