ubuntu/centos/windows时间同步

64 阅读2分钟

ntp服务使用123端口传递udp包,所以在配置之前请务必确认端口能放通,不管是上层还是下层都要确认 以下是配置iptables的命令,其他防火墙工具同理:

iptables -I INPUT -p udp --dport 123 -j ACCEPT
iptables-save > /etc/sysconfig/iptables //保存配置
  • unbuntu

ubuntu使用ntp进行时间同步


$ apt update // 更新资源库
$ apt install ntp

$ nano /etc/ntp.conf
driftfile /var/lib/ntp/ntp.drift

leapfile /usr/share/zoneinfo/leap-seconds.list

statistics loopstats peerstats clockstats
filegen loopstats file loopstats type day enable
filegen peerstats file peerstats type day enable
filegen clockstats file clockstats type day enable

pool 0.cn.pool.ntp.org iburst
pool 1.ubuntu.pool.ntp.org iburst
pool 2.ubuntu.pool.ntp.org iburst
pool 3.ubuntu.pool.ntp.org iburst

pool ntp.ubuntu.com

restrict -4 default kod notrap nomodify nopeer noquery limited
restrict -6 default kod notrap nomodify nopeer noquery limited

restrict 127.0.0.1
restrict ::1

restrict source notrap nomodify noquery


$ timedatectl set-timezone Asia/Shanghai //设置时区为中国上海

$ hwclock -w // 将系统时间写入硬件时钟
$ timedatectl // 查看时间同步情况

$ ntpstat
synchronised to NTP server (100.64.8.9) at stratum 3
time correct to within 28 ms
polling server every 64 s

  • centos

centos可以使用ntp服务或chrony服务进行时间同步,二者的区别是chrony服务更适合在网络连接不稳定或不频繁的情况下使用,而ntp服务更适合在网络连接稳定且持续的情况下使用。我这里使用的是chrony,chrony在系统中自带

$ yum update // 更新资源库
$ yum reinstall chrony // 重新安装chrony组件,以匹配版本

$ nano /etc/chrony.conf
server *.*.*.* 
pool 0.pool.ntp.org iburst 
//这里的配置表示在内网环境下使用你配置的ntp服务器进行时间同步,注意server和pool之间一定要换行,原来的pool配置可以都注释掉

$ systemctl start chronyd.service //使用systemctl启动chrony服务
$ systemctl enable chronyd.service //在开机启动项中添加chrony
$ systemctl status chronyd.service //查看服务状态

如果要使用ntp服务,配置与unbuntu下略有不同:
$ nano /etc/ntp.conf
driftfile /var/lib/ntp/drift

restrict 127.0.0.1
restrict ::1

server 10.10.14.10 iburst
#server 0.cn.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst

restrict 10.10.0.0 mask 255.255.0.0 nomodify notrap

includefile /etc/ntp/crypto/pw

keys /etc/ntp/keys

disable monitor

$ hwclock -w // 将系统时间写入硬件时钟
$ timedatectl // 查看时间同步情况
  • windows 这里配置windows自带的时间服务工具w32tm
[打开“服务”(services.msc),找到“Windows Time”并将启动类型修改为“自动”]
C:\Windows\System32>w32tm /config /manualpeerlist:*.*.*.* /syncfromflags:manual /reliable:yes /update
// ntp服务器写在manualpeerlist下
C:\Windows\System32>net stop w32time //停止服务 
C:\Windows\System32>net start w32time //启动服务 
C:\Windows\System32>w32tm /resync /force //应用修改并马上同步时间



C:\Windows\System32>w32tm /query /status //查看时间同步情况

如果只有一个ntp服务器的话,也可以直接在日期与时间的位置修改默认的时间服务器

windows如何确定与时间服务器的连接是否正常

除了使用ping命令以外,还可以: C:\Windows\System32>w32tm/stripchart /computer:10.10.10.10

当windows配置时报错,可以重新注册时间服务再重复上述步骤

C:\Windows\System32>w32tm /unregister

C:\Windows\System32>w32tm /register

参考资料: 1、使用windows时间服务:Windows 时间服务工具和设置 | Microsoft Learn

才疏学浅,在这里记录一下经验,如有出入,欢迎指正:)