Windows 搭建 NTP 服务器
一、核心说明
- 用途:Windows 作为 NTP 时间服务器,Linux 通过
ntpdate同步 Windows 系统时钟 - 协议端口:UDP 123(必须放行)
- 适用环境:同一局域网/跨网段(需网络放通 UDP 123)
二、Windows 端配置(管理员 PowerShell 执行)
1. 启用 NTP 服务(注册表配置)
# 启用 NTP 服务器功能
reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer /v Enabled /t REG_DWORD /d 1 /f
# 声明为可靠时间源 (AnnounceFlags: 0x01=可靠, 0x04=自动公告, 5=两者皆是)
reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Config /v AnnounceFlags /t REG_DWORD /d 5 /f
# 设置同步模式为 NTP
reg add HKLM\SYSTEM\CurrentControlSet\Services\W32Time\Parameters /v Type /t REG_SZ /d NTP /f
2. 重启时间服务使配置生效
# 重启 Windows 时间服务
Restart-Service w32time
# 设置服务开机自启
Set-Service -Name w32time -StartupType Automatic
3. 放行防火墙 UDP 123 端口
# 删除旧规则(避免冲突)
Remove-NetFirewallRule -DisplayName "NTP Server" -ErrorAction SilentlyContinue
# 新建入站规则,放行 UDP 123
New-NetFirewallRule -DisplayName "NTP Server" -Direction Inbound -Protocol UDP -LocalPort 123 -Action Allow -Profile Any
4. 验证 Windows NTP 服务正常
# 查看 NTP 配置(确认 Enabled: True)
w32tm /query /configuration
# 查看端口监听(必须看到 UDP 0.0.0.0:123)
netstat -ano | findstr ":123"
三、Linux 端配置(root 权限执行)
1. 停止占用 NTP 端口的服务(解决端口占用报错)
# 停止系统自带时间服务
systemctl stop ntp chronyd systemd-timesyncd
# 禁用开机自启(永久解决端口冲突)
systemctl disable --now ntp chronyd systemd-timesyncd
2. 安装 ntpdate(未安装时执行)
# Debian/Ubuntu 系统
apt update && apt install -y ntpdate
# CentOS/RHEL 系统
yum install -y ntpdate
3. 同步 Windows 时间(替换为你的 Windows IP)
ntpdate 192.165.52.31
4. 写入硬件时钟(重启不失效)
hwclock --systohc
5. 配置定时同步(可选,每10分钟同步一次)
# 编辑定时任务
crontab -e
添加以下内容:
*/10 * * * * /usr/sbin/ntpdate 192.165.52.31 > /dev/null 2>&1
查看任务:
crontab -l
四、常见报错解决方案
1. Linux 报错:the NTP socket is in use, exiting
- 原因:系统时间服务占用 UDP 123 端口
- 解决:执行 Linux 端步骤 1
2. Linux 报错:no server suitable for synchronization found
- 原因1:Windows IP 填写错误 → 核对 Windows
ipconfigIPv4 地址 - 原因2:防火墙未放行 → 执行 Windows 步骤 3
- 原因3:跨网段拦截 UDP 123 → 临时关闭 Windows 防火墙测试:
Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled False - 终极替代方案(SSH 同步时间,无需 NTP 端口):
ssh 192.165.52.31 "date +%Y%m%d%H%M%S" | xargs date -s
五、验证成功标准
- Windows:
netstat能看到UDP 0.0.0.0:123 - Linux:执行
ntpdate输出类似:adjust time server 192.165.52.31 offset -0.023456 sec
浙公网安备 33010602011771号