251118-NTP(systemd-timesyncd)配置内网时间同步

systemd-timesyncd 这个服务,怎么同步内网服务

Ubuntu 20.04 默认就用 systemd-timesyncd 做时间同步,无需安装任何包,只要改两行配置即可让它只走内网 NTP
下面给出最小步骤(假设内网 NTP 服务器 IP 为 192.168.0.100),复制就能用。


  1. 确认服务已启用

1
systemctl status systemd-timesyncd

若看到 Active: inactive (dead),先启动它:

1
2
sudo systemctl unmask systemd-timesyncd
sudo systemctl enable --now systemd-timesyncd

  1. 指定内网服务器

编辑配置文件

1
sudo vim /etc/systemd/timesyncd.conf

[Time] 段改成:

1
2
3
[Time]
NTP=192.168.0.100
FallbackNTP=

FallbackNTP= 留空,防止断网时去连外网)

保存后执行:

1
sudo systemctl restart systemd-timesyncd

  1. 立即触发同步 & 验证

1
2
sudo systemctl restart systemd-timesyncd   # 重启即触发
timedatectl timesync-status # 看是否已指向 192.168.0.100

输出示例:

1
2
3
4
Server: 192.168.0.100 (192.168.0.100)
Poll interval: 32s
Leap: normal
...

看到 Server: 行就是只走内网


  1. 常用排障

  • 时间差太大(>1000s)同步失败:

    1
    2
    sudo timedatectl set-time "2025-11-28 12:00:00"   # 先手动拉到 1s 内
    sudo systemctl restart systemd-timesyncd
  • 防火墙:本机需放行出站 UDP 123

    1
    sudo ufw allow out 123/udp

【方案一】增加定时调度器,定时重启时间同步(系统定时任务crontab)

sudo systemctl restart systemd-timesyncd # 重启即触发

1
2
3
4
5
crontab -e

# 每小时的 0 分、45 分各跑一次,相当于 45 min 间隔
0,45 * * * * /bin/systemctl restart systemd-timesyncd

【方案二】增加定时调度器【替代方案】干脆让 systemd 自己定时(更简洁):

1
2
3
4
5
6
7
8
9
10
# /etc/systemd/system/refresh-timesyncd.timer
[Unit]
Description=Refresh systemd-timesyncd every 45 min

[Timer]
OnBootSec=5min
OnUnitActiveSec=45min

[Install]
WantedBy=timers.target
1
2
3
4
# /etc/systemd/system/refresh-timesyncd.service
[Service]
Type=oneshot
ExecStart=/bin/systemctl restart systemd-timesyncd

然后

1
2
sudo systemctl daemon-reload
sudo systemctl enable --now refresh-timesyncd.timer

即可实现“每 45 分钟重启一次 timesyncd”,无需再写 crontab。


  1. 一键脚本(客户端批量)
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
srv=192.168.0.100
sudo tee /etc/systemd/timesyncd.conf <<EOF
[Time]
NTP=$srv
FallbackNTP=
EOF
sudo systemctl unmask systemd-timesyncd
sudo systemctl enable --now systemd-timesyncd
sudo systemctl restart systemd-timesyncd
timedatectl timesync-status

保存为 set-timesyncd.shchmod +x set-timesyncd.sh && ./set-timesyncd.sh 即可。

至此,systemd-timesyncd通过内网地址完成时间同步,无需额外安装 chrony 或 ntp 包