搭建NTP时间服务器

作者: oldboy 分类: IDC 发布时间: 2022-07-18 15:59

一.NTP介绍

NTP(Network Time Protocol,网络时间协议)是用来使网络中的各个计算机时间同步的一种协议。它的用途是把计算机的时钟同步到世界协调时UTC,其精度在局域网内可达0.1ms,在互联网上绝大多数的地方其精度可以达到1-50ms。
NTP服务器就是利用NTP协议提供时间同步服务的

二.NTP服务器安装

1.查看本机系统版本
cat /etc/redhat-release
2.查看本机NTP软件包
rpm -qa ntp

检查ntp服务的安装情况

rpm -qa |grep ntp
ntpdate-4.2.6p5-25.el7.centos.2.x86_64                        #客户端
ntp-4.2.6p5-25.el7.centos.2.x86_64                               #服务端

如果没有安装的话则安装下

yum install -y ntp ntpdate

三.NTP服务器配置

0.先把服务器的时间同步并定时同步

yum -y install rdate
rdate -s time.nist.gov
clock -w
echo "0 */1 * * * /usr/bin/rdate -s time.nist.gov &> /dev/null" /var/spool/cron/root

1.备份ntp服务器配置文件

cp /etc/ntp.conf /etc/ntp.conf.bak

ll /etc/ntp.conf*
2.精简优化配置文件

egrep -v “^$|#” /etc/ntp.conf.bak >/etc/ntp.conf

3.编辑配置文件

vim /etc/ntp.conf

修改成:

driftfile /var/lib/ntp/drift
restrict default nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
#允许哪些网段的机器可以同步时间
restrict 61.160.0.0 mask 255.255.255.0 nomodify notr
service 61.160.236.160
#把本机作为ntp服务端
server 127.127.1.0
#这行是时间服务器的层次。设为0则为顶级,如果要向别的NTP服务器更新时间,请不要把它设为0
fudge 127.127.1.0 stratum 1
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor

/etc/ntp.conf文件说明

#允许哪些网段的机器可以同步时间
restrict 61.160.0.0 mask 255.255.255.0 nomodify notr
#指明局域网中作为NTP服务器的IP
service 61.160.236.160
#把本机作为ntp服务端 
server 127.127.1.0
#这行是时间服务器的层次。设为0则为顶级,如果要向别的NTP服务器更新时间,请不要把它设为0 
fudge 127.127.1.0 stratum 1
#启用日志功能(报错)
#logfile /var/log/ntp.log

4. 使硬件时间和系统时间一致

修改配置文件 vim /etc/sysconfig/ntpd 添加

echo "SYNC_HWCLOCK=yes" >> /etc/sysconfig/ntpd

最终配置:

cat >/etc/ntp.conf<<EOF
driftfile /var/lib/ntp/drift
restrict default nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
#允许哪些网段的机器可以同步时间
restrict 61.160.0.0 mask 255.255.255.0 nomodify notrap
restrict 103.26.0.0 mask 255.255.255.0 nomodify notrap
restrict 103.56.152.0 mask 255.255.255.0 nomodify notrap
restrict 103.73.119.0 mask 255.255.255.0 nomodify notrap
restrict 118.184.172.64 mask 255.255.255.0 nomodify notrap
#把本机作为ntp服务端 
server 127.127.1.0
#这行是时间服务器的层次。设为0则为顶级,如果要向别的NTP服务器更新时间,请不要把它设为0 
fudge 127.127.1.0 stratum 1
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor
logfile /var/log/ntp.log
EOF

四.启动NTP服务器()

Centos6: /etc/init.d/ntpd start centos7:

systemctl start ntpd 

显示节点列表

ntpq -p

查看本ntp服务器与上层服务器的连接状态

说明
remote:本机与上层ntp的ip或主机名,“+”表示优先,“*”表示次优先。
refid:参考的上一层ntp主机地址
st:stratum阶层
poll:每几秒更新一次
offset:时间补偿的结果

ntpstat

五.防火墙放行

firewall-cmd --add-port=123/udp --permanent
firewall-cmd --reload

六.客户端时间同步测试

ntpdate 61.160.236.160

定时同步时间

echo "0 */1 * * * /usr/sbin/ntpdate 61.160.236.160 &>/dev/null"  >>/var/spool/cron/root

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

标签云