Time windows ntp сервер

howto:ntp_server_activation

по материалам сайта http://windowsnotes.ru

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

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

  • При установке операционной системы Windows запускает клиента NTP, который синхронизируется с внешним источником времени;

  • При добавлении компьютера в домен тип синхронизации меняется. Все клиентские компьютеры и рядовые сервера в домене используют для синхронизации времени контроллер домена, проверяющий их подлинность;

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

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

Такая схема работает в большинстве случаев и не требует вмешательства. Однако структура сервиса времени в Windows может и не следовать доменной иерархии и надежным источником времени можно назначить любой компьютер.

В качестве примера приведем настройку NTP-сервера в Windows Server 2008 R2, по аналогии можно настроить NTP сервер и в Windows 7.

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

Служба времени в Windows Server не имеет графического интерфейса и настраивается либо из командной строки, либо путем прямой правки системного реестра. Рассмотрим второй способ:

Необходимо запустить сервер NTP. Открываем ветку реестра:
HKLM\System\CurrentControlSet\services\W32Time\TimeProviders\NtpServer.
Для включения сервера NTP параметру Enabled надо установить значение 1. Затем перезапускаем службу времени командой net stop w32time && net start w32time.

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

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

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

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

  • NoSync — NTP-сервер не синхронизируется с каким либо внешним источником времени. Используются системные часы, встроенные в микросхему CMOS самого сервера (в свою очередь эти часы могут синхронизироваться от источника NMEA по RS-232 например);

  • NTP — NTP-сервер синхронизируется с внешними серверами времени, которые указаны в параметре реестра NtpServer;

  • NT5DS — NTP-сервер производит синхронизацию согласно доменной иерархии;

  • AllSync — NTP-сервер использует для синхронизации все доступные источники.

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

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

Допускаются следующие значения режима:

  • 0×1 – SpecialInterval, использование временного интервала опроса;

  • 0×2 – режим UseAsFallbackOnly;

  • 0×4 – SymmetricActive, симметричный активный режим;

  • 0×8 – Client, отправка запроса в клиентском режиме.

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

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

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

И еще несколько команд для настройки, мониторинга и диагностики службы времени:

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

  • w32tm /resync – при помощи этой команды можно заставить компьютер синхронизироваться с используемым им сервером времени.

  • w32tm /stripchart – показывает разницу во времени между текущим и удаленным компьютером. Команда w32tm /stripchart /computer:time.nist.gov /samples:5 /dataonly произведет 5 сравнений с указанным источником и выдаст результат в текстовом виде.

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

  • w32tm /query — показывает текущие настройки службы. Например команда w32tm /query /source покажет текущий источник времени, а w32tm /query /configuration выведет все параметры службы.

  • net stop w32time — останавливает службу времени, если запущена.

  • w32tm /unregister — удаляет службу времени с компьютера.

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

  • net start w32time — запускает службу.

Особенности, замеченные в Windows 7 — служба времени не запускается автоматически при старте Windows. Исправлено в SP1 для Windows 7.

howto/ntp_server_activation.txt

· Последнее изменение: 2022/02/24 17:39 —

Dmitriy Sazhin


Accurate time synchronization is vital for the smooth operation of computer systems, especially in environments where multiple devices interact over a network. Network Time Protocol (NTP) ensures that all devices maintain the correct time, which is crucial for logging events, security protocols, and the proper functioning of time-dependent applications. In Windows, NTP settings can be managed through the Windows Registry, providing advanced users and IT professionals with granular control over time synchronization behaviors. This guide will walk you through understanding and configuring NTP settings via the Windows Registry.


Understanding NTP and Its Importance

Network Time Protocol (NTP) is a networking protocol designed to synchronize the clocks of computers over packet-switched, variable-latency data networks. Accurate timekeeping is essential for:

  • Security: Ensures the validity of authentication tokens and encryption protocols.
  • Logging: Provides accurate timestamps for system and application logs.
  • Data Integrity: Prevents issues in databases and file systems that rely on precise time stamps.
  • Network Operations: Coordinates tasks and schedules across multiple devices.

