audministrator
Windows Server 2016–Sync Time Server using (S)NTP
How to sync the time to a public time server using NTP
You need to use the w32tm command.
First check the current settings :
What about the 0x1 parameter ?
- 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 :
This is the configuration :
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: ]
[/computers: [, [, …]]]
[/threads: ] [/ipprotocol: ] [/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
Convert a NT system time, in (10^-7)s intervals from 0h 1-Jan 1601,
into a readable format.
w32tm /ntpte
Convert an NTP time, in (2^-32)s intervals from 0h 1-Jan 1900, into
a readable format.
w32tm /resync [/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 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: [/period: ]
[/dataonly] [/samples: ] [/packetinfo] [/ipprotocol: ]
Display a strip chart of the offset between this computer and
another computer.
computer: – the computer to measure the offset against.
period: – the time between samples, in seconds. The
default is 2s
dataonly – display only the data, no graphics.
samples: – collect 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: ] [/update]
[/manualpeerlist:
] [/syncfromflags: ]
[/LocalClockDispersion: ]
[/reliable:(YES|NO)]
[/largephaseoffset: ]
computer: – adjusts the configuration of . 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:
– sets the manual peer list to
,
which is a space-delimited list of DNS and/or IP addresses.
When specifying multiple peers, this switch must be enclosed in
quotes.
syncfromflags: – sets what sources the NTP client should
sync from. 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: – 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: – 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: ] [/computer: ]
Display the values associated with a given registry key.
The default key is HKLM\System\CurrentControlSet\Services\W32Time
(the root key for the time service).
subkey: – displays the values associated with subkey
of the default key.
computer: – queries registry settings for computer .
w32tm /query [/computer: ]
[/verbose]
Display a computer’s windows time service information.
computer: – query the information of . 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 [/truncate]>>
Enable or disable local computer windows time service private log.
disable: disable the private log.
enable: enable the private log.
file: – specify the absolute filename.
size: – specify the maximum size for circular logging.
entries: – 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.
Точное время в Windows Server 2016 Accurate Time for Windows Server 2016
Применяется к: Windows Server 2016, Windows Server 2012 R2, Windows Server 2012, Windows 10 или более поздних версий Applies to: Windows Server 2016, Windows Server 2012 R2, Windows Server 2012, Windows 10 or later
Служба времени Windows — это компонент, использующий модель подключаемых модулей для клиентских и серверных поставщиков синхронизации времени. The Windows Time service is a component that uses a plug-in model for client and server time synchronization providers. В Windows есть два встроенных клиентских поставщика и доступны подключаемые модули сторонних поставщиков. There are two built-in client providers on Windows, and there are third-party plug-ins available. Один поставщик использует протокол NTP (RFC 1305) или MS-NTP для синхронизации локального системного времени с эталонным сервером, совместимым с этими протоколами. One provider uses NTP (RFC 1305) or MS-NTP to synchronize the local system time to an NTP and/or MS-NTP compliant reference server. Другой поставщик предназначен для Hyper-V и синхронизирует виртуальные машины с узлом Hyper-V. The other provider is for Hyper-V and synchronizes virtual machines (VM) to the Hyper-V host. Если есть несколько поставщиков, Windows выберет наилучшего поставщика, оценивая стратовый уровень, корневую задержку, корневую дисперсию, а затем смещение времени. When multiple providers exist, Windows will pick the best provider using stratum level first, followed by root delay, root dispersion, and finally time offset.
Краткий обзор службы времени Windows см. в этом видео. For a quick overview of Windows Time service, take a look at this high-level overview video.
В этом разделе мы обсудим темы по мере их влияния на точность времени: In this topic, we discuss . these topics as they relate to enabling accurate time:
- Улучшения Improvements
- Измерения Measurements
- Советы и рекомендации Best Practices
Дополнение, на которое ссылается статья о точном времени в Windows 2016, можно скачать здесь. An addendum referenced by the Windows 2016 Accurate Time article can be downloaded here. В этом документе содержатся дополнительные сведения о методологиях тестирования и измерения. This document provides more details about our testing and measurement methodologies.
Модель подключаемого модуля поставщика времени Windows описана в документации в TechNet. The windows time provider plugin model is documented on TechNet.
Иерархия доменов Domain Hierarchy
Доменная и автономная конфигурации работают по-разному. Domain and Standalone configurations work differently.
Участники домена используют безопасный протокол NTP для проверки подлинности, обеспечивающий безопасность и подлинность ссылки времени. Domain members use a secure NTP protocol, which uses authentication to ensure the security and authenticity of the time reference. Участники домена синхронизируются с главными часами, определенными иерархией доменов и системой оценки. Domain members synchronize with a master clock determined by the domain hierarchy and a scoring system. В домене существует иерархический уровень страт времени, где каждый контроллер домена указывает на родительский контроллер домена с более точной стратой времени. In a domain, there is a hierarchical layer of time strata, whereby each DC points to a parent DC with a more accurate time stratum. Иерархия разрешается в основной контроллер домена, контроллер домена в корневом лесу или контроллер домена с меткой домена GTIMESERV, которая обозначает лучший сервер времени для домена. The hierarchy resolves to the PDC or a DC in the root forest, or a DC with the GTIMESERV domain flag, which denotes a Good Time Server for the domain. См. раздел «Указание надежной локальной службы времени с помощью GTIMESERV» ниже. See the [Specify a Local Reliable Time Service Using GTIMESERV section below.
По умолчанию автономные компьютеры настроены использовать time.windows.com. Standalone machines are configured to use time.windows.com by default. Это имя разрешается DNS-сервером, который должен указывать на ресурс, принадлежащий корпорации Майкрософт. This name is resolved by your DNS Server, which should point to a Microsoft owned resource. Все удаленно размещенные ссылки времени могут создавать сетевые сбои, препятствующие синхронизации. Like all remotely located time references, network outages, may prevent synchronization. Нагрузка сетевого трафика и асимметричные сетевые пути могут уменьшить точность синхронизации времени. Network traffic loads and asymmetrical network paths may reduce the accuracy of the time synchronization. Если вам требуется точность времени до 1 мс, удаленные источники времени будут неэффективны. For 1 ms accuracy, you can’t depend on a remote time sources.
При работе в гостевом компьютере вы можете столкнуться с различным поведением домена или автономной среды, так как у гостевых машин Hyper-V будут по крайней мере два поставщика времени Windows на выбор — время узла и NTP. Since Hyper-V guests will have at least two Windows Time providers to choose from, the host time and NTP, you might see different behaviors with either Domain or Standalone when running as a guest.
Дополнительные сведения об иерархии доменов и системе оценки см. в записи блога, посвященной службе времени Windows. For more information about the domain hierarchy and scoring system, see the «What is Windows Time Service?» . blog post.
Страта — это концепция, используемая в поставщиках NTP и Hyper-V, и ее значение указывает расположение часов в иерархии. Stratum is a concept used in both the NTP and Hyper-V providers, and its value indicates the clocks location in the hierarchy. Страта 1 резервируется для часов самого высокого уровня, а Страта 0 — для оборудования, время которого считается точным с минимальной или отсутствующей задержкой, связанной с ним. Stratum 1 is reserved for the highest-level clock, and stratum 0 is reserved for the hardware assumed to be accurate and has little or no delay associated with it. Страта 2 обращается к серверам страты 1, страта 3 — к страте 2 и т. д. Stratum 2 talk to stratum 1 servers, stratum 3 to stratum 2 and so on. Хотя страты более низкого уровня часто указывают более точное время, случаются несоответствия. While a lower stratum often indicates a more accurate clock, it is possible to find discrepancies. Кроме того, служба W32Time принимает только время из страты 15 или ниже. Also, W32time only accepts time from stratum 15 or below. Чтобы просмотреть страту клиента, используйте w32tm /query /status. To see the stratum of a client, use w32tm /query /status.
Критические факторы для определения точного времени Critical Factors for Accurate Time
Во всех случаях для определения точного времени есть три важных фактора: In every case for accurate time, there are three critical factors:
- Физический источник времени — исходные часы в домене должны быть стабильными и точными. Solid Source Clock — The source clock in your domain needs to be stable and accurate. Обычно это означает установку устройства GPS или указание на источник страты 1 с учетом страты 3. This usually means installing a GPS device or pointing to a Stratum 1 source, taking #3 into account. Аналогия такова: если у вас есть две лодки в воде и вы пытаетесь измерить высоту одной по сравнению с другой, точность будет правдивой, если исходная лодка очень стабильна и не движется. The analogy goes, if you have two boats on the water, and you are trying to measure the altitude of one compared to the other, your accuracy is best if the source boat is very stable and not moving. То же самое касается времени. Если исходные часы нестабильны, то влияние распространится на всю цепь синхронизации времени, усиливаясь на каждом этапе. The same goes for time, and if your source clock isn’t stable, then the entire chain of synchronized clocks is affected and magnified at each stage. Источник времени должен быть доступен, так как нарушения соединения могут помешать синхронизации времени. It also must be accessible because disruptions in the connection will interfere with time synchronization. И наконец, источник должен быть безопасным. And finally, it must be secure. Если источник ссылки времени обслуживается неправильно или им управляет потенциально вредоносная сторона, домен может подвергаться атакам на основе времени. If the time reference is not properly maintained, or operated by a potentially malicious party, you could expose your domain to time based attacks.
- Стабильные клиентские часы — часы, которые гарантируют, что естественное смещение осциллятора не будет критичным. Stable client clock — A stable client clocks assures that the natural drift of the oscillator is containable. NTP использует несколько выборок, возможно из нескольких серверов NTP, для настройки и согласования часов в ваших локальных компьютерах. NTP uses multiple samples from potentially multiple NTP servers to condition and discipline your local computers clock. Это не шаг изменения времени, а скорее замедление или ускорение местных часов, что позволяет гарантировать точность времени и обеспечить точность среди NTP-запросов. It does not step the time changes, but rather slows or speeds up the local clock so that you approach the accurate time quickly and stay accurate between NTP requests. Тем не менее, если осциллятор часов клиентского компьютера нестабилен, то могут возникнуть дополнительные отклонения между настройками и алгоритмы, используемые Windows для настройки часов, не будут работать точно. However, if the client computer clock’s oscillator is not stable, then more fluctuations in between adjustments can occur and the algorithms Windows uses to condition the clock don’t work accurately. В некоторых случаях для обеспечения точности времени могут потребоваться обновления встроенного ПО. In some cases, firmware updates might be needed for accurate time.
- Симметричное NTP-подключение — очень важно, чтобы подключение по протоколу NTP было симметричным. Symmetrical NTP communication — It is critical that the connection for NTP communication is symmetrical. NTP использует вычисления для корректировки времени, которые предполагают, что сетевой путь симметричен. NTP uses calculations to adjust the time that assume the network path is symmetrical. Если путь, по которому пакет NTP передается на сервер, возвращается за другой период времени, это повлияет на точность. If the path the NTP packet takes going to the server takes a different amount of time to return, the accuracy is affected. Например, путь может измениться из-за изменений в топологии сети или пакетов, направляемых через устройства с разными скоростями интерфейсов. For example, the path could change due to changes in network topology, or packets being routed through devices that have different interface speeds.
Для устройств с питанием от аккумулятора, как мобильных, так и переносимых, необходимо учитывать разные стратегии. For battery powered devices, both mobile and portable, you must consider different strategies. Мы советуем поддерживать точность времени, обеспечивая корректировку часов единожды в секунду, что соотносится с частотой обновления часов. As per our recommendation, keeping accurate time requires the clock to be disciplined once a second, which correlates to the Clock Update Frequency. Эти настройки будут требовать большего потребления энергии аккумулятора, чем ожидалось, и могут отрицательно влиять на режимы энергосбережения, доступные в Windows для таких устройств. These settings will consume more battery power than expected and can interfere with power saving modes available in Windows for such devices. В устройствах с питанием от аккумулятора также есть определенные режимы энергопитания, в которых останавливается работа всех приложений, что препятствует способности W32Time корректировать часы и поддерживать точность времени. Battery powered devices also have certain power modes which stop all applications from running, which interferes with W32time’s ability to discipline the clock and maintain accurate time. Кроме того, часы в мобильных устройствах могут быть изначально неточными. Additionally, clocks in mobile devices may not be very accurate to begin with. Условия окружающей среды влияют на точность часов, и мобильное устройство может попадать из одних условий в другие, что может помешать его способности поддерживать точность времени. Ambient environmental conditions affect clock accuracy and a mobile device can move from one ambient condition to the next which may interfere with its ability to keep time accurately. Поэтому мы не советуем выбирать для мобильных устройств с питанием от аккумулятора параметры высокой точности. Therefore, Microsoft does not recommend that you set up battery powered portable devices with high accuracy settings.
Почему важно время? Why is time important?
Есть множество различных причин, по которым может потребоваться точное время. There are many different reasons you might need accurate time. Типичным случаем для Windows является Kerberos, где для работы требуется 5-минутная точность между клиентом и сервером. The typical case for Windows is Kerberos, which requires 5 minutes of accuracy between the client and server. Тем не менее есть множество других областей, в которых важна точность времени, в том числе: However, there are many other areas that can be affected by time accuracy including:
- правительственное управление, к примеру Government Regulations like:
- 50 мс для FINRA в США; 50 ms accuracy for FINRA in the US
- 1 мс для Европейской организации по ценным бумагам и рынкам (Директива Евросоюза «O рынках финансовых инструментов») в ЕС; 1 ms ESMA (MiFID II) in the EU.
- алгоритмы шифрования; Cryptography Algorithms
- распределенные системы, такие как кластеры, SQL, Exchange и Document DB; Distributed systems like Cluster/SQL/Exchange and Document DBs
- платформа Блокчейн для биткойн-транзакций; Blockchain framework for bitcoin transactions
- распределенные журналы и анализ угроз; Distributed Logs and Threat Analysis
- Репликация Active Directory AD Replication
- отрасль платежных карт (сейчас требуется точность до 1 с). PCI (Payment Card Industry), currently 1 second accuracy