Linux which ntp server

About time synchronisation

Network Time Protocol (NTP) is a networking protocol for synchronising time over a network. Basically, a client requests the current time from a server, and uses it to set its own clock.

Behind this simple description, there is a lot of complexity. There are three tiers of NTP servers; tier one NTP servers are connected to atomic clocks, while tier two and tier three three servers spread the load of actually handling requests across the Internet.

The client software is also a lot more complex than you might expect. It must factor in communication delays and adjust the time in a way that does not upset all the other processes that run on the server. Luckily, all that complexity is hidden from you!

By default, Ubuntu uses timedatectl / timesyncd to synchronise time, and they are available by default. See our guide If you would like to know how to configure timedatectl and timesyncd .

Users can also optionally use chrony to serve NTP.

How time synchronisation works

Since Ubuntu 16.04, timedatectl / timesyncd (which are part of systemd ) replace most of ntpdate / ntp .

About timesyncd

timesyncd replaces not only ntpdate , but also the client portion of chrony (formerly ntpd ). So, on top of the one-shot action that ntpdate provided on boot and network activation, timesyncd now regularly checks and keeps your local time in sync. It also stores time updates locally, so that after reboots the time monotonically advances (if applicable).

About timedatectl

If chrony is installed, timedatectl steps back to let chrony handle timekeeping. This ensures that no two time-syncing services can conflict with each other.

ntpdate is now considered deprecated in favor of timedatectl (or chrony ) and is no longer installed by default. timesyncd will generally keep your time in sync, and chrony will help with more complex cases. But if you had one of a few known special ntpdate use cases, consider the following:

  • If you require a one-shot sync, use: chronyd -q
  • If you require a one-shot time check (without setting the time), use: chronyd -Q

While use of ntpd is no longer recommended, this also still applies to ntpd being installed to retain any previous behaviour/config that you had through an upgrade. However, it also implies that on an upgrade from a former release, ntp / ntpdate might still be installed and therefore renders the new systemd -based services disabled.

Further reading

  • ntp.org: home of the Network Time Protocol project
  • pool.ntp.org: project of virtual cluster of timeservers
  • Freedesktop.org info on timedatectl
  • Freedesktop.org info on systemd-timesyncd service
  • Chrony FAQ
  • Feeding chrony from GPSD
  • Also see the Ubuntu Time wiki page for more information.
Читайте также:  How to install linux mint on virtualbox

Источник

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 macbook pro 2010

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

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.

Источник

How do I find my NTP server in Debian

NTP is an abbreviation of “Network Time Protocol” which is used to synchronize the time of the server and the client machine. In this process, the client machine requests the server for the current time and the server sends data in the form of packets. There is a standard of time that is universal and followed by everyone known as UTC (Coordinated Universal Time). Port 123 is by default allocated to the NTP server and this whole process is followed by the User Datagram Protocol (UDP).

In this post, we are focusing on finding the NTP server by installing and configuring the NTP in Debian.

How do I find my NTP server on Debian

NTP is a process in which the client machine requests the server to set its time. So first we will understand how to install and configure the NTP server then will learn how to find out the IP addresses of NTP.

Читайте также:  Этот linux не совместим

Installation and Configuration of NTP : First, we will update Debian’s repository:

We will install the latest package available of NTP:

By default, after the installation, NTP should be of active status, you can confirm it by checking its status but if it is inactive, you can start the NTP server:

After restarting, check its status whether it is running or not:

Hence the NTP is running. Now, we will configure the firewall so it will allow the client to request the server else it will restrict the client to send any query and for this purpose will first go to the root mode.

Run these two commands here, asking the firewall to allow the queries on port 123 which is by default allocated to the NTP.

iptables -A OUTPUT -p udp —dport 123 -j ACCEPT

iptables -A INPUT -p udp —dport 123 -j ACCEPT

Now we will exit the root user mode as:

Verification of the NTP working using ntpstat : The ntpstat command shows us whether the connection is established between the server and client, if the connection is established, then the status will be “synchronized”. If ntpstat generates the error of “command not found” on running the command:

Then we can install ntpstat running the following command.

Now to check the status, again run the command.

The output shows the NTP server IP address along with the recent details of the correction of time with the server and to verify the status of synchronization of the clock we will run the command to get the exit status.

The outcome “0” means the client’s clock is synchronized with the server. The other outcomes can be either “1” which means the clock of the client machine is not synchronized with the server or “2” which means the client is not connected to the server.

Checking the ntp server using ntpq command : Ntpq command monitors the NTP daemon, ntpd operations, and determines the performance of the NTP. We will use flags, p which means print the entire list of the peers known by the server with the summary of their state, and n which means display the host addresses.

Conclusion

NTP enables us to synchronize with the same time units that the world is following. NTP sets the time of its machine by asking the server to give it time information and then both are synchronized with the time of the internet. In this post, we have discussed two methods by which we can get the information about our NTP server in Debian. Hope this post will help you understand not only how to find our NTP server on Debian but also the installation and configuration of NTP on both server and client’s machine.

About the author

Hammad Zahid

I’m an Engineering graduate and my passion for IT has brought me to Linux. Now here I’m learning and sharing my knowledge with the world.

Источник

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