在 NTP 服务器(10.0.0.81)上的配置
- 安装 NTP 服务:
yum install ntp -y
- 配置 NTP 服务器:
编辑 NTP 配置文件/etc/ntp.conf
。
vi /etc/ntp.conf
在文件中进行以下修改:
- 注释掉所有默认的上游 NTP 服务器(通常以
server
开头的行)。 - 添加以下内容,允许 10.0.0.0/24 网段的客户端访问该 NTP 服务器:
restrict 10.0.0.0 mask 255.255.255.0 nomodify notrap server 127.127.1.0 # 本地时钟作为时间源 fudge 127.127.1.0 stratum 10 server ntp.aliyun.com iburst server 210.72.145.44 iburst server time1.tsinghua.edu.cn iburst
restrict
语句用于设置访问控制,nomodify
表示客户端不能修改服务器的时间参数,notrap
表示不接受客户端的时间陷阱报文。server 127.127.1.0
将本地时钟作为时间源,fudge 127.127.1.0 stratum 10
设置本地时钟的层级为 10(层级数字越小越接近权威时间源)。
[root@ansible ~]# cat ntp.conf
# /etc/ntp.conf, configuration for ntpd; see ntp.conf(5) for help
# Drift file. This file keeps track of the system clock's time drift.
driftfile /var/lib/ntp/drift
# Enable this if you want to serve time to other machines. This works if you enable
# restricted access (see "restrict" options below).
# 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
# 注释掉所有默认的上游 NTP 服务器
# 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
# 添加自定义的上游 NTP 服务器
server ntp.aliyun.com iburst
server 210.72.145.44 iburst
server time1.tsinghua.edu.cn iburst
# 将本地时钟作为时间源
server 127.127.1.0
# 设置本地时钟的层级为 10(层级数字越小越接近权威时间源)
fudge 127.127.1.0 stratum 10
# Access control configuration; see /usr/share/doc/ntp-doc/html/accopt.html for
# details. The web page <http://support.ntp.org/bin/view/Support/AccessRestrictions>
# might also be helpful.
#
# Note that "restrict" applies to both servers and clients, so a configuration
# that might be intended to block requests from certain clients could also end
# up blocking replies from your own upstream servers.
# 默认情况下,拒绝所有请求
restrict default kod nomodify notrap nopeer noquery
# 允许 10.0.0.0/24 网段的客户端访问该 NTP 服务器
restrict 10.0.0.0 mask 255.255.255.0 nomodify notrap
# Local users may interrogate the ntp server more closely.
restrict 127.0.0.1
restrict ::1
# 如果需要,可以添加其他配置选项,例如:
# keys /etc/ntp/keys
# disable monitor
- 启动和配置开机自启 NTP 服务:
systemctl start ntpd
systemctl enable ntpd
- 检查 NTP 服务状态:
可以使用以下命令检查 NTP 服务是否正常运行:
systemctl status ntpd
也可以使用 ntpq -p
命令查看 NTP 服务器的同步状态:
ntpq -p
在客户端(10.0.0.8)上的配置
- 安装 NTP 工具 如果客户端尚未安装 NTP 工具,需要安装:
yum install ntpdate -y
- 手动同步时间 使用
ntpdate
命令手动将客户端时间与 NTP 服务器同步:
ntpdate 10.0.0.81
- 配置自动同步时间(可选) : 为了确保客户端时间始终与 NTP 服务器同步,可以设置定时任务来定期执行
ntpdate
命令。编辑 crontab 文件:
crontab -e
添加以下内容,使系统每分钟执行一次
ntpdate
命令与 NTP 服务器同步时间:
* * * * * /usr/sbin/ntpdate 10.0.0.81 > /dev/null 2>&1
这里
> /dev/null 2>&1
是将命令的输出重定向到空设备,以避免产生日志信息。