「Linux」- 搭建 NTP 服务

  CREATED BY JENKINSBOT

问题描述

该笔记将记录:在 Linux 中,如何使用 ntpd 搭建 NTP 服务,以及常见问题解决方案。

解决方案

第一步、安装服务

# 系统环境:Ubuntu 14.04.5 LTS
# ntp中包含的是服务端相关的程序文件。
# ntpdate中包含的是客户端相关的程序文件。
apt-get install ntp ntpdate

参考 BLFS7.1.0/ntp-4.2.8p8 文档,以获取源码编译安装的方法。

安装的可执行程序:
calc_tickadj,calculates optimal value for tick given ntp drift file.
ntp-keygen,generates cryptographic data files used by the NTPv4 authentication and identification schemes.
ntp-wait,is useful at boot time, to delay the boot sequence until ntpd has set the time.
ntpd,is a ntp daemon that runs in the background and keeps the date and time synchronized based on response from configured ntp servers. It also functions as a ntp server.
ntpdate,is a client program that sets the date and time based on the response from an ntp server. This command is deprecated.
ntpdc,is used to query the ntp daemon about its current state and to request changes in that state.
ntpq,is a utility program used to monitor ntpd operations and determine performance.
ntptime,reads and displays time-related kernel variables.
ntptrace,traces a chain of ntp servers back to the primary source.
sntp,is a Simple Network Time Protocol (SNTP) client.
tickadj,reads, and optionally modifies, several timekeeping-related variables in older kernels that do not have support for precision timekeeping.
update-leap,is a script to verify and, if necessary, update the leap-second definition file.

注意事项
1)以上的部分命令可能不存在于发行版的包中,只有使用源码编译才会出现。

第二步、修改 /etc/ntp.conf 配置

# restrict、default定义默认访问规则,nomodify禁止远程主机修改本地服务器
restrict default kod nomodify notrap nopeer noquery
# 配置,notrap拒绝特殊的ntpdq捕获消息,noquery拒绝btodq/ntpdc查询
restrict -6 default kod nomodify notrap nopeer noquery
# (这里的查询是服务器本身状态的查询)。
restrict 127.0.0.1
restrict -6 ::1

# 这句是手动增加的,意思是指定的192.168.1.0--192.168.1.254的服务器都可以使用ntp服务器来同步时间。
restrict 0.0.0.0 mask 0.0.0.0 nomodify notrap

#这句也是手动添加的,可以将局域网中的指定ip作为局域网内的ntp服务器。
server 0.centos.pool.ntp.org
server 1.centos.pool.ntp.org
server 2.centos.pool.ntp.org

# local clock。当服务器与公用的时间服务器失去联系时,就是连不上互联网时,以局域网内的时间服务器为客户端提供时间同步服务。
server  127.127.1.0
fudge   127.127.1.0 stratum 10

第三步、启动服务

#!/bin/sh

/usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 105:114

# 防火墙配置
iptables -A INPUT -i eth0 -p udp -m udp --sport 123 --dport 123 -j ACCEPT

第四步、测试服务

ntpdate -v 103.213.249.202

参考文献

How to Install and Configure Linux NTP Server and Client
BLFS7.1.0中的ntp-4.2.8p8的编译手册