Проверить ntp сервер linux

How to verify if NTP sync is working on Linux?

NTP stand for Network Time Protocol, which synchronizes the clock between computer systems over the network.

NTP server keep all the servers in-sync with accurate time to perform time based jobs in an organization. NTP client will synchronize its clock to the network time server.

We already wrote an article about NTP Server, Client installation and configuration. If you would like to check these articles, navigate to the following links:

I’m assuming that we have setup the NTP server and NTP client by referring to the above links. In this guide, we will show you how to verify whether the NTP setup is working or not?

NTP sync status can be verified using the following three commands:

  • ntpq: ntpq is standard NTP query program.
  • ntpstat: It shows network time synchronization status.
  • timedatectl: It controls the system time and date in systemd system.

Let’s understand each of the commands in detail.

Method-1: Checking the status of NTP using ntpq command

The ‘ntpq’ command is used to monitor NTP daemon and determine the performance, which can be identified by querying the NTP servers running on the host.

It runs either in interactive mode or by using command-line arguments. It prints a list of connected peers by sending multiple queries to the server.

If NTP is working properly, you should get the below output:

# ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== *CentOS7.2daygee 133.243.238.163 2 u 14 64 37 0.686 0.151 16.432
  • -p: Print a list of the peers known to the server as well as a summary of their state.
  • remote: Remote NTP server
  • st: The stratum of the remote peer
  • t: Type of the peer (local, unicast, multicast or broadcast)
  • when: Time the last packet was received, the polling interval (seconds)
  • poll: How frequently to query server (in seconds)
  • reach: Octal bitmask of success or failure of last 8 queries.
  • delay: Network round trip time (in milliseconds)
  • offset: Difference between local clock and remote clock (in milliseconds)
  • jitter: Difference of successive time values from server
Читайте также:  Astra linux сглаживание шрифтов

Method-2: How to check NTP status using ntpstat command

ntpstat will report the synchronization state of the NTP daemon (ntpd) running on the local machine.

If the local system is found to be synchronized to a reference time source, ntpstat will report the approximate time accuracy.

The ntpstat command returns three types of status codes based on the NTP sync as mentioned below:

  • 0: It returns 0, if clock is synchronised.
  • 1: It returns 1, if clock is not synchronised.
  • 2: It returns 2, if clock state is indeterminant, for example if ntpd is not contactable.
# ntpstat synchronised to NTP server (192.168.1.8) at stratum 3 time correct to within 508 ms polling server every 64 s

Method-3: Checking NTP sync status with timedatectl command

timedatectl command is used to query and change the system clock and its settings in systemd system:

# timedatectl or # timedatectl status Local time: Thu 2019-05-30 05:01:05 CDT Universal time: Thu 2019-05-30 10:01:05 UTC RTC time: Thu 2019-05-30 10:01:05 Time zone: America/Chicago (CDT, -0500) NTP enabled: yes NTP synchronized: yes RTC in local TZ: no DST active: yes Last DST change: DST began at Sun 2019-03-10 01:59:59 CST Sun 2019-03-10 03:00:00 CDT Next DST change: DST ends (the clock jumps one hour backwards) at Sun 2019-11-03 01:59:59 CDT Sun 2019-11-03 01:00:00 CST

Bonus Tips:

Chrony is replacement of NTP client. It can synchronize the system clock faster with better time accuracy and it can be very much useful for the systems which are not online all the time.

Chronyd is smaller in size, it uses less system memory and it wakes up the CPU only when necessary, which is better for power saving.

It can perform well, even when the network is congested for longer periods of time. You can use any of the below commands to check Chrony status:

# chronyc tracking Reference ID : C0A80105 (CentOS7.2daygeek.com) Stratum : 3 Ref time (UTC) : Thu Mar 28 05:57:27 2019 System time : 0.000002545 seconds slow of NTP time Last offset : +0.001194361 seconds RMS offset : 0.001194361 seconds Frequency : 1.650 ppm fast Residual freq : +184.101 ppm Skew : 2.962 ppm Root delay : 0.107966967 seconds Root dispersion : 1.060455322 seconds Update interval : 2.0 seconds Leap status : Normal

Run the sources command to display information about the current time sources:

# chronyc sources 210 Number of sources = 1 MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* CentOS7.2daygeek.com 2 6 17 62 +36us[+1230us] +/- 1111ms

Conclusion

In this guide, you learned how to check NTP synchronize status on linux using three different commands.

If you have any questions, feel free to leave a comment. We will get back to you as soon as possible.

Читайте также:  Файловыми менеджерами linux являются

Источник

NTP сервер на Linux Ubuntu

Обновлено и опубликовано

Опубликовано: 12.01.2018

Тематические термины: NTP, Linux, Ubuntu. Следить за актуальностью времени на всех узлах локальной сети удобнее с помощью сервера синхронизации времени NTP. В инструкции рассказано об установке и настройке такого сервера на Linux Ubuntu Server 16.04. Данное руководство можно использовать для настройки ntpd на любом другом Linux (например, Debian или CentOS).

Установка сервера

Настройка NTP

pool ru.pool.ntp.org iburst
server ntp2.vniiftri.ru iburst prefer
pool 0.ubuntu.pool.ntp.org iburst
pool 1.ubuntu.pool.ntp.org iburst
server 127.127.1.0

* iburst — отправлять несколько пакетов (повышает точность); ru.pool.ntp.org / 0.ubuntu.pool.ntp.org / 1.ubuntu.pool.ntp.org — адреса серверов, с которыми наш сервер будет сверять время; server — указывает на выполнение синхронизации с сервером, а не пулом серверов; prefer — указывает на предпочитаемый сервер. server 127.127.1.0 — позволит в случае отказа сети Интернет брать время из своих системных часов. Настраиваем безопасность:

restrict default kod notrap nomodify nopeer noquery
restrict 192.168.0.0 mask 255.255.255.0 nomodify notrap
restrict 127.0.0.1
restrict ::1

  • restrict default — задает значение по умолчанию для всех рестриктов.
  • kod — узлам, которые часто отправляют запросы сначала отправить поцелуй смерти (kiss of death), затем отключить от сервера.
  • notrap — не принимать управляющие команды.
  • nomodify — запрещает команды, которые могут вносить изменения состояния.
  • nopeer — не синхронизироваться с хостом.
  • noquery — не принимать запросы.
  • restrict 192.168.0.0 mask 255.255.255.0 — разрешить синхронизацию для узлов в сети 192.168.0.0/24.
  • IP адреса127.0.0.1 и ::1 позволяют обмен данные серверу с самим собой.

Настройки по умолчанию могут быть разные для IPv4 и IPv6:

restrict -4 default kod notrap nomodify nopeer noquery
restrict -6 default kod notrap nomodify nopeer noquery

systemctl restart ntp || service restart ntp

Если используется брандмауэр, добавляем правило:

iptables -I INPUT 1 -p udp —dport 123 -j ACCEPT

ufw allow in on enp2s0 to any port 123 proto udp

* где enp2s0 — сетевой интерфейс, на котором слушает наш сервер.

Дополнительные настройки

Настройка файла хранения логов:

Тестирование

Проверить состояние получения эталонного времени можно командой:

Мы должны увидеть, примерно, следующее:

remote refid st t when poll reach delay offset jitter
==============================================================================
ru.pool.ntp.org .POOL. 16 p — 64 0 0.000 0.000 0.000
ntp.ubuntu.com .POOL. 16 p — 64 0 0.000 0.000 0.000
*91.189.94.4 17.253.34.253 2 u 58 64 377 55.802 3.790 0.412
-91.189.91.157 132.246.11.231 2 u 56 64 377 113.456 -1.746 0.334
+91.189.89.198 192.53.103.108 2 u 1 64 377 54.595 4.229 0.608
+91.189.89.199 17.253.34.253 2 u 61 64 377 54.061 2.637 0.557

  • remote — адрес сервера времени, с которым синхронизируется наш сервер;
  • refid — вышестоящий сервер (с которым сервер из графы выше получает время);
  • st — уровень сервера (stratum);
  • t — пир (unicast или multicast);
  • when — когда последний раз сверялось время;
  • poll — периодичность синхронизации с этим сервером;
  • reach — состояние работоспособности. Если удалось произвести синхронизации восемь раз в подряд становится равным 377;
  • delay — время задержки;
  • offset — разница между нашим временем и временем на сервере; положительное — наши часы спешат, отрицательное — отстают;
  • jitter — смещение времени на удаленном сервере;
  • * — с этим сервером синхронизирует время наш ntpd;
  • + — сервер можно использовать для сверки часов;
  • — — не рекомендован для синхронизации;
  • x — не доступен.

Проверить отдачу времени сервером можно введя команду на другом Linux:

Читайте также:  Linux red hat добавить пользователя

Правильный ответ имеет следующий вид:

ntpdate[3576]: adjust time server 192.168.0.15 offset 0.017657 sec

* время было рассинхронизировано на 0.017657 секунд.

Отобразить текущее время можно командой:

Если после синхронизации время некорректно, настраиваем правильный часовой пояс:

cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime

Настройка клиента Linux

Для клиентов можно выбрать 2 стратегии настройки — с помощью ntp или утилиты ntpdate.

NTP

В настройка /etc/ntp.conf в качестве сервера оставляем только наш локальный сервер, например:

Остальные pool и server удаляем или комментируем.

systemctl restart ntp || service restart ntp

ntpdate

Утилита командной строки выполняет разовую синхронизацию. Чтобы автоматизировать процесс, добавляем задание в cron:

0 0 * * * /usr/sbin/ntpdate 192.168.0.15

* в данном примере задание будет выполняться раз в день в 00:00. /usr/sbin/ntpdate — полный путь расположения утилиты, в разных системах может быть разным — проверить стоит командой which ntpdate.

Настройка клиента Windows

В командной строке выполняем:

w32tm /config /manualpeerlist:»192.168.0.15,0×8″ /syncfromflags:manual /update

Некоторые ошибки

1. the NTP socket is in use, exiting

Как правило, данная ошибка возникает при попытке синхронизировать время с помощью ntpdate, когда в системе работает демон ntp.

Причина: NTP сокет в системе уже занят, как правило, ntpd.

Решение: либо не использовать ntpdate, так как ntp умеет сверять время, либо отключить сервис ntpd командой service ntp stop.

2. Connection refused

Возникает при попытке выполнить команду ntpq -p.

Причина: нет разрешения на обращение к серверу.

Решение: проверьте, удастся ли выполнить запрос командой ntpq -pn 127.0.0.1 или ntpq -pn ::1. Также убедитесь, что настройка restrict позволяет серверу подключаться к самому себе по нужному протоколу.

3. no server suitable for synchronization found

Ошибка появляется при попытке синхронизировать время с другим сервером синхронизации.

Причина: сервер синхронизации не доступен по одной из причин: 1) не работает или выключен, 2) установлен restrict, 3) на сервере не запущен ntpd, 4) нет сетевой доступности из-за проблем на сети или брандмауэра.

  1. Убедиться, что сервер доступен по сети.
  2. Проверить настройки ntp.conf — наличие соответствующего restrict.
  3. Проверить состояние сервиса командой service ntp status.
  4. Проверить настройки брандмауэра — убедиться в наличие правила, которое разрешает UDP порт 123.

Источник

Оцените статью
Adblock
detector