学习笔记之ntp服务

973 阅读2分钟

一、ntp服务器配置

1、安装ntp和ntpdate
yum -y install ntp ntpdate
2、编辑ntp服务配置文件

优先从外网服务器同步时间,当外网链接失败,使用本地服务器同步时间。

vi /etc/ntp.conf

PS:可以直接使用下面配置替换ntp.conf文件里的内容

driftfile /var/lib/ntp/drift

# chown ntp:ntp /var/log/ntpd.log
# chcon -t ntpd_log_t /var/log/ntpd.log
# NTP服务器的默认日志路径 /var/log/messages
logfile /var/log/ntpd.log

# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default nomodify notrap nopeer noquery

# Permit all access over the loopback interface.  This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1
restrict ::1

#授权192.168.33网段上所有的机器可以从ntp服务器上查询和同步时间
restrict 192.168.33.0 mask 255.255.255.0 nomodify notrap

#从以下几个时间服务器列表同步时间
server 0.asia.pool.ntp.org iburst
server 1.asia.pool.ntp.org iburst
server 2.asia.pool.ntp.org iburst
server 3.asia.pool.ntp.org iburst

#当外部时间服务器不可用时,使用本地服务器时间
server 127.127.1.0 iburst
fudge 127.127.1.0 stratum 10

#允许上层服务器修改本机时间
restrict 0.asia.pool.ntp.org nomodify notrap noquery
restrict 1.asia.pool.ntp.org nomodify notrap noquery
restrict 2.asia.pool.ntp.org nomodify notrap noquery
restrict 3.asia.pool.ntp.org nomodify notrap noquery

includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor
3、执行命令
#设置ntp和ntpdate开机自启动
systemctl enable ntpd
systemctl enable ntpdate

#验证自启动是否成功
[root@ironman ~]# systemctl is-enabled ntpd
enabled

#启动ntp服务
systemctl start ntpd

#系统时间和硬件时间同步
hwclock -w

#测试
[root@ironman ~]# ntpstat 
synchronised to NTP server (192.46.215.60) at stratum 3
   time correct to within 137 ms
   polling server every 64 s

四、客户端配置

1、安装ntp和ntpdate
yum -y install ntp ntpdate
2、执行命令
#设置ntpdate开机自启动
systemctl enable ntpdate

#系统时间和硬件时间同步
hwclock -w

#设置定时器,每天同步一次时间
crontab -e

00 01 * * * (/usr/sbin/ntpdate -u 192.168.10.200 && /sbin/hwclock -w) &> /var/log/ntpdate.log

#测试(ironman为ntp服务器hostname)
[root@mark2 ~]# ntpdate -u ironman
25 Jun 18:27:44 ntpdate[2162]: adjust time server 192.168.37.37 offset 0.001191 sec