概述
ntp是网络时间协议,用于不同主机之间通网络同步时间.在linux中使用ntpd工具可以搭建一个ntp服务器,其他主机可以向该服务器同步时间,这在某些对通信双方系统时间一致性有要求的场景中使用较多.
环境
server端:ubuntu 14.04内网
client端:arm64
ntp服务器搭建
- 在外网环境下载ntp及其依赖的deb包
sudo apt-get install ntp
执行此命令会下载deb安装包到/var/cache/apt/archives/下
ls /var/cache/apt/archives/
==> libopts25_1%3a5.18.7-3_amd64.deb lock ntp_1%3a4.2.8p4+dfsg-3ubuntu5.9_amd64.deb partial
其中libopts为ntp所需的依赖.
- 将下载的.deb安装包拷到内网服务器,并安装
sudo dpkg -i libopts25_1%3a5.18.7-3_amd64.deb
sudo dpkg -i ntp_1%3a4.2.8p4+dfsg-3ubuntu5.9_amd64.deb
注意两个包安装的先后顺序.
- 配置
主要需修改的配置文件为/etc/ntp.conf,修改如下(节选需改动部分):
# Use Ubuntu's ntp server as a fallback.
pool ntp.ubuntu.com
# By default, exchange time with everybody, but don't allow configuration.
restrict -4 default kod notrap nomodify nopeer noquery limited
restrict -6 default kod notrap nomodify nopeer noquery limited
# Local users may interrogate the ntp server more closely.
restrict 127.0.0.1
restrict -6::1
#restrict 192.168.1.0 mask 255.255.255.0 nomodify //(add)允许192.168.1网段客户端同步时间
restrict default nomodify //(add)允许任意主机进行时间同步
# Needed for adding pool entries
restrict source notrap nomodify noquery
#server 127.127.22.1 # ATOM(PPS)
#fudge 127.127.22.1 flag3 1 # enable PPS API
server 127.0.0.1 //(add)该服务器同步时间的server为本机
参数解释如下:
restrict:用来实现权限控制
restrict [IP] [mask] [netmask_IP] [patameter]
patameter支持的参数:
igonre:拒绝所有类型的`NTP`连接
nomodify:Client不能够使用命令ntpc以及ntpdq来修改修改服务器的时间参数,但是可以进行网络校时;
noquery:表示不提供NTP网络校时;
notrap:表示不提供远程事件登陆的功能;
notrust:表示不接受没有认证的Clent;
如果没有任何参数,表示不接受任何的限制;
server [IP or hostname] [prefer]
用于设置上层提供NTP服务的服务器;
prefer:表示优先使用
driftfile [可以被ntpd写入的进程或者文件]
NTP Server计算时间是通过本机的时钟振荡来记录的,这个时间和上层Time Server的时钟振荡频率不一定是一致的,需要将这个振荡差异记录下来
- 启动ntp服务
sudo /etc/init.d/ntp restart
或:
sudo systemctl start ntpd
- 等待ntp服务器完成自身同步
该过程可能需要5~6分值哦该,使用该命令查看ntp服务是否完成自身同步:
watch ntpq -p
指令“ntpq -p”可以列出目前我们的NTP与相关的上层NTP的状态,以上的几个字段的意义如下:
remote:即NTP主机的IP或主机名称。注意最左边的符号,如果由“+”则代表目前正在作用钟的上层NTP,如果是“*”则表示也有连上线,不过是作为次要联机的NTP主机。
refid:参考的上一层NTP主机的地址
st:即stratum阶层
when:几秒前曾做过时间同步更新的操作
poll:下次更新在几秒之后
reach:已经向上层NTP服务器要求更新的次数
delay:网络传输过程钟延迟的时间
offset:时间补偿的结果
jitter:Linux系统时间与BIOS硬件时间的差异时间
一般等待reach列大于17即可.
客户端同步时间
arm上需移植ntpd工具,使用如下命令进行时间同步:
ntpd -qnd -p 192.168.10.93(ntp-server ip)
同步完成后可分别在服务器和客户端使用date命令查看时间是否相同
注意事项
- 服务器需关闭防火墙或将ntp的port(udp 123)加入信任
/sbin/iptables -I INPUT -p udp --dport 123 -j ACCEPT