手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux部署NTP服务器进行时间同步

[日期:2019-04-01] 来源:Linux社区  作者:jhxxb [字体: ]

NTP 是网络时间协议(Network Time Protocol)的简称,通过 udp 123 端口进行网络时钟同步

一、安装

# 既可做服务端也可做客户端
yum install -y ntp

# 开启服务,让其他客户端与本机同步,注意防火墙状态
systemctl start ntpd

# 开机自启
systemctl enable ntpd

二、ntp 常用配置 /etc/ntp.conf

# 记录和上级时间服务器的时间差异
driftfile /var/lib/ntp/drift

# ntp 日志
logfile /var/log/ntp.log
# 日志级别 all event info
logconfig all

# 设置默认策略,允许同步时间,不允许修改
restrict default nomodify notrap nopeer noquery

# 允许本机地址的一切操作,-6 为 IPV6
restrict 127.0.0.1
restrict -6 ::1

# 允许网段内客户端连接此服务器同步时间,但是拒绝让他们修改服务器上的时间
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

# https://www.ntppool.org/zone/cn
# 利用 server 设定上层 NTP 服务器,可设置多个。prefer 表示优先
server s1b.time.edu.cn prefer

# 在 /ntp.conf 中定义的 server 都不可用时,将使用 local 时间作为 ntp 服务提供给 ntp 客户端。建议配置,否则 ntp 服务器无法与公网 ntp 服务器同步时,其客户端也会无法同步
server  127.127.1.0
fudge  127.127.1.0 stratum 10

restrict 控制相关权限

# 格式:restrict [IP地址] mask [netmask_IP] [parameter]
# IP地址:可以是 default,指所有的 IP
# netmask_IP:子网掩码
# parameter 有以下几个:
## ignore  :拒绝所有类型的 NTP 联机
## nomodify:客户端不能使用 ntpc 与 ntpq 修改服务器的时间参数,但客户端仍可通过这部主机来进行网络校时
## noquery :客户端不能够使用 ntpq 与 ntpc 等来查询时间服务器,等于不提供 NTP 的网络校时
## notrap :不提供 trap 这个远程事件登录(remote event logging)的功能,用于远程事件日志记录
## notrust :Client 除非通过认证,否则该 Client 来源将被视为不信任网域,会拒绝没有认证的客户端
## nopeer :用于阻止主机尝试与服务器对等,并允许欺诈性服务器控制时钟
## kod : 向不安全的访问者发送 Kiss-Of-Death 报文

三、使用

# 国家授时中心
210.72.145.44
# 阿里云
ntp.aliyun.com

s1a.time.edu.cn 北京邮电大学
s1b.time.edu.cn 清华大学
s1c.time.edu.cn 北京大学
s1d.time.edu.cn 东南大学
s1e.time.edu.cn 清华大学
s2a.time.edu.cn 清华大学
s2b.time.edu.cn 清华大学
s2c.time.edu.cn 北京邮电大学
s2d.time.edu.cn 西南地区网络中心
s2e.time.edu.cn 西北地区网络中心
s2f.time.edu.cn 东北地区网络中心
s2g.time.edu.cn 华东南地区网络中心
s2h.time.edu.cn 四川大学网络管理中心
s2j.time.edu.cn 大连理工大学网络中心
s2k.time.edu.cn CERNET桂林主节点
s2m.time.edu.cn 北京大学
ntp.sjtu.edu.cn 202.120.2.101 上海交通大学

ntp 常用命令

ntpdate 命令参数

# 查看ntp版本
ntpq -c version

# 上层 ntp 的状态
ntpq -p

# ntp 同步状态
ntpstat

# 向 NTP 服务器同步自己的时间,需关闭 ntpd 服务,-u 指定使用无特权的端口发送数据包 -d 调试
ntpdate -u s1a.time.edu.cn

系统时钟与硬件时钟之间同步

# 设置硬件时钟
# -w,--systohc
hwclock -w

# 设置系统时钟
# -s, --hctosys
hwclock -s

# 修改配置文件方式
vim /etc/sysconfig/ntpd
# 将系统时间写入BIOS,与 hwclock -w 效果相同
SYNC_HWCLOCK=yes

ntpd 与 ntpdate

ntpd 不仅仅是时间同步服务器,它还可以做客户端与标准时间服务器进行同步时间,而且是平滑同步,并非ntpdate立即同步,在生产环境中慎用ntpdate,也正如此两者不可同时运行。

时钟的跃变,对于某些程序会导致很严重的问题。

四、关于定时同步

开机时自动同步可编辑 /etc/ntp/step-tickers 文件

vim /etc/ntp/step-tickers

# List of NTP servers used by the ntpdate service.

ntp.aliyun.com
time2.aliyun.com
ntp2.aliyun.com

定时同步可使用 crontab,添加定时任务

systemctl start crond

systemctl enable crond

# 添加
crontab –e

# 每两个小时同步一次
0 */2 * * * ntpdate s2m.time.edu.cn && hwclock -w

# 查看
crontab –l

linux
相关资讯       NTP服务器 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款