Without proper time synchronization, discrepancies can lead to security vulnerabilities, data inconsistencies, and operational inefficiencies.


Windows Time Service Overview

Windows uses the Windows Time Service (W32Time) to synchronize the system clock with configured time sources. By default, Windows Time Service is configured to use NTP servers to keep the system time accurate. The service can operate in different modes, such as:

  • NTP Client: Synchronizes the system time with external NTP servers.
  • NTP Server: Provides time synchronization services to other devices on the network.

Understanding and configuring the Windows Time Service via the Registry allows for customized synchronization settings tailored to specific network environments.


Locating NTP Settings in the Windows Registry

The NTP settings are primarily located within the Windows Registry under the following path:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

Within this key, several values determine how the Windows Time Service operates, including the NTP server addresses, synchronization frequency, and other related settings.

Key Registry Values for NTP Configuration:

  • NtpServer: Specifies the list of NTP servers the system will synchronize with.
  • Type: Defines the synchronization type (e.g., NTP, NT5DS).
  • AnnounceFlags: Determines the role of the computer in the time synchronization hierarchy.
  • SpecialPollInterval: Sets the interval between synchronization attempts.

Warning: Editing the Windows Registry can have significant impacts on your system. Always back up the Registry before making any changes.

Steps to Configure NTP Settings:

1. Open Registry Editor

To edit the Registry, you’ll use the Registry Editor (regedit), a built-in Windows utility.

  1. Press Win + R to open the Run dialog box.
  2. Type regedit and press Enter.
  3. If prompted by User Account Control (UAC), click Yes to allow Registry Editor to make changes.

2. Navigate to the NTP Settings

In Registry Editor, browse to:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters

3. Modify the NtpServer Value

  1. Double-click on NtpServer in the right pane.
  2. Enter the NTP servers you wish to use, separated by spaces. Each server should be followed by a comma and a flag. For example: time.windows.com,0x9 time.nist.gov,0x9
    • The flag 0x9 indicates that the server should be used for synchronization and that it’s a reliable time source.

4. Set the Synchronization Type

  1. Double-click on Type.
  2. Set the value to NTP to specify that the system should use the NTP server(s) defined in NtpServer.NTP
    • Other possible values include:
      • NT5DS: Synchronizes with the domain hierarchy.
      • AllSync: Allows synchronization with all available time sources.

5. Adjust the Polling Interval (Optional)

  1. Navigate to:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient
  2. Double-click on SpecialPollInterval.
  3. Set the value (in seconds) to define how often the system will poll the NTP server. For example, to set it to 1 hour:3600

6. Enable the NTP Client

  1. Navigate to:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient
  2. Double-click on Enabled.
  3. Set the value to 1 to enable the NTP client.

Example Configuration

Suppose you want to configure your system to synchronize with pool.ntp.org every 2 hours. Here’s how you can set it up:

  1. Set NtpServer:pool.ntp.org,0x9
  2. Set Type:NTP
  3. Set SpecialPollInterval:7200
  4. Ensure Enabled is set to 1.

Restarting the Windows Time Service

After making changes to the Registry, it’s essential to restart the Windows Time Service to apply the new settings.

Steps to Restart the Service:

  1. Open Command Prompt as Administrator:
    • Press Win + X and select Command Prompt (Admin) or Windows PowerShell (Admin).
  2. Stop the Windows Time Service:net stop w32time
  3. Start the Windows Time Service:net start w32time
  4. Resynchronize the Time (Optional):w32tm /resync
    • Note: If you encounter errors, ensure that the Windows Time Service is configured correctly and that there are no network issues preventing synchronization.

