Windows server настройка сервера времени в windows

Начиная с Windows 2000 все операционные системы Windows включают в себя службу времени W32Time. Эта служба предназначена для синхронизации времени в пределах организации. W32Time отвечает за работу как клиентской, так и серверной части службы времени, причем один и тот же компьютер может быть одновременно и клиентом и сервером NTP (Network Time Protocol).

По умолчанию служба времени в Windows сконфигурирована следующим образом:

• При установке операционной системы Windows запускает клиента NTP и синхронизируется с внешним источником времени;
• При добавлении компьютера в домен тип синхронизации меняется. Все клиентские компьютеры и рядовые сервера в домене используют для синхронизации времени контроллер домена, проверяющий их подлинность;
• При повышении рядового сервера до контроллера домена на нем запускается NTP-сервер, который в качестве источника времени использует контроллер с ролью PDC-эмулятор;
• PDC-эмулятор, расположенный в корневом домене леса, является основным сервером времени для всей организации. При этом сам он также синхронизируется с внешним источником времени.

Такая схема работает в большинстве случаев и не требует вмешательства. Однако структура сервиса времени в Windows может и не следовать доменной иерархии, и надежным источником времени можно назначить любой компьютер. В качестве примера я опишу настройку NTP-сервера в Windows Server 2008 R2, хотя со времен Windows 2000 процедура не особо изменилась.

Запуск NTP сервера

Сразу отмечу, что служба времени в Windows Server (начиная с 2000 и заканчивая 2012) не имеет графического интерфейса и настраивается либо из командной строки, либо путем прямой правки системного реестра. Лично мне ближе второй способ, поэтому идем в реестр.

Итак, первым делом нам надо запустить сервер NTP. Открываем ветку реестра
HKLM\System\CurrentControlSet\services\W32Time\TimeProviders\NtpServer.
Здесь для включения сервера NTP параметру Enabled надо установить значение 1.

включение сервера NTP

Затем перезапускаем службу времени командой net stop w32time && net start w32time

перезапуск службы времени в Windows

После перезапуска службы NTP сервер уже активен и может обслуживать клиентов. Убедиться в этом можно с помощью команды  w32tm /query /configuration. Эта команда выводит полный список параметров службы. Если раздел NtpServer содержит строку Enabled :1 , то все в порядке, сервер времени работает.

просмотр параметров службы времени в Windows

Для того, чтобы NTP-сервер мог обслуживать клиентов, не забудьте на файерволле открыть UDP порт 123 для входящего и исходящего траффика.

Основные настройки NTP сервера

NTP сервер включили, теперь надо его настроить. Открываем ветку реестра HKLM\System\CurrentControlSet\services\W32Time\Parameters. Здесь в первую очередь нас интересует параметр Type, который задает тип синхронизации. Он может принимать следующие значения:

NoSync — NTP-сервер не синхронизируется с каким либо внешним источником времени. Используются часы, встроенные в микросхему CMOS самого сервера;
NTP — NTP-сервер синхронизируется с внешними серверами времени, которые указаны в параметре реестра NtpServer;
NT5DS —  NTP-сервер производит синхронизацию согласно доменной иерархии;
AllSync — NTP-сервер использует для синхронизации все доступные источники.

Значение по умолчанию для компьютера, входящего в домен — NT5DS, для отдельно стоящего компьютера —  NTP.

И параметр NtpServer, в котором указываются NTP-сервера, с которыми будет синхронизировать время данный сервер. По умолчанию в этом параметре прописан NTP-сервер Microsoft (time.windows.com, 0x1), при необходимости можно добавить еще несколько NTP-серверов, введя их DNS имена или IP адреса через пробел. Список доступных серверов времени можно посмотреть например здесь.

В конце каждого имени можно добавлять флаг (напр. ,0x1) который определяет режим для синхронизации с сервером времени. Допускаются следующие значения:

0x1 –  SpecialInterval, использование специального интервала опроса ;
0x2 – режим UseAsFallbackOnly;
0x4 – SymmetricActive, симметричный активный режим;
0x8 – Client, отправка запроса в клиентском режиме.

При использовании флага SpecialInterval, необходимо установленное значение интервала в ключе SpecialPollInterval. При значении флага UseAsFallbackOnly службе времени сообщается, что данный сервер будет использоваться как резервный и перед синхронизацией с ним будут выполнятся обращения к другим серверам списка. Симметричный активный режим используется NTP-серверами по умолчанию, а клиентский режим можно задействовать в случае проблем с синхронизацией. Подробнее о режимах синхронизации можно посмотреть здесь, либо не морочиться и просто ставить везде ,0x1 (как советует Microsoft).

