Ntp linux and windows

Syncing time in Linux and Windows with NTP

Using the Network Time Protocol will ensure that precise time syncs exist on your Linux and Windows Server, crucial if you want your Linux machine to connect to a Windows domain.

There are plenty of reasons you should have your Linux and Windows servers set with the correct time. One of the most obvious (and annoying) is, without the correct time, your Linux machine will be unable to connect to a Windows Domain. You can also get into trouble with the configuration of your mail and web servers when the time is not correct (sending email from the future is never a good idea). So how do you avoid this? Do you have to constantly be resetting the time on your machines? No. Instead of using a manual configuration, you should set up all of your servers to use NTP (Network Time Protocol) so that they always have the correct time.

Windows Server settings

There is a very simple way to set your Windows Server OS (2000 and later) to use an external time server. To do this simply click on this Fixit link and the registry entries necessary to be changed will be changed and your server will start updating time from an external source.

If you are more of the DIY Windows admin, you will want to know the registry edits that are made by clicking that Fix It link. Here they are (NOTE: The Windows registry is a tool that not all users are qualified to use. Make sure you do a backup of your registry before you make any changes.):

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters\Type

Right-click Type and select Modify. Change the entry in the Value Data box to NTP and click OK.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\AnnounceFlags

Right-click AnnounceFlags and select Modify. In the Edit D Word change the Value Data to 5 and click OK.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer

In the right pane, right-click Enabled and select Modify. In the Edit D Word change the Value Data to 1 and click OK.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

In the right pane, right-click NtpServer and select Modify. Change the Value Data to Peers and click OK.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient\SpecialPollInterval

In the right pane, right-click SpecialPollInterval and select Modify. Change the Value Data to Seconds (where Seconds is a number representing the amount of seconds between polls; 900 seconds is ideal) and click OK.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\MaxPosPhaseCorrection

In the right pane right-click MaxPosPhaseCorrection and select Modify. Change the Value Data to Seconds (where Seconds is a number representing the amount of seconds used for positive corrections; this is used to correct for time zones and other issues).

Читайте также:  Start and stop processes linux

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config\MaxNegPhaseCorrection

In the right pane, right-click MaxNegPhaseCorrection and select Modify. Change the Value Data to Seconds (where Seconds is a number representing the amount of seconds used for negative corrections; this is used to correct for time zones and other issues).

Once you have made the final registry edit, quit the registry editor and then click Start | Run and enter the following command:

net stop w32time && net start w32time

Your Windows machine will now start syncing time to an external server at the set intervals.

On to the Linux server

In order to get NTP up and running you first have to install the ntp daemon on the machine. This is very simple, as ntpd will be located in your default repositories. So, with that in mind, open up a terminal window and issue one of the following commands (dependent upon which distribution you are using). NOTE: If you are using a non-sudo distribution you will need to first su to the root user. Once you have administrative privileges issue one of the following:

  • sudo apt-get install ntp (for Debian-based systems).
  • yum install ntp (for Red Hat-based systems).
  • urpmi ntp (For Mandriva-based systems).
  • zypper ntp (For SUSE-based systems)

Upon installation, your NTP system should be pre-configured correctly to use an NTP server for time. But if you want to change the server you use, you would need to edit your /etc/ntp.conf file. In this file you want to add (or edit) a line to reflect your NTP needs. An entry looks like:

Where SERVER_ADDRESS is the address of the server you want to use and [OPTIONS] are the available options. Of the available options, there are two that might be of interest to you:

  • iburst: Use this option when the configured server is unreachable. This option will send out bursts of eight packets instead of the default one when trying to reconnect to the server.
  • dynamic: Use this option if the NTP server is currently unreachable (but will be reachable at some point).

By default, the /etc/ntp.conf file will look similar to this:

server 0.debian.pool.ntp.org iburst dynamic 

server 1.debian.pool.ntp.org iburst dynamic

server 2.debian.pool.ntp.org iburst dynamic

server 3.debian.pool.ntp.org iburst dynamic

More than one server is used in order to assure a connection. Should one server not be available, another one will pick up the duty.

When you have everything set up correctly, enter the following command:

sudo /etc/init.d/ntp start (on Debian-based machines) OR /etc/rc.d/init.d/ntp start (on most other machines. NOTE: You will need to first su to the root user for this command to work).

Your machine should now start syncing its time with the NTP server configured.

Final thoughts

It may seem like a task that should be unnecessary, but in certain systems and configurations, the precise time is crucial. Whether you are serving up web pages, mail, or trying to connect to a Windows domain, keeping the correct time will make just about ever task either easier or simply correct.

Читайте также:  Linux h264 to mp4

Person using a laptop computer.

Subscribe to the Daily Tech Insider Newsletter

Stay up to date on the latest in technology with Daily Tech Insider. We bring you news on industry-leading companies, products, and people, as well as highlighted articles, downloads, and top resources. You’ll receive primers on hot tech topics that will help you stay ahead of the game.

Published: January 25, 2011, 5:16 AM PST Modified: January 25, 2011, 5:16 AM PST See more Data Centers

Источник

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:

Читайте также:  How to rise linux

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

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