- Ntp сервер для windows server 2012
- Настройка NTP в Windows Server 2012
- Сброс настроек NTP
- Команды установки NTP в обычном случае
- Выбор ntp-сервера
- Протокол UDP для NTP и блокировка файрволом
- Проверка правильности работы ntp
- Configuring NTP on Windows Server 2012
- Which NTP-server to use? Or several?
- Don’t forget your firewall
- More info and debug logging
- Force a resync
- 16 Comments
- Настройка доменного сервера времени NTP в Windows Server 2012R2/2016 через GPO
Ntp сервер для windows server 2012
Настройка NTP в Windows Server 2012
Настройка времени в серверных операционных системах Windows с помощью протокола NTP является критичной для многих служб. Без правильного настроенного времени, а точнее при рассогласовании часов на сервере и рабочих станциях не могут правильно работать многие протоколы Active Directory и сервисы синхронизации. Установка и поддержка часов с помощью NTP является простой задачей, связанной иногда, однако, с некоторыми сложностями, которые мы попытаемся рассмотреть в этой статье.
Для примера будем использовать не самую свежую систему — Windows Server 2012. Она является наиболее распространенной и, в то же время, для многих других систем, включая Windows Server 2008, Windows Server 2016 применимы аналогичные команды и правила. Следует отметить, что описание касается настройки окружения с единственным главным контроллером PDC. Более сложные варианты не рассматриваются.
Сброс настроек NTP
Для того, чтобы перевести службу NTP в «дефолтное» состояние, необходимо выполнить следующие команды:
Stop-Service w32time w32tm /unregister w32tm /register
В данном случае они останавливают сервис, разрегистрируют сервис и регистрируют его в системе заново. Следует выполнять эти команды только в случае существенной необходимости. Как правило, нужды в них нет — NTP настраивается, если учтены другие обстоятельства системы.
Команды установки NTP в обычном случае
Для того, чтобы настроить протокол сетевого времени на контроллере Windows Server, прежде всего необходимо отключить синхронизацию посредством Hyper-V, если контроллер виртуализирован с помощью этой технологии. Для этого нужно зайти в настройки и снять галочку с пункта Time Synchronization в разделе Management -> Integration Services
Для тех, кто не использует Hyper-V, предыдущий шаг можно опустить.
Далее, запустить Power-Shell и ввести команды:
w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL Stop-Service w32time Start-Service w32time
На этом установка в качестве основного ntp-сервера одного из pool.ntp.org закончена.
Выбор ntp-сервера
Однако нет жесткой необходимости использовать именно этот сервер. Для тех, кто находится в интранете, для тех, у кого есть предпочтения по геолокации или другим параметрам, можно указать другой сервер. Или даже список в кавычках, разделенный пробелами:
w32tm /config /manualpeerlist:»0.de.pool.ntp.org 1.de.pool.ntp.org» /syncfromflags:MANUAL
Протокол UDP для NTP и блокировка файрволом
Протокол времени использует для своей связи порт UDP с номером 123 в стандартной конфигурации. Необходимо следить за тем, чтобы файрвол не блокировал этот порт. В случае, если блокировка происходит, в логах ntp будет масса информации о том, что соединение невозможно:
Log Name: System
Source: Microsoft-Windows-Time-Service
Event ID: 47
Level: Warning
Description: Time Provider NtpClient: No valid response has been received from manually configured peer pool.ntp.org after 8 attempts to contact it. This peer will be discarded as a time source and NtpClient will attempt to discover a new peer with this DNS name. The error was: The peer is unreachable.
Для того, чтобы убедиться, что проблема именно в этом, можно включить вывод дополнительной отладочной информации. Настраиваем логи Windows Server таким образом, чтобы в них писалась вся необходимая информация, но они не росли больше, чем 20 мегабайт:
w32tm /debug /enable /file:C:\tmp\ntp.log /size:20971520 /entries:0-300
Следите за тем, чтобы на диске присутствовал каталог C:\tmp куда будут записаны логи.
После того, как ошибка будет отловлена, вывод дополнительной отладочной информации можно будет отключить:
w32tm /debug /disable
Блокировка ntp файрволом отлавливается по фразе в отладке:
— Logging error: NtpClient has been configured to acquire time from one or more time sources, however none of the sources are currently accessible and no attempt to contact a source will be made for 1 minutes. NTPCLIENT HAS NO SOURCE OF ACCURATE TIME.
В этом случае (да, в общем, сразу с целью проверки) необходимо проверить правило в файрволе
И, в случае необходимости, поменять правило или добавить его.
Проверка правильности работы ntp
Чтобы проверить — все ли работает правильно, можно запустить синхронизацию вручную:
Если все прошло успешно, получите сообщение:
Sending resync command to local computer
The command completed successfully.
Если есть проблемы — сообщение:
The computer did not resync because no time data was available.
Во втором случае необходимо проверить все сначала: файрвол, правильность заданных серверов (не ошиблись ли в имени). Если что — информацию о сбросе настроек мы уже приводили.
Configuring NTP on Windows Server 2012
This article explains how to configure NTP on Windows Server 2012. If you’re looking for Windows Server 2008 R2, see my article here. Remember, that in a domain environment, time synchronization is taken care of but you should configure the PDC Emulator of a domain to sync externally since that is the server which decides what time it is!
Are you looking how to configure NTP using GPO, please read my article on it here.
This is all you need if you want to keep it simple. Run using PowerShell as admin:
w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:MANUAL
Stop-Service w32time
Start-Service w32time
If the machine is a VM inside Hyper-V, you have to disable time sync. Open VM settings -> Management -> Integration Services and uncheck Time Synchronization.
That should be it! Want to know more? Doesn’t work? Have you screwed up the config and want to start from the beginning? Keep on reading…
W32tm is the command to use. Sure, there are articles out there mentioning “net time”, but you should not use that. Some other also mentions editing the registry directly, but as Microsoft mentions in the article: It is recommended that you do not directly edit the registry unless there is no other alternative. But if you really want to check the registry, it’s here: HKLM\System\CurrentControlSet\Services\W32Time.
Which NTP-server to use? Or several?
The pool.ntp.org is a round-robin of random selected NTP servers. As they say “This is usually good enough for end-users“. But you might want to add several NTP-servers yourself for redundancy?
w32tm /config /manualpeerlist:”0.pool.ntp.org 1.pool.ntp.org” /syncfromflags:MANUAL
Just keep adding them with a space in between them. Yes, I know some sites say you should separate them using comma but that doesn’t work. Also, I’ve experienced issues that it configures correctly, but still after restarting the service, it doesn’t work. I just needed to do the configuration again, and try once more. Also, remember that cut’n’paste from the web can sometimes screw up the ” character so write it manually instead of cut’n’paste to be sure.
Don’t forget your firewall
If you got a firewall between your host and the Internet, it might drop udp/123 which is the NTP protocol. This is how it looked in my Cisco ASA FW:
So I created a rule to allow it and after that it worked.
More info and debug logging
The following commands are quite useful which lists the current source, when it last sync’ed etc.
Eventually, when the server can’t get time from the NTP server it will add an event to the event log:
Log Name: System
Source: Microsoft-Windows-Time-Service
Event ID: 47
Level: Warning
Description: Time Provider NtpClient: No valid response has been received from manually configured peer pool.ntp.org after 8 attempts to contact it. This peer will be discarded as a time source and NtpClient will attempt to discover a new peer with this DNS name. The error was: The peer is unreachable.
Otherwise, when it’s working, you will get:
Log Name: System
Source: Microsoft-Windows-Time-Service
Event ID: 35
Level: Information
Description: The time service is now synchronizing the system time with the time source pool.ntp.org (ntp.m|0x0|0.0.0.0:123->85.10.240.253:123).
You still getting problems? You can easily turn on debugging to a logfile which in this case is limited t0 10 MB and include ALL debug entries.
w32tm /debug /enable /file:C:\Temp\w32tmdebug.log /size:10485760 /entries:0-300
Turn it off again with:
Expect a lot of info in this debug log. For me, when it worked, the following entries showed it was working:
– Reachability: peer pool.ntp.org (ntp.m|0x0|0.0.0.0:123->129.70.132.35:123) is reachable.
– Logging information: NtpClient is currently receiving valid time data from pool.ntp.org (ntp.m|0x0|0.0.0.0:123->129.70.132.35:123).
But when I had my firewall blocking the packets, I would get the following. Don’t trust this too much though, since I did get this when I allowed it in the firewall also, but when it was blocked, I did not get the entries above.
– Logging error: NtpClient has been configured to acquire time from one or more time sources, however none of the sources are currently accessible and no attempt to contact a source will be made for 1 minutes. NTPCLIENT HAS NO SOURCE OF ACCURATE TIME.
Force a resync
If you want to force the client to resync, run:
w32tm /resync
Sending resync command to local computer
The command completed successfully.
If you get the following error, the computer can’t reach the NTP-server(s).
The computer did not resync because no time data was available.
Start from scratch
If you completely screwed up the config, you can always do the following command and it will completely erase and add a default W32time configuration:
Stop-Service w32time
w32tm /unregister
w32tm /register
When doing the unregister I got the following error for some reason, but it seems like it worked anyway.
The following error occurred: Access is denied. (0x80070005)
Sometimes when doing the /register, I would get the following. This usually solved by waiting for a while. I would suggest you stop the service before doing /unregister. Otherwise, a reboot would probably solve most problems.
The following error occurred: The specified service has been marked for deletion. (0x80070430)
If you miss any important information, let me know and I’ll add it.
16 Comments
there are about 1,000 forum threads and websites about automatically syncing the time in Windows Server using NET TIME and none of them worked on W2K12…I’m reluctant to change any registry settings because…for gawd’s sakes it’s 2013 and I don’t think MS is that asinine to have something simple like time syncing to be only configurable by opening the registry editor…and then i found this page…and it solved the problem for me. thank you! hopefully this lone comment somehow bump you up in the Google search result page.
Works great on my W2k12 Datacenter Edition.
Worked perfectly for me on Server 2012 as DC inside a VM. I did it, then I made one change and did it again…. worked both times. The only change was the peer list from pool.ntp.org -to- us.pool.ntp.org
Just moved over to Server 2012 and you explanations worked great and really helped my understanding of NTP. Thanks.
As mentioned earlier- excellent solution.
Does this NTP config work for non-MS devices like cisco switches?
Best article about time servers! I’m glad that it comes as first page on google 🙂 Had issues with VM not syncing and this guide cleared everything!
Yes, it should. I often create a CNAME in DNS like “ntp.domain.local” and point that to a good DC and configure all network devices to sync against that CNAME.
Many thanks. I have to sort my AD based time sync every few years, and always forget how. Your article is a good summary on completely sorting it, and reflects on some of the pitfuls I’ve also hit before. Added to my favourites! Many thanks 🙂
Works fine, much easier than what described elsewhere.
More information can be found with WIN32TM /?
For me, the solution for a dysfunctional NTP setting on a domain member server was the /register as described above.
Yes it’s working with cisco devices like switches, Routers & Firewalls.
Microsoft makes it seem as if I HAVE to edit the registry in order to make my DC sync against its internal clock rather than syncing against an NTP server on the WAN. Any suggestions on this?
Great article, thank you for posting it up.
I also found the following command useful to confirm the settings entered
w32tm /query /configuration
My configuration command for my PDC emulator looked like this
w32tm /config /reliable:YES /syncfromflags:MANUAL /manualpeerlist:”ntp.maths.tcd.ie 0.ie.pool.ntp.org 1.ie.pool.ntp.org 2.ie.pool.ntp.org 3.ie.pool.ntp.org”
I also ran the update option which causes changes to take effect.
w32tm /config /update
Awesome article. However, I did have to “run as administrator” for my Powershell for these commands to work. I entered the commands properly and then added three pool servers along with stopping and restarting the service. It worked like a charm. thank you so much for the great article.
The best article about NTP I have found so far. A lot of 2018 articles telling to mess with the registry. This one is 6 years old but it still works like a charm!
Настройка доменного сервера времени NTP в Windows Server 2012R2/2016 через GPO
Сразу оговорим важные вещи:
- Работа по настройке точного времени на участниках домена через GPO часто делят на 2 части: настройки сервера/-ов и настройки клиентских машин.
- Настройку клиентских машин на получение точного времени некоторые администраторы делают через политики (в частности правкой политики Default Domain Policy), но я так не делаю, ибо все входящие в домен машины «автоматически узнают», что сервер времени для них — контроллер домена. Клиентские машины я только проверяю на правильное соединение с нашим сервером NTP.
Для начала определяю какой контроллер домена Windows Server 201x имеет роль PDC (если я этого не знаю )) ), если контроллеров домена несколько, как в моём случае. Для этого на любом компьютере или сервере, входящем в домен! , запускаю командную строку от имени Администратора:
Не будем обсуждать распределение ролей между контролерами, в тестовом домене у меня все роли принадлежат одному контроллеру, и перейдя на сервер ADDC01 (в моём случае) — начнем его настройку.
1. Для начала создадим WMI-фильтр, который будет применять нашу новую политику только к серверу с ролью эмулятора PDC
2. Создадим новую групповую политику и применим к ней фильтр WMI, созданный нами выше.
Нас интересует путь: Computer Configuration — Administrative Templates — System — Windows Time Service — Time Providers (Конфигурация компьютера -> Политики -> Административные шаблоны -> Система -> Служба времени Windows -> Поставщики времени)
Здесь нам нужно включить три политики:
Enable Windows NTP Client: Enabled
Enable Windows NTP Server: Enabled
Configure Windows NTP Client: Enabled
Пункт Configure Windows NTP client имеет следующие настройки:
Я использовал следующий список серверов точного времени:
3. Создав политику не забываем применить к ней фильтр WMI:
4. Пришло время обновить политики на сервере времени и синхронизировать время. Запускаем командную строку от имени Администратора.