настройка синхронизации NTP сервера

Еще один важный параметр AnnounceFlags находится в разделе реестра HKLM\System\CurrentControlSet\services\W32Time\Config. Он отвечает за то, как о себе заявляет NTP-сервер и может принимать следующие значения:

0x0 (Not a time server) — сервер не объявляет себя через NetLogon, как источник времени. Он может отвечать на NTP запросы, но соседи не смогут распознать его, как источник времени;
0x1 (Always time server) — сервер будет всегда объявлять о себе вне зависимости от статуса;
0x2 (Automatic time server) — сервер будет объявлять о себе только, если он получает надежное время от другого соседа (NTP или NT5DS);
0x4 (Always reliable time server) — сервер будет всегда заявлять себя, как надежный источник времени;
0x8 (Automatic reliable time server) — контроллер домена автоматически объявляется надежным если он PDC-эмулятор корневого домена леса. Этот флаг позволяет главному PDC леса заявить о себе как об авторизованном источнике времени для всего леса даже при отсутствии связи с вышестоящими NTP-серверами. Ни один другой контроллер или рядовой сервер (имеющие по умолчанию флаг 0x2) не может заявить о себе, как надежном источнике времени, если он не может найти источник времени для себя.

Значение AnnounceFlags составляет сумму составляющих его флагов, например:

10=2+8 — NTP-сервер заявляет о себе как о надежном источнике времени при условии, что сам получает время из надежного источника либо является PDC корневого домена. Флаг 10 задается по умолчанию как для членов домена, так и для отдельно стоящих серверов.

5=1+4 — NTP-сервер всегда заявляет о себе как о надежном источнике времени. Например, чтобы заявить рядовой сервер (не домен-контроллер) как надежный источник времени, нужен флаг 5.

настройка представления NTP сервера

Ну и настроим интервал между обновлениями. За него отвечает уже упоминавшийся выше ключ SpecialPollInterval, находящийся в ветке реестра HKLM\System\CurrentControlSet\services\W32Time\TimeProviders\NtpClient. Он задается в секундах и по умолчанию его значение равно 604800, что составляет 1 неделю. Это очень много, поэтому стоит уменьшить значение SpecialPollInterval до разумного значения, скажем до  1 часа (3600).

настройка интервала синхронизации NTP сервера

После настройки необходимо обновить конфигурацию сервиса. Сделать это можно командой w32tm /config /update. И еще несколько команд для настройки, мониторинга и диагностики службы времени:

w32tm /monitor – при помощи этой опции можно узнать, насколько системное время данного компьютера отличается от времени на контроллере домена или других компьютерах. Например: w32tm /monitor /computers:time.nist.gov
w32tm /resync – при помощи этой команды можно заставить компьютер синхронизироваться с используемым им сервером времени.
w32tm /stripchart–  показывает разницу во времени между текущим и удаленным компьютером, причем может выводить результат в графическом виде. Например, команда w32tm /stripchart /computer:time.nist.gov /samples:5 /dataonly произведет 5 сравнений с указанным источником и выведет результат в текстовом виде.

w32tm /config – это основная команда, используемая для конфигурирования службы NTP. С ее помощью можно задать список используемых серверов времени, тип синхронизации и многое другое. Например, переопределить значения по умолчанию и настроить синхронизацию времени с внешним источником, можно командой w32tm /config /syncfromflags:manual /manualpeerlist:time.nist.gov /update
w32tm /query — показывает текущие настройки службы. Например команда w32tm /query /source  покажет текущий источник времени, а w32tm /query /configuration  выведет все параметры службы.

Ну и на крайний случай 🙁
w32tm /unregister — удаляет службу времени с компьютера.
w32tm /register – регистрирует службу времени на компьютере.  При этом создается заново вся ветка параметров в реестре.

В этой статье показано, как настроить службу времени Windows (NTP) в Windows Server 2016, чтобы она действовала как NTP-сервер для клиентских компьютеров домена.

Немного теории

Синхронизация времени — важный и во многом достаточно критичный аспект работы Active Directory, особенно сегодня, когда широко используется взаимодействие с внешними системами и работа с сотрудниками, которые могут находиться в различных часовых поясах. Применение систем виртуализации вносит дополнительные особенности, которые также следует учитывать. Поэтому данный вопрос может оказаться не столь простым, как кажется, а синхронизация с внешним источником точного времени становится одной из актуальных задач.

