需求

在内网服务器中,部署一台ntp服务器,然后其他服务器同步ntp服务器的时间

ntp服务端安装及配置

如在 192.168.149.150 上安装ntp服务,作为服务端

安装ntp
yum -y install ntp

编辑配置文件: /etc/ntp.conf

#添加本节点IP地址
restrict 192.168.149.150 nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
 
#添加节点所在网关和掩码
restrict 192.168.149.2 mask 255.255.255.0 nomodify notrap
 
#指定本ntp服务器的上游ntp服务器为本地时间
server 127.127.1.0  #local clock 如果上面的服务器都无法同步时间,就和本地系统时间同步。127.127.1.0在这里是一个IP地址,不是网段。
Fudge 127.127.1.0 stratum 10  #127.127.1.0 为第10层。ntp 和127.127.1.0同步完后,就变成了11层。  ntp是层次阶级的。同步上层服务器的stratum 大小不能超过或等于16。

interface listen 192.168.149.150

如下图:

centos配置ntp校时 centos7配置ntp_centos配置ntp校时


centos配置ntp校时 centos7配置ntp_客户端_02

启动ntp服务
#开启服务
systemctl start ntpd.service
 
#停止服务
systemctl stop ntpd.service
 
#开机启动
systemctl enable ntpd.service
查看状态
#查看状态
ntpstat

centos配置ntp校时 centos7配置ntp_centos配置ntp校时_03

#查看ntp服务器与上层ntp的状态
ntpq -p

centos配置ntp校时 centos7配置ntp_linux_04

  • remote:本机和上层ntp的ip或主机名,“+” 表示优先,“*” 表示次优先
  • refid:参考上一层ntp主机地址
  • st:stratum阶层
  • when:多少秒前曾经同步过时间
  • poll:下次更新在多少秒后
  • reach:已经向上层ntp服务器要求更新的次数
  • delay:网络延迟
  • offset:时间补偿
  • jitter:系统时间与bios时间差
restrict选项格式
restrict  [客户端IP]  mask  [IP掩码]  [参数]

“客户端IP” 和 “IP掩码” 指定了对网络中哪些范围的计算机进行控制,如果使用default关键字,则表示对所有的计算机进行控制,参数指定了具体的限制内容,常见的参数如下:

  • ignore:拒绝连接到NTP服务器
  • nomodiy: 客户端不能更改服务端的时间参数,但是客户端可以通过服务端进行网络校时。
  • noquery: 不提供客户端的时间查询
  • notrap: 不提供trap远程登录功能,trap服务是一种远程时间日志服务。
  • notrust: 客户端除非通过认证,否则该客户端来源将被视为不信任子网 。
  • nopeer: 提供时间服务,但不作为对等体。
  • kod: 向不安全的访问者发送Kiss-Of-Death报文。
server选项格式
server host  [ key n ] [ version n ] [ prefer ] [ mode n ] [ minpoll n ] [ maxpoll n ] [ iburst ]

其中host是上层NTP服务器的IP地址或域名,随后所跟的参数解释如下所示:

  • key: 表示所有发往服务器的报文包含有秘钥加密的认证信息,n是32位的整数,表示秘钥号。
  • version: 表示发往上层服务器的报文使用的版本号,n默认是3,可以是1或者2。
  • prefer: 如果有多个server选项,具有该参数的服务器有限使用。
  • mode: 指定数据报文mode字段的值。
  • minpoll: 指定与查询该服务器的最小时间间隔为2的n次方秒,n默认为6,范围为4-14。
  • maxpoll: 指定与查询该服务器的最大时间间隔为2的n次方秒,n默认为10,范围为4-14。
  • iburst: 当初始同步请求时,采用突发方式接连发送8个报文,时间间隔为2秒。

ntp客户端安装及配置

在所有客户端主机上安装ntp服务,如 192.168.149.152

yum -y install ntp

编辑配置文件: /etc/ntp.conf

#添加本节点IP地址
restrict 192.168.149.152 nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
 
#添加节点所在网关和掩码
restrict 192.168.149.2 mask 255.255.255.0 nomodify notrap
 
#指定本ntp服务端地址
server 192.168.149.150
Fudge 192.168.149.150

interface listen 192.168.149.152

如下图:

centos配置ntp校时 centos7配置ntp_linux_05


centos配置ntp校时 centos7配置ntp_服务器_06

启动服务
systemctl start ntpd.service
查看状态

centos配置ntp校时 centos7配置ntp_linux_07

同步时间
ntpdate -u 192.168.149.150

centos配置ntp校时 centos7配置ntp_服务器_08

客户端自动同步ntp服务端时间

编辑自动同步脚本:

vim /usr/local/sbin/ntpdate.sh
#!/bin/bash
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin"
ntpdate -u 192.168.149.150
hwclock --systohc  # 将系统时间同步给硬件时间 或者用 clock -w
# 给脚本赋予执行权限:
chmod +x /usr/local/sbin/ntpdate.sh

crontab中添加定时执行脚本命令:

# 如:每分钟同步一次
* * * * * /usr/local/sbin/ntpdate.sh >> /tmp/ntp.log