Donate with
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC
The goal: Automatically synchronize the time of a Microsoft Windows 2008 (R2) server via NTP with one or more online NTP servers.
This CMD batchfile activate_win32time_service_for_windows_servers.cmd (right click and save as a local file with the extension ‘.cmd’ -> Execute as Administrator) automatically configures the Windows (Server 2008 R2) NTP service to use a list of online NTP servers for synchronizing its local time.
This is done by executing the following lines of code on a command shell:
@echo off echo This script activates the automatic Timesync via NTP in Windows Server Systems echo. w32tm /config /update /manualpeerlist:"0.pool.ntp.org,0x8 1.pool.ntp.org,0x8 2.pool.ntp.org,0x8 3.pool.ntp.org,0x8" /syncfromflags:MANUAL net stop w32time net start w32time w32tm /resync
In order to configure an Windows 2008 R2 Server you will need to make a number of changes to the registry. This tutorial will show you both the settings for configuring the NTP Server in addition to the client settings.
Table of Contents
NOTES
It is worth noting that this example is based on the below,
- A Windows 2008 R2 Server acting as the NTP Server
- A Windows 2008 R2 Server acting as the NTP client for which it will source its time from the above server.
- This configuration is not based upon using a Windows Domain.
NTP SERVER
SERVER SETTINGS
1. Enable the NTP Server
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer]"
"Enabled"=dword:00000001
CLIENT SETTINGS
1. Enable NTP Client and set polling interval.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient]"
"Enabled"=dword:00000001
"SpecialPollInterval"="300"
2. Configure the NTP Time Source, period and frequency
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters]
"NtpServer"="[NTP SERVER IP],0x1"
"Type"="NTP"
"Period"="freq"
NTP CLIENT
CLIENT SETTINGS
1. Enable NTP Client and set polling interval.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient]"
"Enabled"=dword:00000001
"SpecialPollInterval"="300"
2. Configure the NTP Time Source, period and frequency
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters]
"NtpServer"="[NTP SERVER IP],0x1"
"Type"="NTP"
"Period"="freq"
ADDITIONAL
STARTUP
By default the w32tm service will not automatically start if your Windows machine is not on a domain. To ensure that the service starts automatically run the following command :
sc triggerinfo w32time start/networkon stop/networkoff
TROUBLESHOOTING
To confirm that your clients are correctly peering with your time source run the following command.
w32tm /query /peers
“NtpServer”=”[NTP SERVER IP],0x1”
- Author
- Recent Posts
Rick Donato is a Network Automation Architect/Evangelist and the founder of Packet Coders.
Want to become a Windows expert?
Here is our hand-picked selection of the best courses you can find online:
Windows Server 2019 Administration course
Windows 10 Troubleshooting course
and our recommended certification practice exams:
AlphaPrep Practice Tests — Free Trial
Skip to content
I grabbed this from the following link.
It explains how to setup Windows 2008R2 to sync with servers from pool.ntp.org
Time synchronization is an important aspect for all computers on the network. By default, the clients computers get their time from a Domain Controller and the Domain Controller gets his time from the domain’s PDC Operation Master. Therefore the PDC must synchronize his time from an external source. I usually use the servers listed at the NTP Pool Project website. Before you begin, don’t forget to open the default UDP 123 port (in- and outbound) on your (corporate) firewall.
1. First, locate your PDC Server. Open the command prompt and type: C:\>netdom /query fsmo
2. Log in to your PDC Server and open the command prompt.
3. Stop the W32Time service: C:\>net stop w32time
4. Configure the external time sources, type: C:\> w32tm /config /syncfromflags:manual /manualpeerlist:”0.pool.ntp.org, 1.pool.ntp.org, 2.pool.ntp.org”
5. Make your PDC a reliable time source for the clients. Type: C:\>w32tm /config /reliable:yes
6. Start the w32time service: C:\>net start w32time
7. The windows time service should begin synchronizing the time. You can check the external NTP servers in the time configuration by typing: C:\>w32tm /query /configuration
8. Check the Event Viewer for any errors.
Tested on Windows Server 2008 R2 (Build 7600).
В крупных конторах просто необходимо, чтоб на всех компьютерах в сети время шло точно. И когда у нас есть Active Directory, то настроить синхронизацию времени очень просто.
Заходим на контроллер домена. Потом: Пуск → Все программы → Администрирование → Управление групповой политикой. Откроется вот такое окно:
Находим в нём политику под названием Default Domain Policy. Сразу оговорюсь, что обычно, рекомендуется создавать новую групповую политику и вносить изменения уже в неё, а умолчательную не трогать. Но я буду вносить изменения в умолчательную политику, чтобы статья была чуток покороче Итак, жмём правой клавишей на Default Domain Policy и выбираем «изменить». Откроется оснастка редактора доменной групповой политики. В ней идём: Конфигурация компьютера → Политики → Административные шаблоны → Система → Служба времени Windows → Поставщики времени.
И в этой папке настраиваем политики вот таким образом: политику «Включить NTP-клиент Windows» ставим в состояние «включить». А политику «Настроить NTP-клиент Windows» настраиваем вот так:
где 172.16.0.107 – адрес контроллера, на котором сейчас и проводим эти настройки.
Всё, теперь закрываем эту оснастку (с политикой Default Domain Policy) и снова переходим в «Управление групповой политикой».
Сейчас нам нужна уже политика не домена, а политика самого контроллера домена Default Domain Controllers Policy. Вот она где находится:
На ней также жмём правой клавишей и выбираем «изменить». Откроется оснастка. В ней также перейдём на Конфигурация компьютера → Политики → Административные шаблоны → Система → Служба времени Windows → Поставщики времени. И здесь уже отредактируем все три существующие политики:
Политику «Включить NTP-клиент Windows» ставим в состояние «включить».
Политику «Включить NTP-сервер Windows» также ставим в состояние «включить».
А политику «Настроить NTP-клиент Windows» настраиваем вот так:
На этом всё, закрываем редактор групповых политик. После всех этих манипуляций, система будет работать следующим образом: контроллер домена синхронизирует время с NTP-сервером Microsoft и, в тоже время, сам является NTP-сервером для клиентских машин. Т.о., в сети на всех машинах всегда будет идти точное время.
Кстати, чтобы пользователи не могли отключить службу времени у себя, нужно это всё дополнить ещё кое-чем. Снова открываем для редактирования политику Default Domain Policy. И переходим на: Конфигурация компьютера → Политики → Конфигурация Windows → Параметры безопасности → Системные службы. И в списке этих самых системных служб находим службу времени windows:
Настраиваем её вот так:
А также, жмём кнопку «Изменить параметры» и там выбираем, чтоб только доменные администраторы могли эту службу запускать и останавливать:
Да, и ещё чуть не забыл: чтоб контроллер домена мог достучаться до NTP-сервера Microsoft, ему на шлюзе нужно во внеху открыть порт 123. По этому порту работает NTP. Ну, и если на самом контроллере домена тоже стоит какой-нибудь фаервол, то он тоже должен разрешать выходить во внеху по порту 123, а также должен разрешать и из внехи (из локальной сети в данном случае) подключения к контроллеру домена по порту 123, чтоб рабочие станции синхронизировали с ним время.
Донаты принимаются на кошельки:
Yoomoney:
4100118091867315
Карта Т-Банк (бывший Тиньков):
2200 7017 2612 2077
Карта Альфа-Банк:
2200 1539 1357 2013
There are so many different ways and articles out there on how to configure NTP in Windows and every time I had to look it up. So i decided to write my own article for my own reference for the setup in my lab so I don’t have to Google it myself next time 🙂
This article is for Windows 2008 R2. If you’re looking for Windows 2012, see this article… Are you looking how to configure NTP using GPO, please read my article on it here.
First, the basics. This is all you need if you want to keep it simple:
w32tm /config /manualpeerlist:pool.ntp.org,0x8 /syncfromflags:MANUAL
net stop w32time
net start 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. [Thanks Todd].
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.
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:"ntp1.sp.se ntp2.sp.se",0x8 /syncfromflags:MANUAL
Just keep adding them with a space in between them.
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.
w32tm /query /status
Eventually, when the server can’t get time from the NTP server it will add an event tto 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,0x8 (ntp.m|0x8|0.0.0.0:123->192.121.13.5: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:
w32tm /debug /disable
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,0x8 (ntp.m|0x8|0.0.0.0:123->79.142.244.39:123) is reachable.
– Logging information: NtpClient is currently receiving valid time data from pool.ntp.org,0x8 (ntp.m|0x8|0.0.0.0:123->79.142.244.39: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:
C:\Windows\system32>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:
net stop 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. 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.
0x8 say what?
You might have noticed the 0x8 flag above. What does it mean? KB875424 mention:
0x01 - use special poll interval SpecialInterval 0x02 - UseAsFallbackOnly 0x04 - send request as SymmetricActive mode 0x08 - send request as Client mode
And the Directory Services Team mention some more reading here.