Настроить время на windows server 2016

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

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

Содержание

  1. Немного теории
  2. Проверяем откуда сервер берет время
  3. Быстрая настройка NTP на Windows Server 2016
  4. Расширенная настройка NTP на Windows Server 2016
  5. Проверка работы NTP сервера (Живой ли внешний NTP сервер с которого мы берем время)
  6. Список команд w32tm
  7. Также хотел бы поделится комментарием найденным на форуме

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

Синхронизация времени — важный и во многом достаточно критичный аспект работы 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_MACHINESYSTEMCurrentControlSetServicesW32TimeTimeProvidersVMICTimeProvider

и установите для параметра 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_MACHINESYSTEMCurrentControlSetServicesW32TimeParameters

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

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

После чего в

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeTimeProvidersNtpServer

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

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

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeConfig

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

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

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

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

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

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeTimeProvidersNtpClient

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

Вернемся в

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeConfig

И зададим максимальное время опережения и отставания часов, после которых синхронизация производиться не будет. Для этого используются параметры 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:UsersAdministrator>

На данном выводе видно что погрешность синхронизации составяляет +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. Грохаем ветку реестра HKLMSystemCurrentControlSetservicesW32Time
3. Регистрируем службу заново
4. Проверяем, что параметр TYPE в HKLMSystemCurrentControlSetservicesW32TimeParameters равен NT5DS

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

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




Мы рассмотрим как настроить NTP сервер в сети предприятия, где компьютеры пользователей получают точное время от DC с ролью эмулятора PDC (главный контроллер домена – Primary Domain Controller), в свою очередь DC синхронизирует свое время с внешним источником времени. В данном примере мы будем получать время с серверов pool.ntp.org.

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

Настройка сервера времени под  Hyper-V

Для тех у кого контролер домена виртуализирован и поднят на Hyper-V, прежде необходимо отключить Time Synchronization, иначе виртуальная машина будет синхронизирована с Hyper-V сервером.

 В настройках виртуальной машины, в разделе Management -> Integration Services отключаем Time Synchronization
# Выключение синхронизации для VMware 5
Свойства машины - Options -> VMware Tools -> Synchronize guest time with host
# Выключение синхронизации для VMware 6
VMware Tools -> Time -> Synchronize guest time with host

Создание GPO для контроллера домена с ролью эмулятора PDC (главный контроллер домена – Primary Domain Controller)

1 . Создание фильтра WMI

Нам необходимо настроить групповую политику для синхронизации NTP для контролера домена PDC, в связи с тем что роль PDC может перемещаться между контроллерами домена, нам необходимо применить политику к текущему владельцу роли PDC. Для этого мы создадим WMI фильтр, чтобы политика была применена для сервера с ролью PDC.

Для этого в консоли управления Group Policy Management Console (GPMC.msc), в разделе WMI Filters создадим новый WMI фильтр с именем PDC selected и запросом: Select * from Win32_ComputerSystem where DomainRole = 5

Добавляем новый WMI фильтр с именем PDC selected и запросом:
Select * from Win32_ComputerSystem where DomainRole = 5

2 . Создаем и редактируем новую GPO

2.1 Для контейнера Domain Controllers создаем групповую политику, в нашем случае это PDC Time Synchronization.

В пункте 2.1 ошибка. на картинке созданный фильтр не привязан к политике

2.2 Редактируем политику PDC Time Synchronization, разворачиваем Computer Configuration -> Policies -> Administrative Templates -> System -> Windows Time Service -> Time Providers и включаем следующие политики:

Configure Windows NTP Client: Enabled
Enable Windows NTP Client: Enabled
Enable Windows NTP Server: Enabled

2.3 В настройках политики  Enable Windows NTP Server, задаем:

NtpServer: 0.pool.ntp.org,0x1 1.pool.ntp.org,0x1 2.pool.ntp.org,0x1
Type: NTP
CrossSiteSyncFlags: 2
ResolvePeerBackoffMinutes: 15
Resolve Peer BAckoffMaxTimes: 7
SpecilalPoolInterval: 3600
EventLogFlags: 0

Дополнительные опции  политики
Enable Windows NTP Server

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

Выбрать сервер для синхронизации вы можете по ссылке NTPPoolServers

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

0x1 – SpecialInterval, использование специального интервала опроса;
0x2 – режим UseAsFallbackOnly;
0x4 – SymmetricActive, симметричный активный режим;
0x8 – Client, отправка запроса в клиентском режиме.
Проверяем ответ NTP сервера
w32tm /stripchart /computer:192.168.1.100 /dataonly /samples:5

In this article, I will show you how to configure NTP Server on Windows Server 2016 in just a few steps.

We will use PowerShell to change the NTP Server and we will validate if it worked afterward.

Configure the NTP Server on Windows Server 2016

On your Windows Server, 2016 hit the Windows Button and type: PowerShell and right-click it and select Run as Administrator

Type the following commands

w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL
Stop-Service w32time
Start-Service w32time

Of course, you can take any NTP Server that you want.

Now verify if the time-server was set correctly on your Server 2016 by typing:

w32tm /query /status

You should get a reply like this:

Now we will go ahead and verify if our clients sync properly.

Verifying if the Time Server was correctly set on our Clients

On a client computer open a PowerShell with right-click and Run as Administrator….

Type:

w32tm /query /status

Check the time-server and type:

w32tm /resync 
w32tm /query /status

Then you are able to see that the time-server actually changed like in the example below.

And that’s it! Easy, right?

Always make sure that you use the same time-server in your network and that all your clients are syncing with it. If you have time differences inside of your Active Directory Domain you will run into major issues.

The correct date, time, and time zone are one of the first settings a Windows Server should have. In today’s article, we’ll see how we can change time, date, and time zone through the graphical environment, command line and Powershell.

Set time, date, and time zone settings from the graphical interface

The process is very simple. Right-click the time field in the lower right corner and then click the Adjust date/time option.

Configure Date, Time and Time Zone settings in Windows Server 2016

In the settings window, you can change the time, date, and time zones of each Windows Server. I do not think there is a need for further guidance as it is a simple process.

Configure Date, Time and Time Zone settings in Windows Server 2016

Alternatively, you can open the time and date settings window by clicking on the corresponding field in the Local Server section of the Server Manager.

Configure Date, Time and Time Zone settings in Windows Server 2016

As you will see, in this case, opens the “old” management window through which you can set the time, date and time zone.

Set time, date, and time zone settings on command prompt

By typing the following command will open the time and date setting window, even in a Server Core installation.

To display the current date and time, enter the following commands.

Configure Date, Time and Time Zone settings in Windows Server 2016

To set time and date, you can use the corresponding Time and Date commands at the command line.

In Windows Server 2012 have been added the Timezone Utility (tzutil) tool that allows us to display and set a time zone through the Windows command line.

First, open the command line with administrator privileges and make sure you are in the System32 folder.

To display the current Windows Server Time Zone, type the following command.

Configure Date, Time and Time Zone settings in Windows Server 2016

