How to set up time synchronization on ubuntu 16.04
Содержание:
- NTPD
- Настройка netfilter (iptables) для NTP сервера
- Time zone
- Настройка сервера ntp в Debian
- Синхронизация времени по NTP
- Как установить и настроить NTP-сервер
- Время и дата в Ubuntu Server
- Configuration
- System clock
- II. Configure NTP Client to Synchronize with NTP Server
- Получить список доступных часовых поясов
- Настройка клиентов сервера времени
- periodic.conf status-ntpd
- Difference Between Chronyd and Ntpd
NTPD
Installation
While the NTP daemon is older than chronyd it is still widely used, by default it is not installed in CentOS 7 so you will first need to install it. You should check if chrony is already installed and perhaps disable the service or remove the package to prevent any conflicts. Ntpd can be installed as shown below.
yum install ntp -y
Once installed we want to make sure that the ntpd service starts up automatically on boot so that we can maintain accurate time.
systemctl enable ntpd
By default after installing the package the service will not be running, start ntpd if it’s not already running.
systemctl start ntpd
See our guide on managing systemd services with systemctl if you need further information on this.
Configuration
The configuration for ntpd is stored in the /etc/ntp.conf file. This file specifies the NTP servers to synchronize with in the same format as chrony, below is an example of the default configuration that already exists out of the box after installing ntpd.
~]# cat /etc/ntp.conf ... server 0.centos.pool.ntp.org iburst server 1.centos.pool.ntp.org iburst server 2.centos.pool.ntp.org iburst server 3.centos.pool.ntp.org iburst ...
This default configuration is enough for the server to start synchronizing time with NTP.
Management
With ntpd we can perform various management tasks. The ntpq command allows us to query and monitor the NTP daemon, ntpd. For instance we can view information about known NTP peers in a similar way to the ‘chronyc sources’ command with chrony.
~]# ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +node02.au.verbn 210.9.192.50 2 u 15 64 177 2.280 -0.791 8.727 -cachens2.onqnet 3.109.212.154 3 u 7 64 177 13.818 0.138 9.007 *hosting.wireles 203.35.83.242 2 u 14 64 177 1.089 -11.553 9.183 +ns2.tti.net.au 203.35.83.242 2 u 14 64 177 14.627 -4.516 9.209
The ntpstat command can be used to quickly show the time synchronization status.
~]# ntpstat synchronised to NTP server (203.23.237.200) at stratum 3 time correct to within 253 ms polling server every 64 s
The ntpdate command has been retired but is still available to set the date and time via NTP, the command below forces a synchronization to the time server specified, in this case pool.ntp.org.
~]# ntpdate pool.ntp.org 20 Sep 18:53:12 ntpdate: adjust time server 125.255.139.115 offset 0.014167 sec
This functionality has been replaced by ‘ntpd -q’. By default this will not update the hardware clock, to do that edit the /etc/sysconfig/ntpdate file and add “SYNC_HWCLOCK=yes” which is set to no by default, this will ensure the hardware clock is updated after a successful nptdate. This should also allow the system clock to automatically update the hardware clock every 11 minutes.
Настройка netfilter (iptables) для NTP сервера
Настроив работу сервера, неплохо было бы его защитить. Мы знаем, что сервер работает на 123/udp порту, при этом запросы так же отправляются с порта 123/udp. Ознакомившись со статьей, что такое netfilter и правила iptables и ознакомившись с практическими примерами iptables, можно создать правила фильтрации сетевого трафика:
ntp ~ # iptables-save # типовые правила iptables для DNS *filter :INPUT DROP :FORWARD DROP :OUTPUT DROP -A INPUT -i lo -j ACCEPT -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -m conntrack --ctstate INVALID -j DROP # разрешить доступ локальной сети к NTP серверу: -A INPUT -s 192.168.1.1/24 -d 192.168.1.1/32 -p udp -m udp --dport 123 -m conntrack --ctstate NEW -j ACCEPT -A OUTPUT -o lo -j ACCEPT -A OUTPUT -p icmp -j ACCEPT -A OUTPUT -p udp -m udp --sport 32768:61000 -j ACCEPT -A OUTPUT -p tcp -m tcp --sport 32768:61000 -j ACCEPT -A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT # разрешить доступ NTP серверу совершать исходящие запросы -A OUTPUT -p udp -m udp --sport 123 --dport 123 -m conntrack --ctstate NEW -j ACCEPT COMMIT
Это типовой пример! Для задания правил iptables под Ваши задачи и конфигурацию сети, необходимо понимать принцип работы netfilter в Linux, почитав вышеуказанные статьи.
Time zone
To check the current zone defined for the system:
$ timedatectl status
To list available zones:
$ timedatectl list-timezones
To set your time zone:
# timedatectl set-timezone Zone/SubZone
Example:
# timedatectl set-timezone Canada/Eastern
This will create an symlink that points to a zoneinfo file under . In case you choose to create the link manually (for example during chroot where will not work), keep in mind that it must be a symbolic link, as specified in :
# ln -sf /usr/share/zoneinfo/Zone/SubZone /etc/localtime
Tip: The time zone can also be selected interactively with tzselect.
See , and for details.
Setting based on geolocation
Note: Some desktop environments have support for automatic time zone selection (e.g. see ).
To set the timezone automatically based on the IP address location, one can use a geolocation API to retrieve the timezone, for example , and pass the output to for automatic setting. Some geo-IP APIs that provide free or partly free services are listed below:
Update timezone every time NetworkManager connects to a network
Create a :
/etc/NetworkManager/dispatcher.d/09-timezone
#!/bin/sh case "$2" in up) timedatectl set-timezone "$(curl --fail https://ipapi.co/timezone)" ;; esac
Настройка сервера ntp в Debian
Теперь настроим свой сервер времени, с которого другие наши сервера смогут синхронизировать свои часы. Сервер времени ntp использует отдельный одноименный протокол — Network Time Protocol, который для работы использует UDP порт 123. Перед установкой и настройкой службы времени убедитесь, что на фаерволе открыт этот порт.
Файл конфигурации ntp — /etc/ntp.conf. Привожу минимальную достаточную конфигурацию для своего сервера времени.
driftfile /var/lib/ntp/ntp.drift restrict -4 default kod notrap nomodify nopeer noquery limited restrict 127.0.0.1 restrict 192.168.155.0 mask 255.255.255.0 nomodify notrap pool 0.debian.pool.ntp.org iburst pool 1.debian.pool.ntp.org iburst pool 2.debian.pool.ntp.org iburst pool 3.debian.pool.ntp.org iburst logfile /var/log/ntp.log
Так же я обычно отключаю ipv6 протокол, если он не используется. Для этого в файле /etc/default/ntp заменяем параметр на
NTPD_OPTS='-4 -g'
После изменения конфигурации, перезапустим ntp и проверим статус службы.
# systemctl restart ntp # systemctl status ntp
Теперь убедимся, что она запущена.
# ss -tulnp | grep ntp udp UNCONN 0 0 192.168.155.102:123 0.0.0.0:* users:(("ntpd",pid=6185,fd=18)) udp UNCONN 0 0 127.0.0.1:123 0.0.0.0:* users:(("ntpd",pid=6185,fd=17)) udp UNCONN 0 0 0.0.0.0:123 0.0.0.0:* users:(("ntpd",pid=6185,fd=16))
Все в порядке, служба ntp запущена и готова принимать подключения. Для примера синхронизирую время одной из windows машин с нашим сервером времени.
Теперь другие компьютеры и серверы могут синхронизировать свои часы с нашего сервера Debian, где мы настроили ntp службу в качестве источника времени для остальных.
Если в логе /var/log/ntp.log увидите сообщение — kernel reports TIME_ERROR: 0x2041: Clock Unsynchronized, не обращайте внимание. Это не ошибка, а информационное сообщение, говорящее о том, что в момент запуска ntp ядро еще не синхронизировало свое время
Синхронизация времени по NTP
NTP – это протокол синхронизации времени по сети. По существу клиенты запрашивают текущее время на сервере и используют его для установки своих собственных часов.
За этим простым описанием скрывается много сложностей – существуют уровни NTP серверов, где первый уровень подключен к атомным часам, а второй и третий уровни серверов распределяют на себя нагрузку по актуальным запросам из интернета. Кроме того клиентское приложение сложнее, чем вы можете подумать – оно компенсирует задержки соединения и регулирует время таким образом, чтобы не навредить другим процессам, запущенным на сервере. Но к счастью вся эта сложность скрыта от вас!
Ubuntu использует ntpdate и ntpd.
ntpdate
Ubuntu стандартно устанавливается с ntpdate и будет запускать его при каждой загрузке один раз для установки времени по NTP серверу Ubuntu.
Сервис NTP ntpd вычисляет уход ваших системных часов и постоянно подправляет их, благодаря чему не происходит сильных изменений, что может приводить к непоследовательности в журналах. Ценой этому небольшое расходование мощности процессора и оперативной памяти, но для современного сервера это несущественно.
Настройка
Отредактируйте /etc/ntp.conf для добавления/удаления серверов. По умолчанию эти сервера такие:
После изменений конфигурационного файла вам надо перезапустить ntpd:
Ссылки
Смотрите страницу энциклопедии Ubuntu Time для дополнительной информации.
Следить за актуальностью времени на всех узлах локальной сети удобнее с помощью сервера синхронизации времени NTP. В инструкции рассказано об установке и настройке такого сервера на Linux Ubuntu Server 16.04. Данное руководство можно использовать для настройки ntpd на любом другом Linux (например, Debian или CentOS).
Как установить и настроить NTP-сервер
Чтобы синхронизировать время, используют демон ntpd, который может быть как сервером, принимающим время из удаленных хостов, так и клиентом, раздающим время сторонним хостам. Демон ntpd зависит от указанных в файле конфигурации настроек.
Для установки сервера NTP используется стандартный менеджер пакетов $ sudo apt-get install ntp.
После установки все необходимые настройки NTP будут находиться в файле /etc/ntp.conf.
Первая строчка файла конфигурации – driftfile /var/lib/ntp/ntp.drift. В ней указан файл, в котором хранится информация о том, как часто смещается время. В этом же файле содержится и значение, которое было получено из предыдущих изменений времени. Если по каким-то причинам внешние NTP-серверы недоступны, знание берут из этого файла.
После этого нужно указать файл, сохраняющий логи синхронизации – logfile /var/log/ntp.log.
В файле конфигурации нужно указать перечень серверов NTP, с которыми нужно синхронизироваться. По умолчанию этот перечень выглядит вот так:
- server 0.ubuntu.pool.ntp.org
- server 1.ubuntu.pool.ntp.org
- server 2.ubuntu.pool.ntp.org
- server 3.ubuntu.pool.ntp.org
Эти строки означают группу серверов, которые сообщают серверу верное время. Через опцию iburst можно увеличить точность синхронизации, то есть указать то, что на сервер необходимо отправлять несколько пакетов вместо одного:
- server 0.ubuntu.pool.ntp.org iburst
- server 1.ubuntu.pool.ntp.org iburst
- server 2.ubuntu.pool.ntp.org iburst
- server 3.ubuntu.pool.ntp.org iburst
Еще можно донести информацию о нужном сервере через опцию prefer:
server 0.ubuntu.pool.ntp.org iburst prefer
Время и дата в Ubuntu Server
Как я уже сказал во введении, следить за системным временем в ubuntu server нужно в обязательном порядке, как и в любом другом сервере. Начальные настройки вы делаете еще во время установки системы. Далее вам может понадобиться либо изменение часового пояса, либо более точная настройка и синхронизация часов.
Кстати, если вам интересно узнать, почему я лично использую именно ubuntu server, а не какой-то другой linux дистрибутив, то читайте мой обзор и сравнение ubuntu с другими системами.
Особенно актуальной тема системного времени становится, когда вы арендуете сервера где-то в другой стране с отличным от вашего часового пояса. По умолчанию, у хостера скорее всего будет установлен его часовой пояс. Иногда я забываю это проверить и замечаю только тогда, когда возникают какие-то проблемы. А вот список проблем, которые могут теоретически возникнуть, если на сервере будет неправильное время:
- При просмотре логов или разборе инцидентов придется сначала переводить время в свой часовой пояс или формат, чтобы адекватно разобраться в ситуации.
- Если у вас настроена какая-то интеграция с доменной структурой Windows, расхождение по времени может приводить к проблемам.
- При использовании cron и автоматических заданий для выполнения, неправильное время на сервере может удивить вас тем, что ваши задачи будут выполнены не тогда, когда вы этого ожидаете.
- Если на сервере работает web сайт или почтовый сервис, время публикации постов или отправления писем будет неправильным, что создаст неудобство пользователям.
Это список, что первым делом приходит на ум. Думаю, его можно сильно расширить, если потратить чуть больше времени. Но не вижу в этом смысла. Думаю, и так понятно, что часы на сервере должны всегда показывать точное время в нужном вам часовом поясе. Этим мы и займемся далее.
Утилита date
Посмотреть время в командной строке Ubuntu можно с помощью команды date.
date
В данном случае вы видите следующую информацию:
Fri | День недели, пятница |
26 | Число месяца |
Mar | Месяц, март |
2021 | Год |
02:01:59 | Время в формате час:минута:секунда |
PM | Время суток в 12-ти часовом формате, PM — после полудня |
UTC | Часовой пояс |
Для того, чтобы посмотреть время в 24-х часовом формате в консоли ubuntu, можно использовать дополнительный ключ к команде, добавив туда еще и саму дату:
date +"%H:%M %d/%m/%Y" 14:09 26/03/2021
Таким образом, с помощью параметров форматирования, вы можете выбирать любой формат времени для отображения. Традиционно, командная строка linux позволяет очень гибко выполнять различные действия с помощью своих утилит. Например, вы можете посмотреть не только время и дату, но и вывести в консоль номер дня недели, добавив дополнительный ключ %j:
date +"%H:%M %d/%m/%Y %j" 14:13 26/03/2021 085
Узнать время сервера в unix формате можно вот так:
date '+%s' 1616768183
Если у вас часовой пояс отличный от UTC, а вы хотите увидеть время именно в этом часовой поясе, то воспользуйтесь следующим ключом команды:
date --utc
Очень удобно использовать утилиту date с различными параметрами в скриптах, чтобы получать время в удобном для вас формате. Например, когда вы используете время в названиях файлов бэкапов при их создании. Вот несколько примеров наиболее часто используемых форматов отображения даты и времени:
date +%Y-%m-%d 2021-03-26 date +%H:%M:%S 14:36:35 date +%Y-%m-%d_%H:%M:%S 2021-03-26_14:36:42
Утилита timedatectl
В составе systemd есть своя утилита для просмотра и настройки времени через консоль — timedatectl. Далее пример с ее участием для просмотра системного времени сервера ubuntu.
timedatectl
Local time | Локальное время данного сервера |
Universal time | Время в часовом поясе UTC |
RTC time | Время на аппаратных часах |
Time zone | Ваш часовой пояс |
С просмотром в консоли текущего времени сервера разобрались, переходим к его настройке.
Configuration
Ntp-client
The service ntp-client is used for one-time sync, usually during bootup. Its purpose is to help with the ntpd startup, as ntpd initially waits before attempting to correct the clock skew, and may even refuse to do so if the skew is too large.
Starting the ntp-client service will run the sync only once. It is then expected that ntpd is used for maintaining the time until the next reboot.
NoteDuring boot, ntp-client service will run before ntpd service. It’s safe to have both in the same (default) runlevel.
ImportantRelying solely on the one-time bootup sync is not recommended for long running deployments, such as servers.
Upstream servers
To adjust ntp-client’s command and upstream servers, edit the ntp-client configuration file. The default configuration is populated with:
FILE
NTPCLIENT_CMD="ntpdate" NTPCLIENT_OPTS="-s -b -u \ 0.gentoo.pool.ntp.org 1.gentoo.pool.ntp.org \ 2.gentoo.pool.ntp.org 3.gentoo.pool.ntp.org"
Usage
To run the ntpdate sync command manually:
To run the ntp-client:
To have the ntp-client run at boot:
systemd
To run the client service:
To have the client service run at boot:
Upstream servers
In /etc/ntp.conf the servers that will be used to synchronize the local time for ntpd can be specified. The default configuration is populated with:
FILE
server 0.gentoo.pool.ntp.org server 1.gentoo.pool.ntp.org server 2.gentoo.pool.ntp.org server 3.gentoo.pool.ntp.org
NoteTime zones and location of the server do not matter for NTP; it synchronizes via UTC.
Network not always available?
On systems where a network connection is not always available at boot (laptops, portable computers, etc.), it is useful to add the following lines to server configuration:
FILE
server 127.127.1.0 fudge 127.127.1.0 stratum 10
This sets localhost as a server with low priority, so that the ntp daemon will start properly even without a network connection and will switch to using network servers when a network connection has been (re)established.
Permissions
Permission are used to control who is allowed to synchronize or change permissions.
To enable time syncing, the ntpd server must be reachable by the other ntp services. can be used for blocking.
To prevent other machines from reconfiguring the server, use .
FILE
# Default configuration: # - Allow only time queries, at a limited rate, sending KoD when in excess. restrict default nomodify nopeer noquery limited kod restrict 127.0.0.1
Access to NTP service allowed only from the 192.0.2.0/24 network:
FILE
# To allow machines within the local network to synchronize # their clocks with this server, but ensure they are # not allowed to configure the server or used as peers # to synchronize against restrict 192.0.2.0 mask 255.255.255.0 nomodify nopeer notrap
To deny access to monlist functionality, used for querying traffic stats, but which may also be exploited in a Denial of Service attack:
FILE
disable monitor
Usage
To start the ntpd service:
To have the ntpd service start at boot:
To monitor status of the ntpd service:
systemd
To start the ntpd service:
To have the ntpd service start at boot:
To monitor status of the ntpd service:
Troubleshooting
If ntpd is already running in daemon mode, it will automatically exit when attempting to be manually run from the commandline.
For example:
ntpd -q -g 22 Jan 02:13:08 ntpd: ntpd 4.2.8p15@1.3728-o Fri Jul 2 16:04:29 UTC 2021 (1): Starting 22 Jan 02:13:08 ntpd: Command line: ntpd -q -g 22 Jan 02:13:08 ntpd: ---------------------------------------------------- 22 Jan 02:13:08 ntpd: ntp-4 is maintained by Network Time Foundation, 22 Jan 02:13:08 ntpd: Inc. (NTF), a non-profit 501(c)(3) public-benefit 22 Jan 02:13:08 ntpd: corporation. Support and training for ntp-4 are 22 Jan 02:13:08 ntpd: available at https://www.nwtime.org/support 22 Jan 02:13:08 ntpd: ---------------------------------------------------- 22 Jan 02:13:08 ntpd: proto: precision = 0.481 usec (-21) 22 Jan 02:13:08 ntpd: basedate set to 2021-06-20 22 Jan 02:13:08 ntpd: gps base set to 2021-06-20 (week 2163) 22 Jan 02:13:08 ntpd: unable to bind to wildcard address :: - another process may be running - EXITING
This can be corrected by stopping the daemon service, running ntpd, then (re)starting the service. On OpenRC systems, this is accomplished as follows:
System clock
The system clock (a.k.a. the software clock) keeps track of: time, time zone, and DST if applicable. It is calculated by the Linux kernel as the number of seconds since midnight January 1st 1970, UTC. The initial value of the system clock is calculated from the hardware clock, dependent on the contents of . After boot-up has completed, the system clock runs independently of the hardware clock. The Linux kernel keeps track of the system clock by counting timer interrupts.
Read clock
To check the current system clock time (presented both in local time and UTC) as well as the RTC (hardware clock):
$ timedatectl
Set system clock
To set the local time of the system clock directly:
# timedatectl set-time "yyyy-MM-dd hh:mm:ss"
For example:
# timedatectl set-time "2014-05-26 11:13:54"
sets the time to May 26th, year 2014, 11:13 and 54 seconds.
II. Configure NTP Client to Synchronize with NTP Server
7. Modify ntp.conf on NTP Client
This setup should be done on your NTP Client (Not on NTP-server)
To synchronize the time of your local Linux client machine with NTP server, edit the /etc/ntp.conf file on the client side. Here is an example of how the sample entries looks like. In the following example, you are specifying multiple servers to act as time server, which is helpful when one of the timeservers fails.
server 0.rhel.pool.ntp.org iburst server 1.rhel.pool.ntp.org iburst server 2.rhel.pool.ntp.org iburst server 3.rhel.pool.ntp.org iburst
iburst: After every poll, a burst of eight packets is sent instead of one. When the server is not responding, packets are sent 16s interval. When the server responds, packets are sent every 2s.
Edit your NTP.conf to reflect appropriate entries for your own NTP server.
server 19.168.1.1 prefer
prefer: If this option is specified that server is preferred over other servers. A response from the preferred server will be discarded if it differs significantly different from other server’s responses.
8. Start the NTP Daemon
Once the ntp.conf is configured with correct settings, start the ntp daemon.
/etc/init.d/ntp start
You will see the NTP will slowly start to synchronize the time of your linux machine with the NTP Server.
9. Check the NTP Status
Check the status of NTP using the ntpq command. If you get any connection refused errors then the time server is not responding or the NTP daemon/port is not started or listening.
# ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== *elserver1 19.168.1.1 3 u 300 1024 377 1.225 -0.071 4.606
10. Set Local Date and Time
The ntpdate command can be used to set the local date and time by polling the NTP server. Typically, you’ll have to do this only one time.
Your jitter value should be low, else check the drift from the clock in the driftfile. You may also need to change to some other NTP server based on the difference. This command synchronizes the time with your NTP server manually.
ntpdate –u 19.168.1.1
After this initial sync, NTP client will talk to the NTP server on an on-going basis to make sure the local time reflects the accurate time.
You can also use the following command to get the current status of ntpd.
# ntpdc -c sysinfo system peer: thegeekstuff.com system peer mode: client leap indicator: 00 stratum: 4 precision: -23 root distance: 0.00279 s root dispersion: 0.06271 s reference ID: reference time: d70bd07b.f4b5cf2b Wed, Apr 30 2014 15:41:47.955 system flags: auth monitor ntp kernel stats jitter: 0.000000 s stability: 0.000 ppm broadcastdelay: 0.000000 s authdelay: 0.000000 s
Получить список доступных часовых поясов
Утилита tzselect
Перед тем, как устанавливать часовой пояс, нужно понять, какое значение можно установить. Для этого можно воспользоваться утилитой tzselect.
После запуска утилита tzselect отображает список географических областей. Вы должны ввести номер области и нажать Enter. Затем появится список стран. Аналогично, нужно ввести номер страны. Появится список городов. Вводим номер города. В результате вы сможете увидеть название вашей временной зоны.
Утилита timedatectl
Утилита timedatectl поддерживает опцию list-timezones. Выполнив следующую команду можно просмотреть список всех доступных временных зон:
Можно воспользоваться grep и ограничить область поиска. Например, выведем список временных зон только для Европы:
Настройка клиентов сервера времени
Если вам нужно только синхронизировать ваши часы при загрузке машины, вы можете воспользоваться утилитой Консольная утилита ntpdate для синхронизации времени. Это может подойти для некоторых настольных машин, которые часто перезагружаются и только требуют изредка синхронизироваться, но на большинстве машин должен работать ntpd.
- Windows — просто указать IP и DNS нашего сервера NTP
-
Ubuntu (любой дистрибутив Debian):
# aptitude install ntp # ntpq -c peers remote refid st t when poll reach delay offset jitter ============================================================================== europium.canoni 193.79.237.14 2 u 43 64 7 58.812 -697293 14.720
Правим /etc/ntp.conf для того чтобы синхронизация производилась с нашим сервером.
# cp /etc/ntp.conf /etc/ntp.conf.orig # nano /etc/ntp.conf driftfile /var/lib/ntp/ntp.drift statsdir /var/log/ntpstats/ statistics loopstats peerstats clockstats filegen loopstats file loopstats type day enable filegen peerstats file peerstats type day enable filegen clockstats file clockstats type day enable # local NTP server server 10.26.95.254 prefer # Backup NTP server server ntp3.time.in.ua restrict default ignore restrict 127.0.0.1 restrict ::1 restrict 10.26.95.254 # ntp3.time.in.ua = 80.91.187.10 restrict 80.91.187.10 # /etc/init.d/ntp restart
-
FreeBSD достаточно прописать в /etc/rc.conf
ntpd_enable="YES" # Time(NTP) -server ntpdate_enable="YES" ntpdate_flags="-u x.x.x.254" # IP NTP server
и запустить службу, предварительно настроив ./etc/ntp.conf(см. выше)
> /etc/rc.d/ntpd start
periodic.conf status-ntpd
FreeBSD: 480.status-ntpd — выводит список известных NTP-серверу peer. Если стабильность работы NTP сервера важна — можно включить.
> ee /etc/periodic.conf # 480.status-ntpd daily_status_ntpd_enable="YES" # Check NTP status
Difference Between Chronyd and Ntpd
Now that we know how to work with both chronyd and ntpd which should you use? In general it doesn’t really matter that much and sticking with the default in your operating system will usually be fine in most instances. With that in mind here are some differences between chronyd and ntpd which may help you decide which to use.
- Linux systems that are not permanently online or connected to the network take longer to adjust their system clocks with ntpd as lots of small corrections need to be made. Typically adjustments begin within the first few milliseconds of system boot, however acceptable accuracy may take anywhere from 10 seconds during a warm restart to a number of hours depending on the operating environment and hardware, variables like temperature start to matter and affect the hardware clock. Chronyd is capable of adjusting the time much faster so is better used in systems that will not be continually online and synchronizing with an NTP server.
- Chronyd works better than ntpd when NTP servers are only intermittently available, this is because ntpd needs regular polling of the reference time servers for best results. For example if network connectivity is poor chronyd may be a better option than ntpd.
- Chronyd supports isolated network functionality whereby the only available way of correcting time is by manual update. This would be useful in a secure network with no access to an NTP server, time is manually entered in and chronyd is capable of examining the errors corrected at different updates to estimate the best accurate time.
- Chronyd usually synchronizes time faster and with better accuracy than ntpd.
- Ntpd supports NTP version 4 (RFC 5905) while chronyd supports NTP version 3 (RFC 1305), but is compatible with version 4. Basically chronyd does not currently fully support the v4 protocol like ntpd.
To summarize the differences, chronyd should be considered for use on Linux systems that may be frequently suspended, powered down, or otherwise intermittently disconnected from the network. Chronyd is also capable of synchronizing faster than ntpd, however ntpd has better support for version 4 of NTP. Ntpd should be considered for systems that remain permanently up and running, however even then the benefits do not seem to be as great as those provided by chronyd.