Precautions and Best Practices

  • Backup the Registry: Before making any changes, create a backup to prevent potential system issues.
    • In Registry Editor, right-click on the W32Time key and select Export. Save the .reg file to a safe location.
  • Use Trusted NTP Servers: Only use reputable NTP servers to ensure accurate and secure time synchronization.
  • Avoid Frequent Polling: Setting the polling interval too low can lead to unnecessary network traffic and may be flagged as suspicious activity.
  • Limit Registry Editing to Advanced Users: Incorrect modifications can cause system instability. If unsure, seek assistance from IT professionals.

Troubleshooting NTP Issues

If you encounter problems with time synchronization after configuring NTP settings, consider the following troubleshooting steps:

1. Verify NTP Server Accessibility

Ensure that the NTP servers you specified are reachable and operational.

  • Use the ping command to test connectivity:ping pool.ntp.org

2. Check Windows Time Service Status

Ensure that the service is running:

sc query w32time

3. Review Event Logs

  • Open Event Viewer (Win + X > Event Viewer).
  • Navigate to Windows Logs > System and look for events related to W32Time.

4. Force Time Synchronization

Use the following command to force synchronization:

w32tm /resync /force

5. Reset Windows Time Service Configuration

  1. Stop the service:net stop w32time
  2. Unregister the service:w32tm /unregister
  3. Register the service again:w32tm /register
  4. Start the service:net start w32time
  5. Reconfigure NTP settings as needed.

Conclusion

Proper time synchronization is essential for the reliable and secure operation of Windows systems within any networked environment. By configuring NTP settings through the Windows Registry, advanced users can tailor time synchronization behaviors to meet specific requirements. However, caution must be exercised when editing the Registry to prevent system instability. Always ensure you have backups and understand the implications of the changes you make.

Network Time Protocol (NTP) is a highly scalable internet protocol that determines the best time information and synchronizes accurate settings on a computer system. This guide explains how to set the time zone and configure NTP on a Windows Server.

This guide uses Windows Server 2019, but these instructions work on any machine with Server 2016 or later.

Prerequisites

Before you begin:

  • Deploy a Vultr Windows Server.
  • Connect to the server.

Set the Timezone

Windows Timezone Settings

  1. Using the Windows Start Menu, open Server Manager.
  2. Locate Time zone in the local server properties section.
  3. Click the current timezone, which is UTC Coordinated Universal Timeby default.
  4. In the Date and Time window, click Change time zone.
  5. Expand the Time zone drop-down list.
  6. Select your preferred timezone. It’s recommended to set it to your server location.
  7. Click OK to save changes.
  8. Click Apply to load changes on the server.
  9. Re-open Server Manager, and verify the timezone change.

Optional: Set the Timezone using PowerShell

  1. From the start menu, open Windows PowerShell, or open the run dialog (Win key + R), type powershell in the search bar, and click OK to start PowerShell.

  2. Run the following command to check the server timezone.

     PS > Get-Timezone
  3. View all available timezones.

     PS> Get-Timezone -ListAvailable

    To find your target timezone, use the following command to filter by name.

     PS> Get-Timezone -ListAvailable | Where-Object {$_.displayname -like "*US*"}

    > The command above displays all names containing the characters US. You can use a different string such as London.

  4. Change your timezone.

     PS> Set-Timezone -Name "Central Standard Time"

    You can also change the timezone by ID.

     PS> Set-Timezone -Id "Central Standard Time"

Configure NTP

In addition to setting the timezone, you can also configure Windows to use NTP to synchronize the time.

  1. Open the Run dialog window by pressing the Windows key (WIN) + R on your keyboard.

  2. In the search bar, enter regedit and click OK to open Registry Editor.

  3. Expand the registry navigation tree:

    HKEY_LOCAL_MACHINE -> SYSTEM -> CurrentControlSet -> Services

  4. Expand W32Time.

  5. Click Config.

  6. Select AnnounceFlags

  7. Enter 5 in the Value data field.

  8. Click OK to save changes.

  9. In the left pane, click Parameters.

Optional: Change the NTP Server

