centos7时间同步——NTP

2023-11-15 13:56:21 217

centos7时间同步——NTP

NTP同步方式在linux下一般两种:使用ntpdate命令直接同步和使用NTPD服务平滑同步。

使用ntpdate命令直接同步的方式存在风险,比如一些定时任务在已有时间内执行过,直接同步导致时间变回任务执行前的时间段,定时任务会重复执行。

使用NTPD服务平滑同步的方式不会让一个时间点在一天内经历两次,而是平滑同步时间,它每次同步时间的偏移量不会太陡,是慢慢来的。

查看是否安装NTP包

rpm -qa |grep ntp

如果有输出ntp和ntpdate版本信息,即已安装。

  • ntpdate :时间同步某台服务器

  • ntp :作为时间服务器

ntp 可用systemctl管理

# 查看服务状态
service ntpd status
# 启动ntpd服务
systemctl
start ntpd.service
# 停止ntpd服务
systemctl
stop ntpd.service
# 设置开机自启动
systemctl enable ntpd.service
# 停止开机自启动
systemctl disable ntpd.service
# 查看服务当前状态
systemctl status ntpd.service
# 重新启动服务
systemctl
restart ntpd.service
# 查看所有已启动的服务
systemctl list-units
--type=service

作为ntp客户端,如何同步服务器端的时间?

以公用的一些时间同步服务器为例

systemctl stop ntpd # 使用ntpdate同步前需要关闭ntpd服务,不然会失败
ntpdate cn.pool.ntp.org
systemctl enable ntpd.service
systemctl
start ntpd.service

# cn.pool.ntp.org 中国开源免费NTP服务器
# ntp1.aliyun.com 阿里云NTP服务器
# ntp2.aliyun.com 阿里云NTP服务器
# time1.aliyun.com 阿里云NTP服务器
# time2.aliyun.com 阿里云NTP服务器

如何配置服务器作为内网内的时间同步服务器?(NTP服务器的配置)

配置内网NTP-Server(10.0.0.12)

配置NTPD服务的服务器需要能访问外网,这里挑选了一台可以访问外网的Linux服务器配置内网的NTPD服务,作为NTP-Server,其他几台内网通过它来进行时间同步。

这里假设其IP为10.0.0.12,其他几台内网的服务器IP分别为10.0.0.13、10.0.0.14。

在配置NTPD服务之前,先手动同步一下时间

systemctl stop ntpd # 使用ntpdate同步前需要关闭ntpd服务,不然会失败
ntpdate cn.pool.ntp.org
systemctl enable ntpd.service
systemctl
start ntpd.service

修改NTPD服务的配置文件/etc/ntp.conf

[root@localhost ~]# vim /etc/ntp.conf
#和上层NTP服务器频率误差的记录文件
driftfile /var/lib/ntp/drift
#对于默认的client拒绝所有操作,下面的restrict开通指定权限
restrict default nomodify notrap nopeer noquery
#允许本机地址的一切操作
restrict
127.0.0.1
restrict ::1

#允许192.168.203段机器同步时间,指定可以和NTP通信的IP或者网段
restrict
192.168.203.0 mask 255.255.255.0 nomodify notrap

#远程的同步时间服务器地址(需要同步外网时间必改)
#prefer表示优先同步的主机
server cn.pool.ntp.org prefer
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
server ntp3.aliyun.com iburst
server ntp4.aliyun.com iburst
server ntp5.aliyun.com iburst

#远程时间服务器不可用时,以本地时间作为服务时间
server
127.127.1.0
#stratum指定层数,越小,离时间源,越近。 层级1为国际时间源服务器...
fudge
127.127.1.0 stratum 10

#允许上层服务器主动修改本机时间(需要同步外网时间必改)
restrict cn.pool.ntp.org nomodify notrap noquery
restrict ntp1.aliyun.com iburst nomodify notrap noquery
restrict ntp2.aliyun.com iburst nomodify notrap noquery
restrict ntp3.aliyun.com iburst nomodify notrap noquery
restrict ntp4.aliyun.com iburst nomodify notrap noquery
restrict ntp5.aliyun.com iburst nomodify notrap noquery

includefile /etc/ntp/crypto/pw

#指定日志文件
logfile /var/log/ntp
#指定日志级别,info、all、event三种可以选择
logconfig all

#启用公钥加密
#crypto
#密钥文件
keys /etc/ntp/keys

设置ntp client客户端配置文件

vim /etc/ntp.conf
server
10.0.0.12

重启ntp服务

[root@localhost /]# systemctl stop firewalld
[root@localhost /]
# setenforce 0
[root@localhost /]
# vim /etc/selinux/config
SELINUX=disabled

[root@localhost /]
# systemctl restart ntpd

查看ntp服务同步状况

ntpd -q


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: