部署 NTP 时间服务器
2013-03-30 by dongnan
开始之前
当前虚拟化遍布企业的每个角落中,在给我们带来好处的同时也带来了一些麻烦,比如正在使用的ESXi,
虚拟机的系统时间有时候是不一样的,这样很糟糕比如会给mysql数据库或者日志等等造成影响。
当我们手动更改时间这样是徒劳的,由于是虚拟机即使用hwclock -w命令也无法把系统时间写入宿主机bios,
下次重启虚拟机时间又变了,有没有什么一劳永逸的方法那? 
答案是使用 NTP时间服务器,Linux系统下使用的是 Network Time Protocol Daemon 程序。
环境描述
操作系统: CentOS 6.2
软件版本: ntp-4.2.6
部署
Linux 下的NTP服务器安装部署比较方便:
yum install ntp
相关文件:
- /etc/ntp.conf:NTP服务的主要配置文件,所有的更改全部在这里。
- /usr/sbin/ntpd:NTP服务的守护进程,配置文件为- /etc/ntp.conf。
- /usr/sbin/ntpdate:用来连接NTP服务器命令,比如- ntpdate 192.168.6.51。
- /usr/sbin/ntpq:NTP查询命令。
配置
示例 ntp.conf 配置:
grep -Ev '^$|^#' /etc/ntp.conf
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
restrict 218.75.4.130
restrict 202.112.10.36
restrict 202.112.31.197
restrict 202.120.2.101
restrict 202.112.29.82
restrict 202.118.1.199 
restrict 127.0.0.1
restrict 192.168.0.0 mask 255.255.0.0 nomodify //该网段可以进行校时
restrict 0.0.0.0 mask 0.0.0.0 notrust          //拒绝没有认证的用户端
server ntp.aliyun.com prefer                   // prefer该服务器优先
server 0.centos.pool.ntp.org
server 1.centos.pool.ntp.org
server 2.centos.pool.ntp.org
fudge 127.127.1.0 stratum 10   
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys
查询限制条件:
restrict IP mask [参数]
其中参数包括以下选项:
- ignore: 拒绝所有类型的NTP的连接。
- nomodfiy: 用户端不能使用- ntpc与- ntpq这两支程式来修改服务器的时间参数,但使用者仍可透过这部主机来进行网络校时。
- noquery: 用户端不能够使用- ntpc、- ntpq等指令来查询服务器。
- notrap:不提供陷阱这个远端事件邮箱(远程事件日志)的功能。
- notrust:拒绝没有认证的客户端查询。
如果没有在参数的地方加上任何参数的话,这表示该IP或网段不受任何限制。
启动NTP服务:
/etc/init.d/ntp start
验证
客户端测试,只需要是用 ntpdate 命令+NTP服务器的IP192.168.6.51,就这么就简单!

查看NTP服务器状态:
ntpstat
synchronised to NTP server (131.107.13.100) at stratum 2  
time correct to within 461 ms 
polling server every 64 s
列出目前NTP服务器与上层NTP服务器的状态,
// * 代表目前正在使用的上层 NTP服务器
ntpq -p
remote           refid      st t when poll reach   delay   offset  jitter 
========================================================================== 
*131.107.13.100  .ACTS.           1 u   30   64   67  237.165    1.539  20.382 
202.118.1.199   202.112.31.197   2 u   33   64   63  163.526   91.844  10.208
NTP 防火墙规则
NTP使用的端口:
grep -E '^ntp' /etc/services
ntp        123/tcp
ntp        123/udp               # Network Time Protocol
防火墙规则:
# 以 iptables 为例
iptables -A INPUT -p tcp -s 0/0 --dport 123 -j ACCEPT
iptables  -A INPUT -p udp -s 0/0 --dport 123 -j ACCEPT