NTP(NetworkTimeProtocol,网络时间协议)是用来在分布式时间服务器和客户端之间进行时间同步。NTP基于UDP报文进行传输,使用的UDP端口号为123
当服务器多了,如果一台一台的配置时间,是非常累的,而且时间不一致是会导致服务器出现各种各样的问题。
一、NTP服务器的安装
RPM安装
Mount /dev/cdrom /media
Rpm -ivh media/Centos/ntp-4.2.2p1-9.e156.centos.2.1.x86_64.rpm
yum安装
yum -y install ntp
源码编译安装
wget http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-4.2/ntp-4.2.6p4.tar.gztar zxvf ntp-4.2.6.tar.gz
cd ntp-4.2.6
./configure --prefix=/usr/local/ntp--enable-all-clocks --enable-parse-clocks
make && make install
二、NTP的配置文件和相关命令
/etc/ntp.conf NTP服务的配置文件。
1)通过restrict来设置权限
配置方法一:至允许192.168.100.0网段的客户机进行时间同步
在restrict default kod nomodify notrap nopeer noquery (表示默认拒绝所欲IP的时间同步)之后增加一行
restrict 192.168.100.0 mask 255.255.255.0 nomodify notrap
配置方法二:允许任何IP的客户机都可以进行时间同步
将restrict default kod nomodify notrap nopeer noquery 修改为如下行:
restrict default nomodify
restrict IP地址 mask 子网掩码参数
其中IP 地址可以是default,default至所有的IP
restrict
参数有以下几个:
ignore :关闭所有的NTP联机服务
nomodify:客户端不能更改服务端的时间参数,但是客户端可以通过服务端进行网络校时。
notrust :客户端除非通过认证,否则该客户端来源将被视为不信任子网
noquery :不提供客户端的时间查询
2)、用server这个参数设定上级时间服务器,语法为:
server IP地址或域名[prefer]
IP地址或域名就是我们指定的上级时间服务器,如果Server参数最后加上prefer,表示我们的NTP服务器主要以该部主机时间进行校准。
3)、解决NTP服务器校准时间时的传送延迟
使用driftfile参数设置:
driftfile 文件名
记录上次的NTP server与上层NTP server 连接所花费的时间
注意: 文件的权限需要设定成 ntpd守护进程可以写入。
4)设置ntp日志
#ntp日志的path
statsdir
#ntp日志文件
/usr/share/zoneinfo/ 这个目录下存放的是各个时区对应的设定文件。
/etc/localtime 本地系统时间设定文件。
/etc/sysconfig/clock 本机时区设定文件cat /etc/sysconfig/clock
ZONE="Asia/Shanghai"
UTC=true
ARC=false
当我们修改了上图中ZONE选项中的时区时,系统就对去/usr/share/zoneinfo/取对应的时区设定文件,复制为本地/etc/localtime。
相关命令:
date 修改和显示日期和时间的命令。
hwclock 将当前系统时间写入CMOS的命令,只有root用户才可以使用。
ntpd NTP服务的守护进程文件,需要先启动它才能提供NTP服务。
ntpdate 客户端时间同步
三、配置NTP
# vi /etc/ntp.conf
#========权限控制============
restrict default kod nomodify notrap nopeer noquery 拒绝IPV4用户
restrict -6 default kod nomodify notrap nopeer noquery 拒绝IPV6用户
restrict 210.72.145.44 授权国家授时中心服务器访问本地NTP
restrict 133.100.11.8 授权133.100.11.8访问本地NTP
restrict 127.0.0.1
restrict -6 ::1
restrict 192.168.100.0 mask 255.255.255.0 nomodify 本地网段授权访问
#=========源服务器===========
server 210.72.145.44 prefer 指定上级更新时间服务器,优先使用这个地址
server 133.100.11.8
#=========差异分析===========
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys
# service ntpd start RPM和YUM安装的启动方式
#/usr/local/ntp/bin/ntpd -c /etc/ntp.conf -p/tmp/ntpd.pid 源码编译安装的启动方式
Chkconfig ntpd on
ntpd启动后,客户机要等几分钟再与其进行时间同步,否则会提示“no server suitable for synchronization found”错误。
# netstat -tlunp | grepntp 如果看到123端口,说明ntp服务成功启动。
# ntpstat 查看ntp服务器与上级服务器是否通讯
# ntpq –p 查看本地NTP与上级服务器的通讯情况
四、客户端如何更新时间
# ntpdate 192.168.100.10
手工更新太麻烦,我们写个任务计划定时更新
Echo “0 1 * * * /usr/sbin/ntpdate 192.168.18.2 ; /sbin/hwclock -w” >> /var/spool/cron/root
Cat /var/spool/cron/root
0 1 * * * /usr/sbin/ntpdate 192.168.18.2 ; /sbin/hwclock -w