Прежде всего вспомним, как происходит синхронизация времени в Active Directory. В качестве эталона времени выступает контроллер, владеющий ролью эмулятора PDC. Это FSMO-роль и эмулятором PDC может являться только один контроллер в каждом домене. С ним синхронизируют время остальные контроллеры домена. Доменные ПК и рядовые серверы сверяют часы с ближайшим контроллером домена.

Сам эмулятор PDC в качестве источника точного времени может использовать либо аппаратные часы материнской платы, либо внешний источник точного времени, при нахождении в виртуальной среде также может быть использовано время хоста виртуализации.

О последней поговорим более подробно. Раньше все было довольно просто, источником времени в домене обычно служили аппаратные часы эмулятора PDC, ну отстали или убежали на пару минут, в конце концов можно и подвести. Когда добавилось требование взаимодействия с внешними системами критичными к точному времени (например, использующих криптографию), то в качестве источника времени стал выступать внешний сервер. От него получал время эмулятор PDC, с ним синхронизировались контроллеры, а от них точное время расходилось на остальных участников домена.

Работа PDC эмулятора

С приходом виртуализации все изменилось, появился еще один источник времени — время хоста виртуализации. Многие гипервизоры по умолчанию имеют включенной настройку синхронизации времени гостевых систем и при попадании в виртуальную среду контроллера может возникнуть следующая коллизия: контроллер синхронизирует время с хостом, но сам хост, являясь членом домена, в свою очередь синхронизируется с контроллером.

Еще хуже, если в виртуальную среду попадает эмулятор PDC, в силу особенностей таймера виртуальных машин, время внутри может достаточно сильно плавать, поэтому виртуальный эмулятор PDC всегда должен синхронизировать время с внешним источником, а синхронизация времени с хостом должна быть отключена, последнее касается и всех остальных виртуальных членов домена.

Проверяем откуда сервер берет время

Давайте перейдем от теории к практике. Начнем с того, что выясним кто из контроллеров является эмулятором PDC и эталоном времени для домена. Это можно сделать на любом контроллере домена командой:

netdom query fsmo

В выводе будут показаны все хозяева операций, нас интересует только эмулятор PDC.

Затем перейдем на указанный контроллер и узнаем источник времени для него, для этого выполните команду:

w32tm /query /source

Если в выводе вы увидите:

Local CMOS Clock
Free-Running System Clock

то источником времени являются аппаратные часы. А если там будет:

VM IC Time Synchronization Provider

то вы имеете дело с виртуальной машиной, которая синхронизирует время с хостом.

Данную настройку следует исправить, это можно сделать в настройках виртуальной машины, отключив синхронизацию времени с хостом, либо в самой системе, для этого откройте ветвь реестра:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\VMICTimeProvider

и установите для параметра Enabled значение 0.

После данного изменения следует перезапустить Службу времени Windows как показано ниже или перезагрузить компьютер.

net stop w32time
net start w32time

Далее будет показана быстрая настройка NTP клиента на сервере и более расширенная.

Быстрая настройка NTP на Windows Server 2016

На вашем Windows Server 2016 нажмите кнопку Windows и введите: PowerShell, щелкните правой кнопкой мыши и выберите «Запуск от имени администратора».

Введите следующие команды

w32tm /config /manualpeerlist:ntp1.stratum2.ru /syncfromflags:manual /reliable:yes /update

reliable:(YES|NO) — определяет, является ли этот компьютер надежным источником времени


Stop-Service w32time
Start-Service w32time

Конечно, вы можете взять любой NTP-сервер, какой захотите. Я брал отсюда

Теперь проверьте, правильно ли настроен сервер времени на вашем сервере Server 2016, набрав:

w32tm /query /status

Расширенная настройка NTP на Windows Server 2016

Расширенная настройка нашего эмулятора PDC на работу с внешними источниками точного времени. Все изменения также будут вноситься через реестр. Прежде всего изменим тип сервера на NTP, для этого откроем ветку

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

и для параметра Type укажем строковое значение NTP. А для параметра NtpServer зададим адреса серверов точного времени, после каждого из которых, через запятую укажем 0x8, если мы хотим работать как стандартный NTP-клиент или 0x1 если будем использовать собственные параметры, например:

ntp1.stratum2.ru,0x1 ntp2.stratum2.ru,0x1 ntp4.stratum2.ru,0x1

После чего в

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

Параметр Enabled установим в значение 1.

Затем перейдем в

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config

и установим для параметра AnnounceFlags значение A.

Значение «AnnounceFlags» может составлять сумму его флагов, например:

10=2+8 — NTP-сервер заявляет о себе как о надежном источнике времени при условии, что сам получает время из надежного источника либо является PDC корневого домена. Флаг 10 задается по умолчанию как для членов домена, так и для отдельно стоящих серверов.

5=1+4 — NTP-сервер всегда заявляет о себе как о надежном источнике времени. Например, чтобы заявить рядовой сервер (не контроллер домена) как надежный источник времени, нужен флаг 5;

Следующие параметры будут работать, только если мы при указании серверов добавили 0x1, иначе будут использоваться настройки, предлагаемые сервером. Чтобы задать период синхронизации откройте ветку

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

и для параметра SpecialPollInterval укажите десятичное значение в секундах.

Вернемся в

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config

И зададим максимальное время опережения и отставания часов, после которых синхронизация производиться не будет. Для этого используются параметры MaxPosPhaseCorrection (опережение) и MaxNegPhaseCorrection (отставание) для которых также следует задать десятичное значение в секундах. По умолчанию стоит 48 часов. Это значит, что если время на эмуляторе PDC уйдет от точного источника более чем на 48 часов в любую сторону, то синхронизация производиться не будет.

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

Выполнив настройки перезапустите Службу времени Windows, это также можно сделать в командной строке:

net stop w32time
net start w32time

После чего еще раз выполним команду чтобы показать источники времени и их состояние

w32tm /query /peers

выполняем еще команду

w32tm /query /source

и убедимся, что источником времени для эмулятора PDC является внешний сервер.

Затем выполним данную команду на рядовых контроллерах домена, в качестве источника времени там должен быть указан эмулятор PDC, и на обычных ПК, где в выводе будет присутствовать любой из контроллеров домена. Обязательно выполните контроль для виртуальных машин, чтобы быть уверенным, что они используют время домена, а не хоста виртуализации.

Проверка работы NTP сервера (Живой ли внешний NTP сервер с которого мы берем время)

В Windows, нужно открыть командную строку и выполнить команду w32tm со специальными параметрами. Где ntp1.stratum2.ru — это NTP сервер

w32tm /stripchart /computer:ntp1.stratum2.ru /dataonly /samples:3

Ответ будет содержать локальное время, и разницу со временем на указанном NTP сервере. Например:

w32tm /stripchart /computer:ntp1.stratum2.ru /dataonly /samples:3
Tracking ntp1.stratum2.ru [88.147.254.230:123].
Collecting 3 samples.
The current time is 8/1/2022 3:48:56 PM.
15:48:56, +00.0098812s
15:48:58, -00.0036452s
15:49:00, +00.0005137s
PS C:\Users\Administrator>

На данном выводе видно что погрешность синхронизации составяляет +00.0098812s

Список команд w32tm

Основные команды конфигурации w32tm

  • w32tm /register — Регистрация и включение службы со стандартными параметрами.
  • w32tm /unregister — Отключение службы и удаление параметров конфигурации.
  • w32tm /monitor — Просмотр информации по домену.
  • w32tm /resync — Команда принудительной синхронизации с заданным в конфигурации источником.
  • w32tm /config /update — Применить и сохранить конфигурацию.
  • w32tm /config /syncfromflags:domhier /update – Задаем настройку синхронизации с контроллером домена.
  • w32tm /config /syncfromflags:manual /manualpeerlist:time.windows.com – задать конкретные источники синхронизации времени по протоколу NTP.

Просмотр параметров (/query)

  • w32tm /query /computer:<target>  — Информация о стутусе синхронизации определенной станции (если имя не указано — используется локальный компьютер).
  • w32tm /query /Source – Показать источник времени.
  • w32tm /query /Configuration — Вывод всех настроек службы времени Windows.
  • w32tm /query /Peers – Показать источники времени и их состояние.
  • w32tm /query /Status – Статус службы времени.
  • w32tm /query /Verbose – Подробный вывод всей информации о работе службы.

Также хотел бы поделится комментарием найденным на форуме

За настройку NTP через политики надо больно бить по рукам.
1. В доменной среде ничего не надо делать, контроллеры берут время с PDC, клиенты с контроллера.
2. Точности времени секунда в секунду не добьетесь.
Больная тема для меня. Предыдущие админы нахреначили синхронизацию чуть ли не в 10 разных политиках, до сих пор натыкаюсь и с матами удаляю.
Есть проблема с синхронизацией времени?
На всех контроллерах:
1. Убиваем службу w32time
2. Грохаем ветку реестра HKLM\System\CurrentControlSet\services\W32Time\
3. Регистрируем службу заново
4. Проверяем, что параметр TYPE в HKLM\System\CurrentControlSet\services\W32Time\Parameters равен NT5DS

Конфигурация NTP-сервера
Задаем тип синхронизации внутренних часов, на использование внешнего источника. 
NoSync — NTP-сервер не синхронизируется с каким либо внешним источником времени. Используются системные часы, встроенные в микросхему CMOS самого сервера.
NTP — NTP-сервер синхронизируется с внешними серверами времени, которые указаны в параметре реестра NtpServer.
NT5DS — NTP-сервер производит синхронизацию согласно доменной иерархии.
AllSync — NTP-сервер использует для синхронизации все доступные источники.

На PDC настраиваем синхронизацию с внешним поставщиком времени
5. И ничего б*ть не трогаем!=) Через какое-то время время стабилизируется.
Для понимания — время не импортируется, оно сверяется и подгоняется под эталон.
Не забываем, что для керберос разница в 5 минут не критична.
Хитрожопых кадровиков и безопасников, желающих снихронить свои убогие СКУДы с виндовыми тачками слать надолго и подальше.
Всё, я кончил =)
===
Полностью согласен. Время домена — не повод для торговли. Оно должно быть правильным, но в разумных пределах, плюс-минус несколько минут не являются критичными для общения. Хотя встречал домен, где для хождения кербероса админы сделали максимальную погрешность часов сутки. Всякое бывает, но «правильный» админ всегда найдет решение… или костыль…
===
ПК не знает и никак не узнает, что PDC сменился. Так что политика обязательно должна быть!
===
А ему не надо знать. Он кричит в сеть «PDC!!!», а те сами знают, кому из них отозваться. У них DNS для этого есть.




Network Time Protocol (NTP) runs on the Transport Layer port 123 UDP and enables accurate time synchronization for network computers. This irons out time inconsistencies on servers and clients during file logging or replication of server databases among other resources.

In this article, we’ll outline the process of installing, configuring, and querying an NTP server on Windows Server 2019.

NTP Server

NTP servers utilize the Network Time Protocol to send time signals to servers across the globe upon request. NTP servers use the Universal Time Coordinated (UTC) time source for time signal synchronization.

The main purpose of NTP servers is to provide time synchronization for servers and computer networks with other major network servers and clients across the globe. In turn, this streamlines communications and transactions all over the world.

Installing and Configuring an NTP Server on Windows Server 2019

The process of installing, configuring, and querying an NTP Server on Windows Server 2019 is quite straightforward.

Set the NTP service to Automatic option

To start off, Hit Windows Key + R to launch the Run dialogue. Next, type services.msc and hit ENTER.

In the ‘Services’ window, locate the service ‘Windows Time’. Right-click and select the ‘Properties’ option as shown:

On the pop-up window, select the Startup type as ‘Automatic’.

Finally, click on ‘OK’ and then ‘Apply’.

Configuring NTP Server using Registry Editor

As before, launch the run dialogue by pressing Windows Key + R. Then type ‘regedit’ and hit ENTER.

The Registry editor will be launched as shown:

Navigate to the path shown below:

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

On the right pane, locate and double-click the ‘Enabled’ file as shown:

Set the Value data to 1 and click OK.

Next, follow this path.

Computer>HKEY_LOCAL_MACHINE>SYSTEM>CurrentControlSet>Services>W32Time>Config

At the right pane locate the ‘Announce Flags’ file.

Double click on the file and set its value to 5 in the ‘Value Data’ section.

Finally, reboot the NTP server for the changes to take place. Head back to the services Window, right-click on ‘Windows Time’ and select ‘Restart

Configuring NTP Server on Windows 2019 using Windows PowerShell

If you love working in Powershell, launch Powershell as Administrator and enable NTP server using the command:

Set-ItemProperty -Path “HKLM:\SYSTEM\CurrentControlSet\Services\w32time\TimeProviders\NtpServer” -Name “Enabled” -Value 1

Next, configure Announce Flags value as shown:

Set-ItemProperty -Path “HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Config” -Name “AnnounceFlags” -Value 5

Finally, restart the NTP server using the command:

Restart-Service w32Time

Important Note: UDP port 123 must be open for the NTP server traffic to reach your Windows Server 2019. If the NTP servers are unreachable, you can check your firewall settings to fix this.

Other useful commands

  1. w32tm /query /configuration to check and shows the NTP server configuration.
  2. w32tm /query /peers for checking the list of NTP servers configured alongside their configuration status
  3. w32tm /resync /nowait to force-synchronize time with your NTP server.
  4. w32tm /query /source to show the source of the time.
  5. w32tm /query /status to reveal NTP time service status.

Final take

Now your Windows Server 2019 clock is synchronized with time the NTP server’s pool.ntp.org and works as NTP client. You can achieve full network and accompanying infrastructure time synchronization by synchronizing all network workstations, servers, routers, hubs, and switches.

Since NTP servers operate over the UDP protocol using TCP/IP, these network infrastructures must be working efficiently for effective NTP server operation. In case you want to make time servers on windows server 2019 hosted on a virtual machine, you should disable the virtual machine time synchronization settings and sync their time with the domain Windows Server 2019.

Timing is everything! There are thousands of NTP servers around the world. Both the protocol and the client-server program that runs on computers are referred to as NTP. Network Time Protocol (NTP) is an internet protocol used to synchronize with computer clock time sources in a network.  Join us with this article to review the way you can Set NTP Server on Windows Server. A time-stamp data exchange takes place between the server and client, which aids in precisely setting the time on the client systems to match the time on the NTP server.

Since a discrepancy of even a fraction of a second can cause problems, accurate time for all devices on a computer network is important for many reasons. So, NTP Server supports time synchronization and is made to be very fault-tolerant and scalable. After buying Windows VPS, you might need to synchronize the machines on your network at the same time. Setting up NTP Server on Windows Server is what you can do perfectly at the end of this guide. Let’s get started to make your NTP Server ready to synchronize time across your network.

What is NTP Server and Why Set it Up?

NTP is a network protocol that enables you to synchronize clocks on devices over a network. It always makes sure that time differences between the server and client systems are minimized and that client systems are always in sync with the server. It listens on UDP port 123.
Many services and IT applications depend on proper time settings to work as intended, thus keeping your server’s clock accurate is crucial. These comprise, to name a few, database replication, monitoring and auditing applications, and logging services. Server time skew, and client time skew in general, is undesirable and frequently results in conflict in time-critical applications. It is recommended to install and enable an NTP server on your server in order to keep accurate time settings on your server and, by extension, throughout the network.

Set NTP Server on Windows is not that complicated. This tutorial helps you to install and enable the NTP server on your server quickly and simply.

You can easily use NTP on your Windows Time service to synchronize time across a network. Let’s go through the steps of this guide to learn how to Install and Configure NTP Server on Windows. Two different methods will be explained, and you can choose the one you prefer more.

Step 1. Open Registry Editor

Search for the ”Run” application in the start menu. There, type in ”regedit” and press Enter.

Open up Registry Editor

There will appear a window similar to the one below.

Registry Editor Window

Step 2. Find NTP Server Files

Follow the below path to go to the NTP Server Configuration:

Computer>HKEY_LOCAL_MACHINE>SYSTEM>CurrentControlSet>Services>W32Time>TimeProviders>NtpServer.

You can see the tree’s end in the picture below. As you can see, the files we are looking for are on the right pane.

NtpServer Path

Step 3. Enable NTP Server

To open a tiny window, double-click the “Enabled” file. A section on the window titled “Value data” is there. As shown below, change the value from 0 to 1. After changing, click “OK”.

How to Enable NtpServer

Step 4. Create the AnnounceFlags 5

First, let’s see what is AnnounceFlag?

This computer’s status as a trustworthy time server is controlled by entry. If a computer is not also designated as a time server, it cannot be certified as dependable. The default value for domain members is 10. The default value for stand-alone clients and servers is 10.

Follow the path below:

Computer>HKEY_LOCAL_MACHINE>SYSTEM>CurrentControlSet>Services>W32Time>

To go to the ”Config”:

Computer>HKEY_LOCAL_MACHINE>SYSTEM>CurrentControlSet>Services>W32Time>Config.

Make the AnnounceFlags 5

On the right pane, as seen above, you will find a file with the name “AnnounceFlags” while there. Double-click it. That will cause a tiny window akin to the one in Step 3 to open. Change the value from a to 5 under “Value data“.

Step 5. Restart NTP Server

By pressing the Windows key and typing “Services,” the “Services” window will appear. Look for “Windows Time” once it has opened. Click “Restart” from the context menu when you right-click on it.

Restart NtpServer

Step 6. Open UDP port 123 in the Firewall

Your Windows Server must have UDP port 123 open in order for NTP to connect to the clocks. Please check your firewall configuration if you can’t reach the servers. To complete this step, follow the How to open a Port on Windows VPS Firewall guide. Remember that this port is UDP and not TCP.

