Настроить ntp клиент 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:

Читайте также:  Update manager linux mint

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

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.
Читайте также:  Kali linux ssh доступ

Источник

Install and Configure NTP Client on Ubuntu/Debian systems

Follow through this tutorial to quickly learn how to install and configure NTP Client on Ubuntu/Debian systems.

Install and Configure NTP Client on Ubuntu/Debian systems

We will discuss three ways in which you can install and configure NTP Client on Ubuntu/Debian systems.

The guide is based on the NTP servers we configured as per our previous guides on how to configure NTP Server.

Synchronizing using systemd timesyncd service

In an Ubuntu/Debian systems, an NTP Client, systemd-timesyncd.service, is running by default.

Edit the file /etc/systemd/timesyncd.conf and add the address for your NTP server by adding such an entry at the end of the file:

vim /etc/systemd/timesyncd.conf

Where 192.168.56.103 is the IP address of configured NTP server.

You can also set FallBack by uncommenting the line below;

Restart systemd-timesyncd NTP client service:

sudo systemctl restart systemd-timesyncd

Confirm the status of status that it is now synchronized with the configured NTP server.

 systemctl status systemd-timesyncd
● systemd-timesyncd.service - Network Time Synchronization Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2022-05-14 12:10:14 UTC; 2s ago Docs: man:systemd-timesyncd.service(8) Main PID: 1166 (systemd-timesyn) Status: "Initial synchronization to time server 192.168.59.38:123 (192.168.59.38)." Tasks: 2 (limit: 2241) Memory: 1.2M CPU: 73ms CGroup: /system.slice/systemd-timesyncd.service └─1166 /lib/systemd/systemd-timesyncd May 14 12:10:14 jellyfish systemd[1]: Starting Network Time Synchronization. May 14 12:10:14 jellyfish systemd[1]: Started Network Time Synchronization. May 14 12:10:14 jellyfish systemd-timesyncd[1166]: Initial synchronization to time server 192.168.59.38:123 (192.168.59.38). 
 Local time: Sat 2022-05-14 12:10:53 UTC Universal time: Sat 2022-05-14 12:10:53 UTC RTC time: Sat 2022-05-14 12:10:53 Time zone: Etc/UTC (UTC, +0000) System clock synchronized: yes NTP service: active RTC in local TZ: no 

Using ntpdate to Synchronize Client Systems’ Time

Optionally the ntpdate command can be used to manually synchronize client system time with NTP server. This guide uses Ubuntu 18.04 as the client.

Install ntpdate package, if not already installed.

sudo apt install ntpdate -y

NOTE: Ensure that Client and NTP Server can communicate. You can use nc command to verify NTP server port connection.

Connection to 192.168.59.38 123 port [udp/ntp] succeeded!

Next, use ntpdate Command to Query Time Service. The ntpdate command can be uses to query time service from an NTP server by running the command:

The output shows the time offset between the two systems.

14 May 12:17:28 ntpdate[1516]: adjust time server 192.168.59.38 offset -0.019108 sec

Synchronize time Automatically Using NTP

NTP client can automatically be configured to query NTP server by using the NTPd daemon.

Читайте также:  Linux vmware unity mode

Install NTP on Ubuntu/Debian

The installation of NTP will mask the systemd-timesyncd.service .

The NTP service is set to run by default after installation. First check if the client is synchronized with NTP:

The output will show if the system clock is synchronized or not. The output below clearly indicates time is not synced to any server.

 Local time: Sat 2022-05-14 12:20:04 UTC Universal time: Sat 2022-05-14 12:20:04 UTC RTC time: Sat 2022-05-14 12:20:04 Time zone: Etc/UTC (UTC, +0000) System clock synchronized: no NTP service: n/a RTC in local TZ: no

To configure the NTP client to synchronize time from your NTP server, edit the ntp configuration file:

Replace public NTP pool servers with your server.

#pool 0.ubuntu.pool.ntp.org iburst #pool 1.ubuntu.pool.ntp.org iburst #pool 2.ubuntu.pool.ntp.org iburst #pool 3.ubuntu.pool.ntp.org iburst pool 192.168.59.38 iburst

Ideally the server can be added without commenting out the default NTP servers by making it the preferred reference clock using the prefer option:

pool 192.168.59.38 prefer iburst

Save the configuration file and restart ntp.

 sudo systemctl restart ntp

The client is now successfully configured to sychronize system time with NTP server. This can be verified by running the command:

 remote refid st t when poll reach delay offset jitter ============================================================================== 192.168.59.38 .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 *192.168.59.38 91.189.89.198 3 u 2 64 1 1.732 +16.240 0.089 chilipepper.can 17.253.34.251 2 u 8 64 1 255.060 -41.243 0.000 pugot.canonical 17.253.108.125 2 u 5 64 1 171.300 -0.021 0.000 golem.canonical 134.71.66.21 2 u 4 64 1 263.212 -45.093 0.000 alphyn.canonica 194.58.200.20 2 u 5 64 1 251.289 +2.991 0.000 

From the output we can see NTP server (192.168.56.103) as the time synchronization host/source in the queue.

Confirm NTP service is set to start at boot time:

To enable NTP service to start at boot time, just in case is not enabled, then you would run the command:

Great, your NTP Clients should now be able to query the time services from your NTP Server.

That brings us to the end of the guide on how install and setup NTP Client on Ubuntu/Debian.

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We’re passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Источник

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