To display all available time zones, type the following command.

Configure Date, Time and Time Zone settings in Windows Server 2016

To change the current time zone in Windows Server, type the following command, between the doubles, enter the time zone as it appears in the list of the previous command. For example, for the Greek time zone type:

tzutil /s "GTB Standard Time"

To confirm that the time zone has changed, you can see the corresponding registry entry by using the following command from within the same command-line window.

reg query HKLMSYSTEMCurrentControlSetControlTimeZoneInformation

Configure Date, Time and Time Zone settings in Windows Server 2016

[pro_ad_display_adzone id=”1683″]

Set time, date and time zone settings on Powershell

To view the current date and time, type the following command.

Configure Date, Time and Time Zone settings in Windows Server 2016

To set the time and date through Powershell the process is very easy. Use the following command as an example by changing the date and time values.

Set-Date -Date "06/06/2017 14:45"

Alternatively, you can simply type the Set-Date command and promptly you will be prompted to enter the server’s date and time.

Configure Date, Time and Time Zone settings in Windows Server 2016

To view the current time zone through Powershell, type the following command.

Configure Date, Time and Time Zone settings in Windows Server 2016

Before changing the time zone, you will need to know the right name. Type the following command to see all available time zones in Windows Server.

Get-TimeZone -ListAvailable

Configure Date, Time and Time Zone settings in Windows Server 2016

To change the time zone, use the following command along with the corresponding time zone of your server.

Set-TimeZone -Name "GTB Standard Time"

This article shows how to configure Windows Time Service (NTP) on Windows Server 2016 so that it acts as an NTP server for domain client computers.

Configure Windows Time Service (NTP)

A prerequisite to having the correct time on the Windows clients, we must have a correct time on the Windows 2016 server. So the first step is to sync server time with pool.ntp.org. Type the following commands on PowerShell:

w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL

Then apply the changes, this is done by restarting the time service. First, we stop the service and then we start it again.

Stop-Service w32time
Start-Service w32time

Now the Windows Server 2016 is an NTP client of pool.ntp.org and its time/clock is synced with the NTP pool servers (The server is at the same time the NTP server for other domain client systems).

Optional: Server is in a Hyper-V VM

If your Windows Server 2016 machine is a VM inside Hyper-V, you have to disable time sync. Go to:

M settings-> Management-> Integration Services

and uncheck:

Time Synchronization.

Otherwise, Windows Server 2016 time/clock will be synced with the Host time/clock.

Configure Windows Clients

Then go to the client machines and run the following command on PowerShell to force them to sync their time/clock with the domain controller on the Windows Server 2016.

w32tm /resync

You can check the time synchronization status using the following command.

w32tm /query /status

Check Windows time sync status

StarWind VSAN

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.

BDR Suite

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.

How to sync the time to a public time server using NTP

You need to use the w32tm command.

First check the current settings :

image

What about the 0x1 parameter ?

https://support.microsoft.com/en-us/help/875424/time-synchronization-may-not-succeed-when-you-try-to-synchronize-with

  • 0x01 – Use special poll interval Special Interval
  • 0x02 – Use As Fall back Only
  • 0x04 – Send request as Symmetric Active mode
  • 0x08 – Send request as Client mode

To set a new External Time Server like pool.ntp.org use this command :

net stop w32time

w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL

net start w32time

w32tm /resync

This is the configuration :

w32tm /query /configuration

image

These are all the command line switches :

w32tm [/? | /register | /unregister ]
? – this help screen.
register – register to run as a service and add default
configuration to the registry.
unregister – unregister service and remove all configuration
information from the registry.

w32tm /monitor [/domain:<domain name>]
[/computers:<name>[,<name>[,<name>…]]]
[/threads:<num>] [/ipprotocol:<4|6>] [/nowarn]
domain – specifies which domain to monitor. If no domain name
is given, or neither the domain nor computers option is
specified, the default domain is used. This option may be
used more than once.
computers – monitors the given list of computers. Computer
names are separated by commas, with no spaces. If a name is
prefixed with a ‘*’, it is treated as an AD PDC. This option
may be used more than once.
threads – how many computers to analyze simultaneously. The
default value is 3. Allowed range is 1-50.
ipprotocol – specify the IP protocol to use. The default is
to use whatever is available.
nowarn – skip warning message.

w32tm /ntte <NT time epoch>
Convert a NT system time, in (10^-7)s intervals from 0h 1-Jan 1601,
into a readable format.

w32tm /ntpte <NTP time epoch>
Convert an NTP time, in (2^-32)s intervals from 0h 1-Jan 1900, into
a readable format.

w32tm /resync [/computer:<computer>] [/nowait] [/rediscover] [/soft]
Tell a computer that it should resynchronize its clock as soon
as possible, throwing out all accumulated error statistics.
computer:<computer> – computer that should resync. If not
specified, the local computer will resync.
nowait – do not wait for the resync to occur;
return immediately. Otherwise, wait for the resync to
complete before returning.
rediscover – redetect the network configuration and rediscover
network sources, then resynchronize.
soft – resync utilizing existing error statistics. Not useful,
provided for compatibility.

w32tm /stripchart /computer:<target> [/period:<refresh>]
[/dataonly] [/samples:<count>] [/packetinfo] [/ipprotocol:<4|6>]
Display a strip chart of the offset between this computer and
another computer.
computer:<target> – the computer to measure the offset against.
period:<refresh> – the time between samples, in seconds. The
default is 2s
dataonly – display only the data, no graphics.
samples:<count> – collect <count> samples, then stop. If not
specified, samples will be collected until Ctrl-C is pressed.
packetinfo – print out NTP packet response message.
ipprotocol – specify the IP protocol to use. The default is
to use whatever is available.

w32tm /config [/computer:<target>] [/update]
[/manualpeerlist:<peers>] [/syncfromflags:<source>]
[/LocalClockDispersion:<seconds>]
[/reliable:(YES|NO)]
[/largephaseoffset:<milliseconds>]
computer:<target> – adjusts the configuration of <target>. If not
specified, the default is the local computer.
update – notifies the time service that the configuration has
changed, causing the changes to take effect.
manualpeerlist:<peers> – sets the manual peer list to <peers>,
which is a space-delimited list of DNS and/or IP addresses.
When specifying multiple peers, this switch must be enclosed in
quotes.
syncfromflags:<source> – sets what sources the NTP client should
sync from. <source> should be a comma separated list of
these keywords (not case sensitive):
MANUAL – sync from peers in the manual peer list
DOMHIER – sync from an AD DC in the domain hierarchy
NO – sync from none
ALL – sync from both manual and domain peers
LocalClockDispersion:<seconds> – configures the accuracy of the
internal clock that w32time will assume when it can’t acquire
time from its configured sources.
reliable:(YES|NO) – set whether this machine is a reliable time source.
This setting is only meaningful on domain controllers.
YES – this machine is a reliable time service
NO – this machine is not a reliable time service
largephaseoffset:<milliseconds> – sets the time difference between
local and network time which w32time will consider a spike.

w32tm /tz
Display the current time zone settings.

w32tm /dumpreg [/subkey:<key>] [/computer:<target>]
Display the values associated with a given registry key.
The default key is HKLMSystemCurrentControlSetServicesW32Time
(the root key for the time service).
subkey:<key> – displays the values associated with subkey <key>
of the default key.
computer:<target> – queries registry settings for computer <target>.

w32tm /query [/computer:<target>]
{/source | /configuration | /peers | /status}
[/verbose]
Display a computer’s windows time service information.
computer:<target> – query the information of <target>. If not
specified, the default is the local computer.
source: display the time source.
configuration: display the configuration of run-time and where
the setting comes from. In verbose mode, display the undefined
or unused setting too.
peers: display a list of peers and their status.
status: display windows time service status.
verbose: set the verbose mode to display more information.

w32tm /debug {/disable | {/enable /file:<name> /size:<bytes> /entries:<value>
[/truncate]}}
Enable or disable local computer windows time service private log.
disable: disable the private log.
enable: enable the private log.
file:<name> – specify the absolute filename.
size:<bytes> – specify the maximum size for circular logging.
entries:<value> – contains a list of flags, specified by number and
separated by commas, that specify the types of information that
should be logged. Valid numbers are 0 to 300. A range of numbers
is valid, in addition to single numbers, such as 0-100,103,106.
Value 0-300 is for logging all information.
truncate: truncate the file if it exists.

Now that you set the server to properly sync you can use this one as internal NTP server for other devices.

TIP :

Keep in mind to set the firewall UDP 123 rules to accept.

More info see here

Enjoy !


This entry was posted on Wednesday, October 30th, 2019 at 4:18 pm and is filed under Server, Windows. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Содержание

  • 1 Инструкция по настройке сервера NTP на ОС Windows 7/8/2008/2012 
  • 2 Изменить сервер времени в Windows 10
  • NetPing
  • >
  • Блог
  • >
  • Примеры применения
  • >
  • Пример настройки локального NTP сервера для работы с устройствами NetPing

Примеры применения08.12.2014

Для синхронизации времени устройства NetPing используют протокол NTP. При помощи этого протокола все устройства в сети корректируют своё время по указанному серверу. Устройства NetPing, подключенные к Internet, могут использовать публичный NTP сервер, как рекомендовано в статье. Если доступа к сети Internet нет, то можно настроить локальный NTP сервер. Таким сервером может являться любой компьютер с ОС Windows с настроенной службой W32TimeСлужба времени Windows»). Данная служба не имеет графического интерфейса и настраивается либо через командную строку либо путём правки ключей реестра.

Инструкция по настройке сервера NTP на ОС Windows 7/8/2008/2012 

Рассмотрим настройку службы времени через редактирование реестра. Настройка происходит одинаково для версий Windows 7/8, Windows Server 2008, Windows Server 2012.

Для данной настройки необходимо обладать правами администратора ОС Windows

Открываем редактор реестра либо через диалоговое окно «Выполнить», вызванное комбинацией клавиш «Win» + «R», либо через форму поиска, где набираем «regedit».

В открывшемся редакторе в левом древовидном меню открываем «ветвь» «HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesW32TimeTimeProvidersNtpServer», где ищем ключ с названием «Enable». Нажимаем правой кнопкой мыши и выбираем «Изменить». Меняем значение ключа с на 1.

_nping_power_ETH_2PWR220_v12_small1.png

Управляемый блок удаленного распределения питания по сети Ethernet/Internet (IP PDU)2 независимые управляемые подробнее…

Цена: 8 157 руб.

</span></p>Устройство NetPing 2/PWR-220 v13/GSM3G_nping_power_2PWR220_v13_3G_small1.png Управляемый блок удаленного распределения питания по сети Ethernet/Internet (IP PDU) c поддержкой управления подробнее…

Цена: 13 732 руб.

NetPing датчик наличия электропитания 995S1_acces_sensr_supply_voltage_sensor_995s1_small1.png Датчик позволяет определить наличие напряжения в розетке питания. Выполнен в корпусе блока питания с подробнее…

Цена: 1 224 руб.

WLC10 кабель протечки_acces_sensr_WLC10_small.png Чувствительный кабель для использования совместно с датчиком VT592. Может быть смонтирован в труднодоступных подробнее…

Цена: 6 700 руб.

VT592 кабельный датчик протечки_acces_sensr_VT592_small1.png Датчик предназначен для работы совместно с кабелем протечки WLC10. Возможность подключения датчика как подробнее…

Цена: 3 800 руб.

При работе со специализированным программным обеспечением, системами бухгалтерского учета, программами для трейд-ина на биржах, букмекерскими приложениями и другим софтом большое значение имеет пунктуальность выполнения задач. Несовпадение локального времени со временем компьютера может обернуться для пользователя различными негативными последствиями — вплоть до потери денежных средств.

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

Точное время на компьютере

Базовой задачей любого современного устройства — от смартфона до компьютера — является подсчет времени. Без этой фундаментальной функции выполнение компьютером какой-либо задачи невозможно в принципе. Аппаратная и программная составляющая устройств построена на том, чтобы сначала отсчитывать время, а только потом выполнять возложенную на них задачу.

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

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

Автоматическая синхронизация времени NTP

Любая операционная система, установленная не компьютер или мобильное устройство, имеет встроенную функцию синхронизации внутренних часов. Эта функция выполняет очень простую задачу — отправляет запрос на сервер синхронизации времени, а затем настраивает системные часы в соответствии с полученным ответом.

Для передачи необходимых данных операционная система использует специальный сетевой протокол NTP — «Network Time Protocol» или «Протокол сетевого времени». Данным протоколом учитывается длительность задержки между отправкой запроса на сервер и получением ответа от него. Благодаря этому принципу функционирования NTP даже при низкой скорости работы интернета на пользовательском компьютере будет установлено точное время с погрешностью не более 10 миллисекунд (1/100 секунды).

Что такое сервер синхронизации времени?

Сервер синхронизации времени (или сервер точного времени, NTP-сервер) — сервер, в задачу которого входит формирование и отправка пакета данных, в котором и содержится информация о текущем времени того региона, где физически расположен компьютер.

Здесь автоматически напрашивается вопрос: «Откуда сам NTP-сервер получает данные о времени в той или иной точке земного шара?» Все очень просто — NTP-сервер получает нужные данные от государственных служб точного времени или других источников. Последние, в свою очередь, сверяются по времени с реально действующими «Эталонами времени» — сложными комплексами, состоящими из множества технических систем и приборов измерения времени.

Синхронизация времени через TimeServer

В настоящий момент существует большое количество бесплатных NTP-серверов. Одним из самых популярных в России и во многих других странах мира является сервер точного времени TimeServer. Основные преимущества сервера:

  • Возможность синхронизации со временем всех стран и городов мира.
  • Минимально возможная погрешность (сервер осуществляет синхронизацию времени с атомным эталоном времени).
  • Высокая скорость обработки данных независимо от количества подключенных к серверу компьютеров.

Настройка синхронизации времени с сервером TimeServer в Windows 10

Приведем пошаговую инструкцию настройки синхронизации времени с NTP-сервером TimeServer.

step1-1.jpg

Шаг 1

Откройте меню «Пуск» и кликните по значку в виде шестеренки.

step1-2.jpg

Шаг 2

В открывшемся окне «Параметры Windows» выберите раздел «Время и язык».

step1-3.jpg

Шаг 3

Во вновь открывшемся окне перейдите во вкладку «Регион и язык», а затем в раздел «Дополнительные параметры даты и времени, региональные параметры».

step1-4.jpg

Шаг 4

В правой части окна найдите подраздел «Установка даты и времени» и откройте его.

step1-5.jpg

Шаг 5

В окне «Дата и время» откройте вкладку «Время по интернету».

step1-6.jpg

Шаг 6

Нажмите на кнопку «Изменить параметры…».

step1-7.jpg

Шаг 7

Время интернет-сервера используется для обеспечения точности ваших системных часов, и поэтому очень важно поддерживать время в Интернете обновлено. Ваш ПК для Windows использует часы для обновления и изменения ваших файлов. Хотя настройки даты и времени для Windows 10i довольно просты в доступе, для доступа к настройкам сервера таймера необходимо пройти через панель управления. В этом сообщении мы видим, как изменить Time Server в Windows 10 . Мы также увидим, как добавить новые серверы времени по вашему выбору в вашу систему Windows 10.

Изменить сервер времени в Windows 10

how-to-add-or-change-time-server-in-windows-10.jpg

Введите «Панель управления» в «Начать поиск» и нажмите «Ввод», чтобы открыть Панель управления вашего ПК с Windows 10.

Введите «Дата и время» в поле поиска и нажмите на результат.

Нажмите вкладку « Время в Интернете» и нажмите на кнопку ` Изменить настройки .

В раскрывающемся меню выберите, скажем, time.nist.gov , как сервер, и нажмите « Обновить сейчас» .

Если вы получили какую-либо ошибку, попробуйте использовать pool.ntp.org как ваш сервер времени, а затем нажмите кнопку «Обновить сейчас».

Убедитесь, что вы выбрали флажок « Синхронизировать с сервером интернет-времени .

Добавить новые серверы времени на Windows 10

how-to-add-or-change-time-server-in-windows-10.png

Если вы хотите добавить больше серверов времени в раскрывающийся список, откройте редактор реестра и перейдите к приведенному ниже пути —

 HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / DateTime / Servers 

Это покажет вам список текущих серверов available-time.windows.com

  • time-nist.gov
  • time-nw.nist.gov
  • time-a.nist.gov
  • time-b.nist.gov

Если вы хотите добавить Time Servers, вы можете использовать следующие экземпляры или любой другой по вашему выбору:

  • pool.ntp.org
  • isc.org

Просто выберите сервер, который вы хотите добавьте, щелкните правой кнопкой мыши в любом месте справа и выберите «Создать»> «Значение строки». Введите следующий номер и укажите адрес сервера времени в поле «Значение».

По завершении вернитесь к параметрам Дата и время , выберите свой сервер и нажмите Обновить сейчас

Принудительно синхронизировать синхронизацию времени с помощью CMD

Вы также можете заставить Windows синхронизировать время с помощью W32tm.exe. W32tm.exe — это строка командной строки, используемая для настройки, мониторинга или устранения неполадок службы времени Windows на ПК под управлением Windows 10.

Для этого откройте приведенную выше командную строку и введите следующие команды один за другим:

 net stop w32time w32tm / unregister w32tm / register net start w32time w32tm / resync 

Перезагрузите компьютер и посмотрите, помогло ли оно.

Используемые источники:

  • http://www.netping.ru/blog/primer-nastrojki-lokalnogo-ntp-servera-dlya-raboty-s-ustrojstvami-netping
  • https://www.timeserver.ru/sync/ntp/windows-10
  • https://ru.joecomp.com/how-to-add-or-change-time-server-in-windows-10

Accurate Time For Windows Server 2016

It is important for Windows Server 2016 to maintain an accuracy of 1ms in sync with the UTC time. This is because new algorithms and periodic time checks are obtained from a valid UTC server.

The Windows time service is a component that uses a plugin for the client and server for synchronization.

Windows has two built-in client time providers that link with the third party plugins.

One of the providers uses the Network Time Protocol (NTP) or the Microsoft Network Time Protocol (MS-NTP) to manage the synchronizations to the nearest server.

Windows has a habit of picking the best provider if the two are available.

This article will discuss the three main elements that relate to an accurate time system in Windows Server 2016:

  • Measurements
  • Improvements
  • Best practices

Domain Hierarchy

Computers that are members of a domain use the NTP protocol that authenticates to a time reference in relating to security and authenticity.

The domain computers synchronize with the master clock that is controlled by domain hierarchy and the scoring system.

A typical domain has hierarchical stratum layers where each Domain Controller (DC) refers to the parent DC with accurate time.

The hierarchy revolves around the Primary Domain Controller (PDC) or a DC with the root forest, or a DC with a Good Time Server for the Domain (GTIMESERV) flag.

Standalone computers use the time.windows.com service. The name resolution takes place when the Domain Name Service resolves to a time owned by a Microsoft resource.

Like any other remotely located time references, network outages do not allow synchronization to take place. Paths that are not symmetrical in a network reduce time accuracy.

Hyper-V guests have at least two windows time providers; therefore, it is possible to observe different behaviors with either the domain or the standalone.

NOTE: stratum refers to a concept in both the NTP and the Hyper-V providers. Each has a value indicating clock location in the hierarchy. Stratum 1 is for high-level clock, and stratum 0 is for hardware. Stratum 2 servers communicate to stratum 1 servers, stratum 3 to stratum 2, and the cycle continues. The lower strata show clocks that are more accurate with the possibility of finding errors. The command line tool w32tm (W32time) takes time from stratum 15 and below.

Factors Critical For Accurate Time

1. Solid Source Clock

The original source of the clock needs to be stable and accurate at all times. This implies that during the installation of the Global Positioning Service (GPS) pointing to stratum 1, you should take #3 into consideration.

Therefore, if the source clock shows stability, then the entire configuration will have a constant time.

Securing the original source time means that a malicious person will not be able to expose the domain to time-based threats.

2. Stable Client Clock

A stable client takes the natural drift of the oscillator to make sure that it is containable. The NTP uses multiple samples to condition the local clocks on standalone to stay on course.

If the time oscillation on the client computers is not stable, there will be fluctuations between adjustments leading to malfunctioning of the clock.

Some machines may require hardware updates for proper functioning.

3. Symmetrical NTP Communication

The NTP connection should be symmetrical at all times because the NTP uses calculation adjustments to set time as per the symmetry levels.

If the NTP request takes longer than the expected time on its return, time accuracy is affected. You may note that the path could change due to changes in topology or routing of packets through different interfaces.

The battery-powered devices may use different strategies, which in some cases require that the device be updating every second.

Such a setting consumes more power and can interfere with power saving modes. Some battery run devices have some power settings that can interfere with the running of other applications and hence interfere with the W32time functions.

Mobile devices are never 100% accurate, especially if you look at the various environmental factors that interfere with the clock accuracy. Therefore, battery-operated devices should not have high time accuracy settings.

Why is Time Important

A typical case in a Windows environment is the operation of the Kerberos that needs at least 5 minutes accuracy between the clients and servers.

Other instances that require time include:

  • Government regulations, for example, the United States of America uses 50ms for FINRA, and the EU uses 1ms ESMA or MiFID II.
  • Cryptography
  • Distributed systems like the databases
  • Block chain framework for bitcoin
  • Distributed logs and threat analysis
  • AD replication
  • The Payment Card Industry (PCI)
  • The Time Improvements for Windows Server 2016
  • Windows Time Service and NTP

The algorithm used in Windows Server 2016 has greatly improved the local clock when synchronizing with the UTC. The NTP has four values to calculate the time offset based on timestamps of client requests or responses and server requests and responses.

The modern network environment has too much congestion and related factors that affect the free flow of communication.

Windows Server 2016 uses different algorithms to cancel out the disturbances. Besides, the source used in Windows for time references uses improved Application Programming Interface (API) with the best time resolution, giving an accuracy of 1ms.

Hyper-V

Windows 2016 Server made some improvements that include accurate VM start and VM restore. The change gives us an accuracy of 10µs of the host with a root mean square (RMS) of 50µs for a machine carrying a 75% load.

Moreover, the stratum level at the host sends to guests more transparently. Earlier hosts would be fixed at stratum 2, regardless of its accuracy and the changes in Windows Server 2016 the host reports at stratum 1, which gives better timing for the virtual machines.

Domains created in Windows 2016 Server will find time to be more accurate because the time does not default to the host and that is the reason behind manually disabling the Hyper-V time provider settings in Windows joining a Windows 2012R2 and below.

Monitoring

Counters tracking the performance counters are now part of the Windows Server 2016, they allow for monitoring, troubleshooting, and baselining time accuracy.

The counters include:

a. Computed Time Offset

This feature indicates the absolute time between the system clock and the chosen time source in microseconds. The time updates whenever a new valid sample is available. Clock accuracy is traced using the performance counter that has an interval of 256 seconds or less.

b. Clock Frequency Adjustment

This adjustment indicates the time set by the local W32Time measured in parts per billion. The counter is important when it comes to visualizing actions taken by W32time.

c. NTP Roundtrip Delay

NTP Roundtrip Delay is the time taken during the transmission of a request to the NTP server and when the response is valid.

This counter helps in characterizing the delays experienced by the NTP client. If the roundtrip is large or varies, it can lead to noise, especially when the NTP computes time, thereby affecting time accuracy.

d. NTP Client Source Count

The source count parameter holds the number of clients and unique IP addresses of servers that are responding to client requests. The number may be large or small compared to active peers.

e. NTP Server Incoming Requests

A representation of the number of requests received by the NTP server indicated as request per second.

f. NTP Server Outgoing Responses

A representation of the number of answered requests by the NTP server indicated as responses per second.

The first three show the target scenarios for troubleshooting accuracy issues. The last three cover NTP server scenarios, which help to determine the load and setting a base for the current performance.

Configuration Updates per Environment

The following is a description that changes the default configurations between Windows 2016 and earlier versions.

The settings for Windows Server 2016 and Windows 10 build 14393 are now taking unique settings.

Role

Settings

Server 2016

Windows 10

Servers 12 and 08 and Windows 10

Standalone or a Nano Server

       
 

Time server

time.windows.com

N/a

time.windows.com

 

Poling frequency

64-1024 seconds

N/a

Once a week

 

Clock update frequency

Once a second

N/a

Once a hour

Standalone Client

       
 

Time server

N/a

time.windows.com

time.windows.com

 

Polling frequency

N/a

Once a day

Once a week

 

Clock update frequency

N/a

Once a day

Once a week

Domain Controller

       
 

Time server

PDC/GTIMESERV

N/a

PDC/GTIMESERV

 

Polling frequency

64 to 1024 seconds

N/a

1024 to 32768 seconds

 

Clock update frequency

Once a day

N/a

Once a week

Domain Member Server

       
 

Time server

DC

N/a

DC

 

Polling frequency

64 to 1024 seconds

N/a

1024 to 32768 seconds

 

Clock update frequency

Once a second

N/a

Once every 5 minutes

Domain Member Client

       
 

Time server

N/a

DC

DC

 

Polling frequency

N/a

1024 to 32768 seconds

1024 to 32768 seconds

 

Clock update frequency

N/a

Once every 5 minutes

Once every 5 minutes

Hyper-V Guest

       
 

Time server

Chooses the best alternative based on host stratum and time on the server

Chooses the best alternative based on host stratum and time server

Defaults to host

 

Polling frequency

Based on the role above

Based on the role above

Based on the role above

 

Clock update frequency

Based on the role above

Based on the role above

Based on the role above

Impact of Increased Polling and Clock Update Frequency

To get the most accurate time, the defaults for polling frequencies and clock updates will give you the ability to make adjustments more frequently.

The adjustments lead to more UDP and NTP traffic that will in no way affect the broadband links.

Battery devices do not store the time when turned off, and when turned on, it may lead to frequent time adjustments. Increasing the polling frequency will lead to instability, and the device will use more power.

Domain controllers should have less interference after multiple effects of increasing updates from NTP clients and AD domain. NTP does not require many resources compared to other protocols.

You can reach the limits of the domain functionality before getting a warning, indicating increased settings in Windows Server 2016.

The AD does not use secure NTP, which does not synchronize time accurately but will increase the clients two strata away from the PDC.

You can reserve at least 100NTP requests per second for every core. If you have a domain with 4 CPUs each, the total NTP should be serving 1,600 NTP requests per second.

As you set up the recommendations, ensure you have a large dependency on the processor speeds and loads. Administrators should conduct all baseline tests onsite.

If your DCs are running on sizeable CPU load of more than 40%, the system is likely to generate some noise when NTP is responding to requests, which may impair domain time accuracy.

Time Accuracy Measurements

Methodology

Different tools can be used to gauge the time and accuracy of Windows Server 2016.

The techniques are applicable when taking measurements and tuning the environment to determine if the test outcome meet the set requirements.

The domain source clock has two precision NTP servers and GPS hardware.

Some of these tests need a highly accurate and reliable clock source as a reference point adding to your domain clock source.

Here are four different methods for measuring accuracy in physical and virtual machines:

  • Take the reading of the local clock conditioned by a w32tm and reference it against a test machine with a separate GPS hardware.
  • Measure pings coming from the NTP server to its clients using the “stripchart” of the W32tm utility
  • Measure pings from the client to the NTP server using “stripchart” of the W32tm utility.
  • Measure the Hyper-V output from the host to the guests using the Time Stamp Counter (TSC). After getting the difference of the host and client time in the VM, use the TSC to estimate the host time from the guest. We also consider the use of TSV clock to factor out delays and the API latency.

Topology

For comparison purposes, testing both the Windows Server 2012R2 and Windows Server 2016 based on topology is sensible.

The topologies have two physical Hyper-V hosts that point to a 2016 Server with a GPS hardware installed. Each of these hosts runs at least three domains joining the Windows guests, taking the arrangement shown in the diagrams below.

TOPOLOGY 1. Image Source

The lines on the diagram indicate time hierarchy and the transport or protocol used.

TOPOLOGY 2. Image Source

Graphical Results Overview

The following graph is a representation of the time accuracy between two members of a domain. Every graph shows both Windows Server 2012R2 and 2016 outcome.

The accuracy was a measurement taken from the guest machine in comparison to the host. The graphical data shown indicate both the best and worst case scenarios.

TOPOLOGY 3. Image Source

Performance of the Root Domain PDC

The root PDC synchronizes with the Hyper-V host using a VMIC that is present in Windows Server 2016 GPS hardware, which shows stability and accuracy. This is critical because a 1ms accuracy is needed.

Performance of the Child Domain Client

The child domain client is attached to a Child Domain PDC for sending communication to the Root PDC. Its timing should also be within the 1ms accuracy.

Long Distance Test

Long distance test could involve comparing a single virtual network hop to 6 physical network hops on Windows Server 2016.

Increasing network hops mean increasing latency and extending time differences. The 1ms accuracy may negatively change, which demonstrates a symmetrical network.

Do not forget that every network is different and measurements taken depend on varying environmental factors.

Best Practices for Accurate Timekeeping

1. Solid Source Clock

The machine timing is as good as its source clock. To achieve the 1ms accuracy, a GPS hardware or time appliance should be installed to refer to the master source clock.

The default time.windows.com may not give an accurate or stable local time source. Also, as you move away from the source clock, you are bound to lose time.

2. Hardware GPS Options

The different hardware solutions that offer accurate time depend on GPS antennas. Use of radio and dial-up modem solutions is also accepted. The hardware options connect through PCIe or USB ports.

Different options give varying time accuracy and the final time depends on the environment.

Environmental factors that interfere with accuracy depends on GPS availability, network stability, the PC hardware and network load.

3. Domain and Time Synchronization

Computers in a domain use the domain hierarchy to determine the machine to be used as a source for time synchronization.

Every domain member will look for a machine to sync with and save it as its source. Every domain member will follow a different route that leads to its source time. The PDC in the Forest Root should be the default source clock for all machines in the domain.

Here is a list of how roles in the domain find their original time source.

  • Domain Controller with PDC role

This is the machine with authority on time source for the domain. Most of the time, its issues are accurate and must synchronize with the DC in the parent domain–with exceptional cases where GTIMESERV role is active.

  • Other Domain Controller

This will take the role of a time source for clients and member servers in the domain. A DC synchronizes with the PDC of its domain or any DC in the parent domain.

  • Clients or Member Servers

This type of machine will synchronize with any DC or PDC within its domain or picks any DC or PDC in the parent domain.

When sourcing for the original clock, the scoring system is used to identify the best time source. Scoring takes into account the reliable time source based on the relative location, which happens only once when the time service starts.

To fine-tune time synchronization, add good timeservers in a specific location and avoid redundancy.

Mixed Operating System Environments (Windows 2012 R2 and Windows 2008 R2)

In a pure Windows Server 2016 domain environment, you need to have the best time accuracy.

Deploying a Windows Server 2016 Hyper-V in a Windows 2012 domain will be more beneficial to the guests because of the improvements made in Server 2016.

A Windows Server 2016 PDC delivers accurate time due to the positive changes to its algorithms, which also acts as a credible source.

You may not have an option of replacing the PDC, but you can add a Windows Server 2016 DC with the GTIMESERV flag as one way of upgrading time accurately for the domain.

Windows Server 2016 DC delivers better time to lower clients, but it’s always good to use it as a source NTP time.

As already stated above, clock polling and refresh frequencies are modified in Windows Server 2016.

You can also change the settings manually to match the down-level DCs or make the changes using the group policy.

Versions that came prior to Windows Server 2016 have a problem with keeping accurate time since their systems drift immediately you make a change.

Obtaining samples from accurate NTP sources and conditioning the clock leads to small changes in system clock, ensuring better time keeping on the low-level OS versions.

In some cases involving the guest domain controllers, samples from the Hyper-V TimeSync is capable of disrupting time synchronization. However, for Server 2016, it should no longer be an issue when the guest machines run on Server 2016 Hyper-V hosts.

You can use the following registry keys to disable the Hyper-V TimeSync service from giving samples to w32time:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeTimeProvidersVMICTimeProvider

“Enabled”=dword:00000000

Allow Linux to Use Hyper-V Host Time

For guest machines using Linux and run the Hyper-V, it is normal for clients to use the NTP Daemon for time synchronization against the NTP servers.

If the Linux distribution supports version 4 TimeSync protocol with an enabled TimeSync integration on the guest, then synchronization will take place against the host time. Enabling both methods will lead to inconsistency.

Administrators are advised to synchronize against the host time by disabling the NTP time synchronization by using any of the following methods:

  • Disabling NTP servers in the ntp.conf file
  • Disabling the NTP Daemon

In this particular configuration, the Time Server Parameter is usually the host, and it should poll at a frequency of 5 seconds, which is the same as the Clock Update Frequency.

Exclusive synchronization over NTP demands that you disable the TimeSync integration service in the guest machine.

NOTE: Linux accurate timing support must have a feature supported in the latest upstream Linux Kernels. As at now, it is not available across most Linux distros.

Specify Local Reliable Time Service Using the GTIMESERV

The GTIMESERV allows you to specify one or more domain controllers as the accurate source clocks.

For example, you can use a specific domain controller with a GPS hardware and flag it as GTIMESERV to make sure that your domain references to a clock based on a GPS hardware.

TIMESERV is a Domain Services Flag that indicates whether the machine is authoritative and can be changed if the DC loses connection.

When the connection is lost, the DC returns the “Unknown Stratum” error when you query via the NTP. After several attempts, the DC will log System Event Time Service Event 36.

When configuring a DC as your GTIMESERV, use the following command:

w32tm /config /manualpeerlist:”master_clock1,0x8 master_clock2,0x8” /syncfromflags:manual /reliable:yes /update

If the DC has a GPS hardware, use the following steps to disable the NTP client and enable the NTP server:

reg add HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesw32timeTimeProvidersNtpClient /v Enabled /t REG_DWORD /d 0 /f

reg add HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesw32timeTimeProvidersNtpServer /v Enabled /t REG_DWORD /d 1 /f

Then, restart Windows Time Service

net stop w32time && net start w32time

Finally, tell network hosts that this machine has a reliable time source using this command:

w32tm /config /reliable:yes /update

Confirm the changes, run the following commands, which indicate the results as shown:

w32tm /query /configuration

Value

Expected Setting

AnnounceFlags

5 (Local)

NtpServer

(Local)

DIIName

C:WINDOWSSYSTEM32w32time.DLL (Local)

Enabled

1 (Local)

NtpClient

(Local)

w32tm /query /status /verbose

Value

Expected Setting

Stratum

1 (primary reference – syncd by radio clock)

ReferenceId

0x4C4F434C (source name: “LOCAL”)

Source

Local CMOS Clock

Phrase Offset

0.0000000s

Server Role

576 (Reliable Time Service)

Windows Server 2016 on 3rd party Virtual Platforms

The virtualization of Windows means that the time responsibility defaults to the Hypervisor.

However, new members of the domain need to be synchronized with the Domain Controller for the AD to work effectively. The best that you can do is to disable time virtualization between guests and 3rd party virtual platforms.

Discover the Hierarchy

The chain of time hierarchy to the master clock is dynamic and non-negotiated. You must query the status of a specific machine to get its time source. This analysis helps in troubleshooting issues relating to synchronizations.

If you are ready to troubleshoot, find the time source by using the w32tm command:

w32tm /query /status

The output will be the source. Finding the source is the initial step in time hierarchy.

The next thing to do is to use the source entry and /Stripchart parameter to find the next time source.

w32tm /stripchart /computer:MySourceEntry /packetinfo /samples:1

The command below gives a list of domain controllers found in a specific domain and relays the results that you can use to determine each partner. The command also includes machines with manual configurations.

w32tm /monitor /domain:my_domain

You can use the list to trace the results through the domain and know their hierarchy and time offset at each step.

If you mark the point where time offset increases, you can get to know the cause of incorrect time.

Using Group Policy

Group policy is used to accomplish strict accuracy by making sure clients are assigned specific NTP servers. Clients can control how down-level OS should work when virtualized.

Look at the following list of all possible scenarios and relevant Group Policy settings:

  • Virtualized Domains

To gain control over the Virtualized Domain Controllers in Windows 2012 R2, disable the registry entry corresponding to the virtual domain controllers.

You may not want to disable the PDC entry because in most cases, Hyper-V host delivers a stable time source. The entry to the registry requires that you restart the w32time service after making changes.

[HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32TimeTimeProvidersVMICTimeProvider]

“Enabled”=dword:00000000

  • Accuracy Sensitive Loads

For any workload that is sensitive to time accuracy, ensure that the group machines are set to use the NTP servers and any related time settings like update frequency and polling.

This is a task handled by a domain, but if you want to have more control, target specific machines to point to the master clock

Group Policy Setting

New Value

NtpServer

ClockMasterName,0x8

MinPollInterval

6-64 seconds

MaxPollInterval

6 seconds

UpdateInterval

100 to once per second

EventLogFlags

3 – All special time logging

NOTE: The NtpServer and EventLogFlags are located on the SystemWindows Time ServiceTime Providers, if you follow the Configure Windows NTP Client Settings. The other three are under the SystemWindows Time Service, if you follow the Global Configuration Settings

Remote Accuracy Sensitive Loads Remote

For systems running on the branch domains, such as the Retail and Payment Credit Industry (PCI), Windows will use the current site data and DC Locator to search the local DC, unless you have a manual NTP time source configured.

In such an environment, you need 1 second accuracy with the option of using the w32time services to move the clock backwards.

If you can meet the requirements, use the table below to create a policy.

Group Policy Settings

New Value

MaxAllowedPhaseOffset

1, if more than on second, set clock to correct time.

The MaxAllowedPhaseOffset is a setting you will find under SystemWindows Time Service using global Configuration settings.

Azure and Windows IaaS Consideration

  • Azure Virtual Machine: Active Directory Domain Services

If you have Azure VM running Active Directory Domain Services as part of the existing configuration in a Domain Forest, then the TimeSync (VMIC) should not be running.

Disabling VMIC allows all DCs in both physical and virtual forests to use a single time sync hierarchy.

  • Azure Virtual Machine: Domain –Joined Machine

If you have a host whose domain links to an existing Active Directory Forest, whether virtual or physical, the best you can do is to disable TimeSync for the guest and make sure the W32Time is set to synchronize with the Domain Controller.

  • Azure Virtual Machine: Standalone Workgroup Machine

If your Azure is not part of a domain and it is not a Domain Controller, you can keep the default time configuration and let the VM synchronize with the host.

Windows Applications that Require Accurate Time

Stamp API

Programs or applications that need time accuracy in line with the UTC should use the GetSystemTimePreciseAsFileTime API to get the time as defined by Windows Time Service.

UDP Performance

An application that uses UDP to communicate during network transactions should minimize latency. You have the registry options to use when configuring different ports. Note that any changes to the registry should be restricted to system administrators.

Windows Server 2012 and Windows Server 2008 need a Hotfix to avoid datagram losses.

Update Network Drivers

Some network cards have updates that help improve performance and buffering of UDP packets.

Logging for System Auditors

Time tracing regulation may force you to comply by archiving the w32tm logs, performance monitors, and event logs. Later, these records may be used to confirm your compliance at a specific time in the past.

You can use the following to indicate time accuracy:

  • Clock accuracy using the computed time offset counter
  • Clock source looking for “peer response from” in the w32tm event logs
  • Clock condition status using the w32tm logs to validate the occurrence of “ClockDispl Discipline:*SKEW*TIME*.”

Event Logging

An event log can give you a complete story in the information it stores. If you filter out the Time-Server logs, you will discover the influences that have changed the time. Group policy can affect the events of the logs.

W32time Debug Logging

Use the command utility w32tm to enable audit logs. The logs will show clock updates as well as the source clock.

Restarting the service enables new logging.

Performance Monitor

The Windows Server 2016 Time service counters can collect the logging information that auditor’s need. You can log the data locally or remotely by recording the machine’s Time Offset and Round Trip Delays.

Like any other counter, you can create remote monitors and alerts using the System Center Operations Manager. You can set an alert for any change of accuracy when it happens.

Windows Traceability Example

Using sample log files from the w32tm utility, you can validate two pieces of information where the Windows Time Service conditions the first log file at a given time.

151802 20:18:32.9821765s – ClockDispln Discipline: *SKEW*TIME* – PhCRR:223 CR:156250 UI:100 phcT:65 KPhO:14307

151802 20:18:33.9898460s – ClockDispln Discipline: *SKEW*TIME* – PhCRR:1 CR:156250 UI:100 phcT:64 KPhO:41

151802 20:18:44.1090410s – ClockDispln Discipline: *SKEW*TIME* – PhCRR:1 CR:156250 UI:100 phcT:65 KPhO:38

All the messages that start with “ClockDisplin Discipline” are enough proof that your system is interacting with the system clock via the w32time.

The next step is to find the last report before the time change to get the source computer that is the current reference clock.

Like in the example below, we have the Ipv4 address of 10.197.216.105 as the reference clock. Another reference could point to the computer name or the VMIC provider.

151802 20:18:54.6531515s – Response from peer 10.197.216.105,0×8 (ntp.m|0x8|0.0.0.0:123->10.197.216.105:123), ofs: +00.0012218s

Now that the first section is valid, investigate the log file on the reference time source using the same steps.

This will give you a physical clock such as the GPS or a known time source like the National Institute of Standards and Technology (NIST). If the clock is a GPS hardware, then manufacturer logs may be required.

Network Considerations

The NTP protocol algorithm depends on the network symmetry, making it difficult to predict the type of accuracies needed for certain environments.

You an use the Performance Monitor and new Windows Time Counters for Windows Server 2016 to create baselines.

The Precision Time Protocol (PTP) and the Network Time Protocol (NTP) are the two that you can use to gauge accurate time.

If clients are not part of a domain, Windows use the Simple NTP by default. Clients found within a Windows domain use the secure NTP protocol, also referred to as MS-SNTP, which help in leveraging domain communication, consequently giving an advantage over Authenticated NTP.

Reliable Hardware Clock (RTC)

Windows will not step time unless some conditions are beyond the norm. The implication is that the w32tm changes the frequency at regular intervals while relying on the Clock Update Frequency Settings, which is 1 second on Windows Server 2016.

It will move the frequency if it is behind, and vice versa when it is ahead of time.

This reason explains why you need to have acceptable results during the baseline test. If what you get for the “Computed Time Offset” is not stable, then you may have to verify the status of the firmware.

Troubleshooting Time Accuracy and NTP

The Discovering Hierarchy section gave us an understanding of the source and inaccurate time.

You need to look for time offset to identify the point where the divergence takes place from its NTP Sources. Once you can trace the hierarchy of time, you need to focus on the divergent system to gather more information in determining the issues causing all these inconsistencies.

Here are some tools that you can use:

System event logs

  • Enable logging:

w32tm logs – w32tm /debug /enable /file:C:WindowsTempw32time-test.log /size:10000000 /entries:0-300

w32Time Registry key HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesW32Time

  • Local network interfaces
  • Performance counters
  • W32tm /stripchart /computer:UpstreamClockSource
  • PING UpstreamClockSource (gauging latency and understanding the number of hops to source)

Tacert UpstreamClockSource

Problem

Symptoms

Resolution

Local TSC unstable

Use perfmon-Physical computer- Sync clock stable clock

Update firmware or try an alternative hard to confirm that it does display the same issue

Network latency

W32tm stripchart displays the RoundTripDelay exceeding 10ms. Use Tracert to find where the latency thrives

Locate a nearby source clock for time. Install a source clock on the same domain segment or point to one that is geographically closer. Domain environment needs a client with the GtimerServ role.

Unable to reliably reach the NTP source

W32tm /stripchart gives “request time out”

NTP source unresponsive

NTP Source is not responsive

Check Perfmon counters for NTP client Source Count, NTP server outgoing responses, and NTP Server Incoming Requests. Determine the outcome with your baseline tests results

Use server performance counters to determine change in load or if there is any network congestion

Domain Controller not using the most accurate clock

Changes in topology or a recently added master clock

w32tm /resync /rediscover

Clients Clocks are drifting

Time-Service event 36 in System event log or you see a text log with the following description: “NTP Client Time Source Count” going from 1 to 10

Identify errors in the upstream source and query if it may be experiencing performance issues

Baselining Time

Baseline tests are important because they give you an understanding of the expected performance accuracy of the network.

You can use the output to detect problems on your Windows Server 2016 in the future. The first thing to baseline is the root PDC or any machine with the role of GTIMESRV.

Every PDC in the forest should have a baseline test results. Eventually, you need to pick DCs that are critical and get their baseline results too.

It is important to baseline Windows 2016 and 2012 R2 using the w32tm /stripchart as a comparison tool. If you use two similar machines, you can compare their results and make comprehensive analysis.

Using the performance counters, you can collect all information for at least one week to give you enough references when accounting for various network time issues.

If you have more figures for comparison, you’ll gain enough confidence that your time accuracy is stable.

NTP Server Redundancy

A manual NTP server configuration in a non-domain network means that you should have a good redundancy measure to get better accuracy when other components are also stable.

On the other hand, if your topology does not have a good design and other resources are not stable, it’ll lead to poor accuracy levels. Take caution to limit timeservers’ w32time to 10.

Leap Seconds

The climatic and geological activities on planet earth lead to varying rotation periods. In an ideal scenario, the rotation varies every two years by one second.

When the atomic time grows, there will be a correction of a second up or down called the leap second. When doing the correction, it never exceeds 0.9 seconds. The correction is always announced six months before time.

Before Windows Server 2016, the Microsoft Time Service did not account for the leap seconds and relied on external time service to handle the adjustments.

The changes made to Windows Server 2016, Microsoft is working on a suitable solution to handle the leap second.

Secure Time Seeding

W32time in Windows Server 2016 includes the Secure Time Seeding Feature that determines the approximate current time of the outgoing Secure Sockets Layer Connection (SSL). The value helps in correcting gross errors on the local system clock.

You can decide not to use the Secure Time Seeding feature and use the default configurations, instead.

If you intend to disable the feature, use the following steps:

  • Set the UtilizeSSLTimeData registry value to 0 using the command below:

reg add KEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesw32timeConfig /v UtilizeSslTimeData /t REG_DWORD /d 0 /f

  • If the machine does not detect any changes and does not ask for a reboot, notify the W32time service about the changes. This will stop enforcing time monitoring based on data coming from the SSL connections.

W32tm.exe /config /update

  • Rebooting the machine activates the settings immediately and directs the machine to stop collecting data from SSL connections.

For the above setting to be effective on the entire domain, set the UtilizeSSLTimeData value in W32time using the Group Policy Setting to 0, and make the setting public.

The moment the setting is picked by a Group Policy Client, the W32time service gets the notification and stops enforcing and monitoring SSL time data.

If the domain has some portable laptops or tablets, you can exclude them from the policy change because when they lose battery power, they will need to re-access the Secure Time Seeding feature to acquire the current time.

Conclusion

The latest developments in the world of Microsoft Windows Server 2016 means that you can now get the most accurate time on your network once you observe some conditions.

The Windows Time Service (W32Time) main work is to give your machine time, regardless of whether it is a standalone or part of a network environment.

The primary use of time in a Windows Server 2016 environment is to make sure that there is enough security for Kerberos authentication.

The W32Time makes it almost impossible to have replay attacks in an Active Directory or when running Virtual Machines on Hyper-V hosts.

Понравилась статья? Поделить с друзьями:
  • Настроить панель задач в windows 10 для всех пользователей
  • Настроенный прокси сервер не отвечает windows 10 как исправить
  • Настроить веб сервер на компьютере windows 10
  • Настроить панель задач в windows 10 без активации
  • Настроенные политики обновления windows 10 как изменить