Configure NTP Using PowerShell

From Windows XP and Windows Server 2008 up to the most recent versions of each OS, PowerShell offers a command-line tool with the name w32tm.exe. You may set up your Windows PC to sync with online time servers using the w32tm.exe program. This is typically the tool of choice when configuring and keeping track of the time on your Windows Server installation. The command-line utility is very simple to use.

If you prefer to use PowerShell, the second method of this guide would be your preferred one to Set NTP Server on Windows. Just open your PowerShell as administrator and use the following commands to do all the steps of the previous method.

Enable NTP Server

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\w32time\TimeProviders\NtpServer" -Name "Enabled" -Value 1

Create the AnnounceFlags 5

Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Config" -Name "AnnounceFlags" -Value 5

Restart NTP Server

Restart-Service w32Time

Run the command below to allow NTP port: (If Firewall is running)

New-NetFirewallRule `
-Name "NTP Server Port" `
-DisplayName "NTP Server Port" `
-Description 'Allow NTP Server Port' `
-Profile Any `
-Direction Inbound `
-Action Allow `
-Protocol UDP `
-Program Any `
-LocalAddress Any `
-LocalPort 123

Most Used Commands to Configure NTP Server

Let’s review some useful commands while setting up NTP Server on Windows.

To check NTP configuration, run:

w32tm /query /configuration

To check NTP server list, type:

w32tm /query /peers

To force NTP server synchronization, run:

w32tm /resync /nowait

Use the command below to show the source of the NTP time:

w32tm /query /source

To show the status of NTP service, type:

w32tm /query /status

At this point, you know everything you need to Set NTP Server on Windows Server.

How to Disable NTP Server on Windows Server?

To disable Windows Internet Time Update, follow the below steps:

1. Load Control Panel.

2. Click Date and Time.

3. Click the Internet Time tab.

4. Click Change settings.

5. Click to clear the checkbox to Synchronize with an Internet time server.

Disable NTP Server on Windows

6. Click OK to save.

7. Close the Date and Time dialog box.

8. Close the Control Panel.

FAQ

A time-request exchange is started by the NTP client and the NTP server. The client can then determine the link latency, its local offset, and set its local clock to sync with the server computer’s clock.

Yes. Go to the «Internet Time» tab and select «Change Settings.» If you want the clock to sync automatically, click the «Synchronize with an internet time server» box; otherwise, uncheck it to set the clock manually.

It is always advised to select an NTP server that is located close to the device you wish to time-synchronize. It is also advised to use a server that is hosted by a reputable business or organization.

Conclusion

In this article, you earned How to Set NTP Server on Windows Server. As we promised, it was simple and straightforward to set up an NTP server on your Windows server instance. After setting up the NTP service on your server, Windows clients connected to the domain will synchronize with the domain controllers and other domain controllers in your environment. Keep in mind that if NTP is set up on a virtual machine, make sure it is configured to exclusively sync with the time service rather than the host system.

If you follow the steps of this guide properly then you can smoothly install and Set NTP Server on Windows without any errors but do not hesitate to contact us if you encounter any problems. Our technical support team will try their best to solve your problems.

StarWind VSAN

Viewing-the-NTP-registry-values-that-are-configured-for-your-Windows-Server
Viewing-the-NTP-registry-values-that-are-configured-for-your-Windows-Server

There is no question about it, having accurate time in your environment set in critical infrastructure systems is a must. Many business-critical applications and infrastructure systems rely on accurate time synchronized between them to ensure the system functions as expected. Time skew can cause all kinds of weirdness when it is misconfigured or out of sync between different servers/systems. This is especially true in a Windows Server Active Directory domain. Having accurate time between a client computer and domain controllers is essential. Let’s take a look at how to set ntp server Windows 2016 or Windows 2019 to see how this can be easily carried out.

What is NTP?

Wen it comes to synchronizing time in most enviornments, Network Time Protocol (NTP) is the protocol that is used to ensure accurate time across your environent. In most environments, NTP servers, special time servers, are configured that provide an external time source for which your internal servers can synchronize with.

There are several widely known NTP IP addresses on the Internet that provide reliable time sources for your network. The NTP.org servers are one such set of time servers that provide an NTP source for configuration.
There are a few NTP values to be aware of:

  • NTP Server – This is a specialized server that is able to detremine the precise time from an external timing reference such as GPS and passes these precise time values on to your network
  • Offset – This is the difference in time between the external time server and the time on a local client computer. The larger the offset, the more inaccurate the timing source is.
  • Delay – This is the value of the round-trip time (latency) of the timing message between the client to the server and back again.

