- How to Install and Configure NTP on Linux
- Introduction
- Installing NTP on Linux
- Configuring NTP
- Add Reference Clock Peers
- Add a Drift File
- Specifying Statistics File Directory
- Example NTP Configuration File
- Enabling and Starting the NTP Service
- Testing and Debugging NTP
- NTP Security
- Debugging
- Troubleshooting
- Синхронизация времени по NTP
- ntpdate
- ntpd
- Установка
- Настройка
- Просмотр статуса
How to Install and Configure NTP on Linux
NTP can be installed and configured on Linux in a few simple steps:
- Install the NTP service.
- Modify the NTP configuration file, ‘/etc/ntp.conf’, with required options.
- Add reference clock peers to the configuration file.
- Add drift file location to the configuration file .
- Add optional statistics directory to the configuration file .
- Enable and start the NTP service.
- Check operation and synchronization status.
Introduction
If you need to keep the system time on your Linux computer accurate, NTP is the solution. Network Time Protocol is a suite of applications that allows computers to coordinate their system time. Here, we describe the simple steps required to install and configure NTP. The process is applicable to most Linux distributions.
Installing NTP on Linux
NTP is available for most Linux distributions, indeed, many install NTP automatically in a default installation.
If NTP is not present on your host system, it can be easily downloaded and installed. You will need root permissions to install the application. Installation also varies slightly depending on which Linux distribution you use:
sudo apt-get install ntp # for Debian/Ubuntu sudo yum install ntp # for CentOS/RHEL sudo dnf install ntp # for Fedora
For more obscure Linux distributions, NTP is available as source code for compilation on a host system.
Configuring NTP
NTP is configured using a configuration file – ntp.conf. The file is generally located in the /etc/ directory, but can be located elsewhere, as specified by the “ntpd -c“ command line option. The file is read by the NTP daemon at start-up. The daemon must be restarted for any modifications to the configuration file to take effect.
The file follows a standard format similar to many other Linux configuration files and can be modified using any standard text editor, such as gedit or nano.
Add Reference Clock Peers
NTP relies on reference clock servers, or peers, in order to synchronize the local system clock. One or more peers can be added to the configuration file, as follows:
The address operand is a domain name or IP address of a NTP server to be used for synchronization.
The ‘prefer’ option may be used to specify a preferred peer. All things being equal, a preferred peer will be selected by NTP from a list of similarly performing peers. The prefer option should only be specified once.
It is also considered best practice to specify an odd number of peers. A time offset that is out of tolerance in any one peer can then be easily detected. The peer can then be discarded by the selection algorithm.
Add a Drift File
NTP uses a drift file to store the frequency offset of the local clock oscillator. The frequency offset is stored in parts-per-million (PPM). The file is updated by the NTP service every hour. It is considered good practice to specify a drift file, since it allows NTP to synchronize the local clock faster on start up. A drift file is specified as follows:
driftfile /var/lib/ntp/ntp.drift.
Specifying Statistics File Directory
You can use the statsdir command in the configuration file to specify a directory where statistics files will be stored. Statistics files are useful to view local clock synchronization performance.
Example NTP Configuration File
As a minimum a configuration file needs to specify a server that should be used for synchronization along with a drift file to store local clock frequency.
server pool.ntp.org # NTP pool project world-wide servers driftfile /var/lib/ntp/ntp.drift.
However, a more complete configuration file will include multiple servers, drift file and a statics directory:
server 192.168.1.127 prefer # Local NTP server IP address server pool.ntp.org # NTP pool project world-wide servers server time-a-g.nist.gov # NIST internet time service driftfile /var/lib/ntp/ntp.drift. statsdir directory_path
Enabling and Starting the NTP Service
NTP can be enabled and started with root permissions using the Linux systemctl command:
sudo systemctl enable ntpd sudo systemctl start ntpd
The NTP service must be restart for any configuration changes to take effect:
sudo systemctl restart ntpd
The service can also be stopped or disabled, as follows:
sudo systemctl disable ntpd sudo systemctl stop ntpd
Testing and Debugging NTP
You can check the operation of the NTP service at any time using the ntpq command.
$ ntpq -p remote refid st t when poll reach delay offset jitter ======================================================================== *192.168.1.127 .GNSS. 1 u 38 64 377 0.792 -9.715 9.039 +ip235.ip-151-80 192.168.100.15 2 u 14 64 377 14.395 0.387 1.848 +time-a-g.nist.g .NIST. 1 u 48 64 377 94.628 2.206 3.809
The command provides a list of configured peers and their associated synchronization performance characteristics.
The first character in the peer list is a tally code that indicates the status of synchronization. If the character is an asterisk (*), then the peer is currently being used for synchronization. This indicates that the local system clock is synchronized to the peer.
Tally code typical values:
‘*‘ – the peer has been declared the system peer and is used for synchronization.
‘+‘ – the peer is in tolerance and used in the combining algorithm. The peer may be used in the event of the system peer being discarded. Other characters generally indicate that the clock has been discarded by the selection algorithm.
Other fields in the peer list are as follows:
Remote – identifies the address of the peer.
Refid – indicates the synchronization source of the peer. Typically GPS or GNSS to indicate a stratum 1 hardware clock. However, it may also be an address if the peer is a lower stratum in the NTP hierarchy. Stratum 1 is the highest level, 15 the lowest.
Type – the peer type – local, unicast, multicast or broadcast. Most peers are accessed in unicast mode.
When – when the last packet was received in seconds.
Poll – the period at which the peer is polled in seconds.
Reach – an octal representation of the synchronization flags.
Delay – the polling round trip delay in milliseconds.
Offset – the current offset, or time difference, between the peer and local system time.
Jitter – a measurement of variance of timing packets from the peer in milliseconds. This is an indication of clock quality. Lower jitter indicates higher quality clock.
NTP Security
NTP security is performed by ‘symmetric key cryptography’ or ‘authentication’ as it is more commonly known. It allows a client to authenticate a server for trusted information exchange.
Authentication is based on a number of agreed keys, or passwords, that are available to both client and server.
When a message is transferred from server to client, it is appended with an encrypted version of one of the keys. Keys are stored in a file called ‘ntp.keys’. The keys are stored in the file in the following format:
1 M AgreedKey 2 M ceNTigraDE541 8 M DeliBERate244 12 M TAIlored 15 M phySIcally 16 M ScaLES723
The first field is a unique key number indicator. The second field denotes the encryption algorithm that should be used to encrypt the key, ‘M’ indicates the most common MD5 encryption. The final field is the actual key itself. Any number of keys can be specified.
As well as the agreed keys, you can also specify which of the keys are trusted. Therefore, a subset of the keys can be specified for use at any particular time. For instance keys 2, 8 and 15 above can be used for use for a specific period. Trusted keys are specified in the NTP configuration file, ‘ntp.conf’, using the trustedkey command with space-separated key numbers:
Debugging
A number of utilities are provided that can be used to debug a NTP installation. Probably the most useful being the ‘ntpq’ program. This is an application that will query an NTP server and can be used to find out if it is working within expected parameters. By using the ntpq program with the ‘-p’ option and specifying the network address of a server:
> ntpq – p 192.168.0.200 # where 192.168.0.200 is the IP address of a NTP server
You should see a response similar to below:
remote refid st t when poll reach delay offset jitter ====================================================== LOCAL(0) .INIT. 16 l 21 64 377 0.000 0.000 0.001 *SHM(0) .GPS. 0 l 53 64 377 0.000 0.009 0.001 SHM(1) .LFa. 0 l – 64 0 0.000 0.000 4000.00
The response indicates the time references that the server is currently utilizing and which is its currently preferred reference.
Troubleshooting
NTP uses UDP port 123 to communicate with a peer. Therefore you must ensure that the port is open in any network firewall. You will also need to leave the port open in any host firewall application. Also, ensure no other NTP client application is in use, such as timesyncd or any third party software.
Синхронизация времени по NTP
NTP — это протокол синхронизации времени по сети. По существу клиенты запрашивают текущее время на сервере и используют его для установки своих собственных часов.
За этим простым описанием скрывается много сложностей — существуют уровни NTP серверов, где первый уровень подключен к атомным часам, а второй и третий уровни серверов распределяют на себя нагрузку по актуальным запросам из интернета. Кроме того клиентское приложение сложнее, чем вы можете подумать — оно компенсирует задержки соединения и регулирует время таким образом, чтобы не навредить другим процессам, запущенным на сервере. Но к счастью вся эта сложность скрыта от вас!
Ubuntu использует ntpdate и ntpd.
ntpdate
Ubuntu стандартно устанавливается с ntpdate и будет запускать его при каждой загрузке один раз для установки времени по NTP серверу Ubuntu.
ntpd
Сервис NTP ntpd вычисляет уход ваших системных часов и постоянно подправляет их, благодаря чему не происходит сильных изменений, что может приводить к непоследовательности в журналах. Ценой этому небольшое расходование мощности процессора и оперативной памяти, но для современного сервера это несущественно.
Установка
Для установки ntpd из терминала введите:
Настройка
Отредактируйте /etc/ntp.conf для добавления/удаления серверов. По умолчанию эти сервера такие:
# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board # on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for # more information. server 0.ubuntu.pool.ntp.org server 1.ubuntu.pool.ntp.org server 2.ubuntu.pool.ntp.org server 3.ubuntu.pool.ntp.org
После изменений конфигурационного файла вам надо перезапустить ntpd:
Просмотр статуса
Используйте ntpq для просмотра дополнительной информации:
# sudo ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +stratum2-2.NTP. 129.70.130.70 2 u 5 64 377 68.461 -44.274 110.334 +ntp2.m-online.n 212.18.1.106 2 u 5 64 377 54.629 -27.318 78.882 *145.253.66.170 .DCFa. 1 u 10 64 377 83.607 -30.159 68.343 +stratum2-3.NTP. 129.70.130.70 2 u 5 64 357 68.795 -68.168 104.612 +europium.canoni 193.79.237.14 2 u 63 64 337 81.534 -67.968 92.792