By default, Vultr uses the time.constant.com time server, located on our high-speed infrastructure. If you want to use a different time server, you can change the value of the NtpServer parameter by following these steps.

  1. Double-click NtpServer

  2. Change the value data field to your preferred value. For example, to sync with the United States NTP pool, use:

     us.pool.ntp.org

    You can find a list of NTP Pool servers at the official website.

  3. Expand TimeProviders.

  4. Click NtpServer.

  5. Double click Enabled, change the value data from 0 to 1, and click OK to save changes.

  6. Close the registry editor, open the start menu, and search the keyword services.

  7. In the services window, scroll through the list, select Windows Time, right-click, and select Restart to apply NTP changes.

Optional: Configure NTP Using PowerShell

If you prefer to use Powershell, you can use the following commands to configure NTP.

  1. Open PowerShell with administrative privileges.

  2. Check the NTP time synchronization status.

     PS> w32tm /query /status
  3. Enter the following command to set the time AnnounceFlags to 5.

     PS> Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\W32Time\Config" -Name "AnnounceFlags" -Value 5 
  4. (Optional) If you want to use NTP pool servers instead of Vultr’s NTP server, run the following command.

     PS> Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\w32time\Parameters" -Name "NtpServer" -Value us.pool.ntp.org
  5. Enable NTP Server.

     PS> Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\w32time\TimeProviders\NtpServer" -Name "Enabled" -Value 1
  6. Restart the Windows Time service.

     PS> Restart-Service w32Time
  7. Test NTP synchronization.

     PS> w32tm /resync

Next Steps

You have successfully set the timezone and configured NTP on Windows Server 2019. If you plan to have other machines on a Vultr VPC use your NTP server, allow port 123 in the Windows Server Firewall. For further information, refer to the following guides.

  • Official NTP Documentation
  • List of database TimeZones
  • Configure the Firewall on Windows Server 2019
  • Create A Vultr Virtual Private Cloud (VPC)

Skip to content

Windows – NTP server installation

Windows – NTP server installation

Would you like to learn how to install the NTP server on Windows? In this tutorial, we are going to show you how to configure an NTP server on a computer running Windows.

• Windows 2012 R2
• Windows 2016
• Windows 2019
• Windows 10
• Windows 7

Equipment list

Here you can find the list of equipment used to create this tutorial.

This link will also show the software list used to create this tutorial.

Windows – Related Tutorial:

On this page, we offer quick access to a list of tutorials related to Windows.

Tutorial Windows – NTP server installation

As Administrator, start an elevated command-line.

Windows - Elevated command prompt

Create a backup of the Windows registry entries.

Configure the Windows time service as an NTP server.

Configure the list of NTP servers.

Configure the NTP poll interval.

Configure the Windows time service to start automatically.

Start the Windows time service.

Optionally, restart the Windows time service using the graphical interface.

Windows - NTP Server installation

Create a Firewall rule to allow the input of packets on the NTP port.

Verify the NTP server configuration.

Here is the command output.

Congratulations! You have finished the installation of the NTP server on Windows.

Tutorial Windows – NTP server verification

Verify the NTP server peer list.

Verify the NTP service communication.

From a remote computer, test your NTP server.

Here is the command output.

In our example, the NTP server IP address is 172.31.0.84.

From a computer running Linux, test your NTP server.

Here is the command output.

Congratulations! You have finished the NTP server configuration on Windows.

VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22020-12-03T09:48:59-03:00

Related Posts

Page load link

This website uses cookies and third party services.

Ok

Материал из support.qbpro.ru

Для правильного функционирования доменной среды Windows Server 2008 R2/2012 R2, является корректная работа службы времени Windows (W32Time).
Схема работы синхронизации времени в доменной среде Active Directory:

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

Служба времени в Windows (W32Time) не имеет графического интерфейса и настраивается из командной строки (утилита w32tm), с помощью реестра

