一、使用公共时间同步服务器
国内稳定的时间同步服务器:
times.aliyun.com
ntp.aliyun.com
cn.pool.ntp.org
0.cn.pool.ntp.org
1.cn.pool.ntp.org
使用ntpdate
命令同步时间:
# yum -y install ntpdate
# ntpdate ntp.aliyun.com
18 Jan 18:30:53 ntpdate[10374]: step time server 203.107.6.88 offset 56.345324 sec
二、自建NTP服务器
对于能够直接访问互联网的服务器,我们可以直接执行ntpdate
命令完成时间同步。但对于局域网中不能直接访问互联网的服务器,我们可能需要利用一台能够访问互联网的服务器自建NTP服务完成时间同步,或者利用一台时间较准确的服务器作为时间同步服务器。
时间同步NTP服务基于NTP协议,默认监听UDP123端口。
2.1、部署NTP服务器
安装NTP服务:
# yum -y install ntp
配置:
# cat /etc/ntp.conf
driftfile /var/lib/ntp/drift
# 注释原有配置
#restrict default nomodify notrap nopeer noquery
#restrict 127.0.0.1
#restrict ::1
#server 0.centos.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 192.168.18.0 mask 255.255.255.0 nomodify notrap
# 指定公共时间同步服务器
server ntp.aliyun.com iburst prefer
server times.aliyun.com iburst
server cn.pool.ntp.org iburst
logfile /var/log/ntpstats/ntpd.log
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor
启动NTP服务并查看服务状态:
# systemctl start ntpd
# systemctl status ntpd
查看时间同步状态:
# ntpq -p
remote refid st t when poll reach delay offset jitter
==============================================================================
*203.107.6.88 100.107.25.114 2 u 62 64 377 14.312 1.895 1.483
+120.25.115.20 10.137.53.7 2 u 68 64 377 42.814 -0.124 0.275
+time.cloudflare 10.12.2.186 3 u 8 64 277 260.186 -30.576 18.076
说明:
remote:连接的NTP服务器,最左边的符号如下:
[*] 代表目前正在使用的NTP服务器;
[+] 代表备用的NTP服务器;
[-] 代表不合格的NTP服务器;
[x] 代表NTP服务器不可用;
refid:指的是给当前NTP服务器提供时间同步的上一级服务器;
st:NTP服务器的级别;
when:上一次与NTP服务器进行时间校对的时间(单位:s);
poll:与NTP服务器进行时间校对的周期(单位:s);
reach:已经向NTP服务器要求更新的次数;
delay:网络传输延迟,单位为微秒;
offset:时间偏移量,单位为微秒;
jitter:Linux系统时间与BIOS硬件时间的差异时间,单位为微秒。
2.2、客户端时间同步
2.2.1、通过ntpdate命令同步
对于已经存在的时间同步服务器,在客户端可以直接通过ntpdate
命令完成时间同步:
# yum -y install ntpdate
# ntpdate [NTP server IP]
如果出现“no server suitable for synchronization found”,尝试在NTP服务器上重启NTP服务。
2.2.2、通过NTP服务同步
客户端也需要安装NTP服务:
# yum -y install ntp
在配置文件中,将NTP服务器设置为本地时间同步服务器:
# cat /etc/ntp.conf
server 192.168.18.133 iburst # 时间同步服务器地址
logfile /var/log/ntpstats/ntpd.log
启动NTP服务:
# systemctl start ntpd
2.3、NTP服务配置相关参数说明
“restrict”配置相关参数:
ignore:拒绝所有类型的NTP同步请求;
nomodify:允许客户端从本服务器同步时间,但客户端不能使用“ntpc”和“ntpq”命令修改服务器的时间参数;
noquery:客户端不能够使用“ntpc”和“ntpq”等命令查询时间服务器,不提供时间同步;
notrap:不提供“trap”远程事件登入的功能;
notrust:拒绝未通过认证的客户端;
kod:可以阻止“Kiss of Death “包对服务器的破坏;
nopeer:不与其它同级别的NTP服务器进行时间同步。
“server”配置相关参数:
perfer:表示优先级最高;
burst:当一个远程NTP服务器可用时,向它发送一系列的并发包进行检测。
iburst:当一个远程NTP服务器不可用时,向它发送一系列的并发包进行检测。