How Time is synchronized in a Windows Server domain

In a Windows domain, Microsoft has default configuration in place that takes care of a good portion of the NTP configuration. Starting with Windows 2000 Server, Windows clients are configured as NTP Clients. When configured as an NTP client, Windows computers only attempt to contact the domain controller for NTP synchronization or a manually specified NTP server.

Cameyo Virtual App Delivery

Microsoft has made the domain controller the default in a Windows domain since it makes sense that clients already have a secure channel established with DCs for other types of communications. Additionally, accurate and synchronized time between domain controllers and clients is especially important for all kinds of things such as logins, group policy synchronization and other tasks/operations.

The order of operations or hierarchy in a Windows domain is as follows:

  • Domain members attempt to synchronize time with any domain controller located in the domain
  • Domain controllers synchronize with a more authoritative domain controller
  • The first domain controller that is installed in the environment is automatically configured to be a reliable time source.
  • Other than the first domain controller installed, the PDC emulator (if role has been moved from the first DC installed) generally holds the position of best time source.

An important point to consider and that comes into play when thinking about why we set ntp server in Windows 2016 or Windows 2019 is the authoritative domain controller must have a reliable source to synchronize with as well. This is generally an external time server outside of the domain hierarchy.

Now that we know how the domain hierarchy for time is configured, how is the external time source configured on your domain controller that is configured as the reliable source of time?

Configuring Windows Time Service with W32tm.exe

When it comes to Windows Server environments like Windows Server 2016 or Windows Server 2019, there is a special Windows service that controls the time synchronization of your Windows hosts. This is the Windows Time Service.

Microsoft provides a command line tool to interact with the Windows Time Service called W32tm.exe. This has been included in Windows operating systems since Windows XP/Windows 2003 and later. It can be used to configure Windows Time service parameters as well as diagnose time service problems. This is generally the tool of choice when it comes to configuring, monitoring, and administering Windows Time.

Using the W32tm.exe utility is fairly straightforward. It can be used from a normal command prompt as well as from a PowerShell prompt. There are several command parameters included that allow not only configuring the NTP servers you want to query, but also parameters that allow viewing the low level registry configuration as well as the synchronization status.

You can read the official Microsoft KB on the Windows Time service and the W32tm.exe utility here:

  • https://docs.microsoft.com/en-us/windows-server/networking/windows-time-service/windows-time-service-tools-and-settings

However, there are a few commands I would like to show you for the purposes of configuring your Domain controller that is to be the reliable time source (PDC Emulator) for your domain.

The first command is the command line entry to specify your NTP servers, which in this case I am using the NTP.org servers to set as the source of my NTP synchronization.

w32tm /config /syncfromflags:manual /manualpeerlist:"0.us.pool.ntp.org 1.us.pool.ntp.org 2.us.pool.ntp.org 3.us.pool.ntp.org" /update

Stop-Service w32time
Start-Service w32time

Configuring-the-time-source-for-your-domain-with-the-w32tm-utility

Configuring the time source for your domain with the w32tm utility

If you want to view the status of the NTP synchronization on your server after you have configured the values and restarted the w32time service, you can use the following command:

w32tm /query /status

Querying-the-NTP-synchronization-status-of-your-Windows-Server-2016-or-2019-domain-controller

Querying the NTP synchronization status of your Windows Server 2016 or 2019 domain controller

You can also check the values configured in your registry key hkey local machine system currentcontrolset services w32time config using the commands below. You can drill into the configuration parameters using the /dumpreg /subkey command.

w32tm /dumpreg

w32tm /dumpreg /subkey:parameters

Viewing-the-NTP-registry-values-that-are-configured-for-your-Windows-Server

Viewing the NTP registry values that are configured for your Windows Server

Final Thoughts

As shown, you can easily set NTP Server Windows 2016 or Windows 2019 using the w32tm command utility that allows interacting with the time service in Windows Server.

In a Windows domain, you want to configure your authoritative time source domain controller, which by default is the PDC Emulator, to pull time information from an authoritative source like NTP.org or some other reliable NTP time server.

After configuring the time source, the other domain controllers will synchronize with this server and then the Windows clients joined to the domain will synchronize with the domain controllers that have the corrected time from the authoritative server.

  • Windows server vpn server sstp
  • Windows server на домашнем компьютере
  • Windows server защита от шифровальщиков
  • Windows server последняя версия скачать
  • Windows server поменять язык интерфейса