(HKLM\System\CurrentControlSet\Services\W32Time\Parameters) и посредством Групповой политики (Group Policy Managment)

Для определения какому контроллеру домена принадлежит FSMО-роль PDC-эмулятора, в командной строке, выполним команду: netdom query FSMO

Включение NTP-сервера
NTP-сервер по-умолчанию включен на всех контроллерах домена, но его можно включить и на рядовых серверах:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer]  — «Enabled»=1

Конфигурация NTP-сервера
Задаем тип синхронизации внутренних часов, на использование внешнего источника. (Командная строка/Реестр):

w32tm /config /syncfromflags:manual
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters] — «Type»=NTP

Допускаются следующие значения:

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

Задание списка внешних источников для синхронизации, с которыми будет синхронизировать время данный сервер. По-умолчанию в этом параметре прописан NTP-сервер Microsoft (time.windows.com, 0×1). (Командная строка/Реестр):

w32tm /config /manualpeerlist:»0.ru.pool.ntp.org,0x1 1.ru.pool.ntp.org,0x1 2.ru.pool.ntp.org,0x1″
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Parameters] — «NtpServer»=0.ru.pool.ntp.org,0x1 1.ru.pool.ntp.org,0x1 
2.ru.pool.ntp.org,0x1

Допускаются следующие значения:

0×1 – SpecialInterval, использование временного интервала опроса.
0×2 – режим UseAsFallbackOnly.
0×4 – SymmetricActive, симметричный активный режим.
0×8 – Client, отправка запроса в клиентском режиме.

Задание интервала синхронизации с внешним источником (для источников помеченных флагом 0×1). По-умолчанию время опроса задано — 3600 сек. (1 час). (Командная строка/Реестр):

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpClient] — «SpecialPollInterval»=3600

Объявление NTP-сервера в качестве надежного. (Командная строка/Реестр):

w32tm /config /reliable:yes
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config] — «AnnounceFlags»=0000000a

После настройки необходимо обновить конфигурацию сервиса. Выполняем команду:

w32tm /config /update

Принудительная синхронизация времени от источника:

w32tm /resync /rediscover

Отобразить текущую конфигурацию службы времени:

w32tm /query /configuration

Получения информации о текущем сервере времени:

w32tm /query /source

Отображение текущих источников синхронизации и их статуса:

w32tm /query /peers

Отображение состояния синхронизации контроллеров домена с компьютерами в домене:

w32tm /monitor /computers:192.168.1.2

Отобразить разницу во времени между текущим и удаленным компьютером:

w32tm /stripchart /computer:192.168.1.2 /samples:5 /dataonly

Удалить службу времени с компьютера:

w32tm /unregister

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

w32tm /register

Остановка службы времени:

net stop w32time

Запуск службы времени:

net start w32time

Конфигурация NTP-сервера/клиента групповой политикой
Для централизованной настройки службы времени Windows, на серверах и рабочих станциях в доменной среде Active Directory, воспользуемся групповой политикой. На примере, выполним настройку для рабочих станций.

Переходим в ветку: Конфигурация компьютера (Computer Configuration) — Политики (Policies) — Административные шаблоны (Administrative Templates) — Система (System) — Служба времени Windows (Windows Time Service) — Поставщики времени (Time Providers).

Открываем параметр: Настроить NTP-клиент Windows (Configure Windows NTP Client)

Time32hlp1.png

NtpServer — 192.168.1.2 (Адрес контроллера домена с ролью PDC)
Type — NT5DS
CrossSiteSyncFlags — 2
ResolvePeerBackoffMinutes —15
Resolve Peer BackoffMaxTimes — 7
SpecilalPoolInterval — 3600
EventLogFlags — 0
  • источник

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Подключение двух мониторов к одному компьютеру windows 10
  • Ошибка 0х80240017 при установке visual c windows
  • Windows server 2019 inside out на русском
  • K meleon для windows 2000
  • Трансляция экрана windows 10 на несколько телевизоров