以下内容讨论在局域网中设置时钟同步。
假设在一个局域网内有两台服务器:
主机名 | IP | 服务器角色 |
---|---|---|
ntp-server | 192.168.0.100 | ntp服务器 |
test | 192.168.0.101 | 普通服务器 |
ntp-server作为ntp服务器,test参考ntp-server的时间进行时钟同步。
安装ntp服务
需要做时钟同步的所有服务器(包括ntp-server)都要安装ntp服务
安装方式,以centos7为例:
yum install ntp
制作局域网ntp服务器
连接到ntp-server,编辑 /etc/ntp.conf 文件如下部分:
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
#server 0.rhel.pool.ntp.org iburst
#server 1.rhel.pool.ntp.org iburst
#server 2.rhel.pool.ntp.org iburst
#server 3.rhel.pool.ntp.org iburst
server 127.127.1.0
fudge 127.127.1.0 stratum 10
如上,注释原有配置:
#server 0.rhel.pool.ntp.org iburst
#server 1.rhel.pool.ntp.org iburst
#server 2.rhel.pool.ntp.org iburst
#server 3.rhel.pool.ntp.org iburst
添加新配置,让本机的ntpd和本地硬件时间同步:
server 127.127.1.0
fudge 127.127.1.0 stratum 10
启动ntp服务:
systemctl start ntpd
systemctl enable ntpd
配置局域网内其他服务器
这里以test服务器为例。
关闭ntp服务:
systemctl stop ntpd
systemctl disable ntpd
同步时钟:
ntpdate 192.168.0.100
如果有问题,可考虑是否是ntp-server防火墙造成的
定时同步,编辑 /etc/crontab 文件,追加内容:
*/5 * * * * root /usr/sbin/ntpdate 192.168.0.100
这里表示每5分钟同步一次。执行用户是root。
然后重启crond服务:
systemctl restart crond
其他
Real Time Clock(RTC) and System Clock
说到设置时间这里还要明确另外一个概念就是在一台计算机上我们有两个时钟:一个称之为硬件时间时钟(RTC),还有一个称之为系统时钟(System Clock)。
硬件时钟是指嵌在主板上的特殊的电路, 它的存在就是平时我们关机之后还可以计算时间的原因。 系统时钟就是操作系统的kernel所用来计算时间的时钟. 它从1970年1月1日00:00:00 UTC时间到目前为止秒数总和的值。 在Linux下系统时间在开机的时候会和硬件时间同步(synchronization),之后也就各自独立运行了
那么既然两个时钟独自运行,那么时间久了必然就会产生误差了,下面我们来看一个例子:
# date
Fri Jul 6 00:27:13 BST 2007
# hwclock --show
Fri 06 Jul 2007 12:27:17 AM BST -0.968931 seconds
通过hwclock --show 命令我们可以查看机器上的硬件时间(always in local time zone),我们可以看到它和系统时间还是有一定的误差的, 那么我们就需要把他们同步。
如果我们想要把硬件时间设置成系统时间我们可以运行以下命令:
# hwclock --hctosys
反之,我们也可以把系统时间设置成硬件时间:
# hwclock --systohc
那么如果想设置硬件时间我们可以开机的时候在BIOS里设定.也可以用hwclock命令:
# hwclock --set --date="mm/dd/yy hh:mm:ss"
如果想要修改系统时间那么用date命令就最简单了:
# date -s "dd/mm/yyyy hh:mm:ss"
现在我们知道了如何设置系统和硬件的时间. 但问题是如果这两个时间都不准确了怎么办? 那么我们就需要在互联网上找到一个可以提供我们准确时间的服务器然后通过一种协议来同步我们的系统时间,那么这个协议就是NTP了。
ntp拓展
配置文件中的driftfile是什么?
我们每一个system clock的频率都有小小的误差,这个就是为什么机器运行一段时间后会不精确. NTP会自动来监测我们时钟的误差值并予以调整.但问题是这是一个冗长的过程,所以它会把记录下来的误差先写入driftfile.这样即使你重新开机以后之前的计算结果也就不会丢失了
如何同步硬件时钟?
NTP一般只会同步system clock. 但是如果我们也要同步RTC(hwclock)的话那么只需要把下面的选项打开就可以了:
# vi /etc/sysconfig/ntpd
SYNC_HWCLOCK=yes
提示
让linux运行ntpdate更新时间时,linux不能开启NTP服务,否则会提示端口被占用:如下
[root@ESXI ~]# ntpdate 1.rhel.pool.ntp.org
20 May 09:34:14 ntpdate[6747]: the NTP socket is in use, exiting
crontab文件配置简要说明
命令格式的前一部分是对时间的设定,后面一部分是要执行的命令。时间的设定我们有一定的约定,前面五个*号代表五个数字,数字的取值范围和含义如下:
分钟 (0-59)
小時 (0-23)
日期 (1-31)
月份 (1-12)
星期 (0-6)//0代表星期天
除了数字还有几个个特殊的符号就是“”、“/”和“-”、“,”,“”代表所有的取值范围内的数字,“/”代表每的意思,“*/5”表示每5个单位,“-”代表从某个数字到某个数字,“,”分开几个离散的数字。以下举几个例子说明问题:
每天早上6点:
0 6 * * * command
每两个小时:
0 */2 * * * command
晚上11点到早上8点之间每两个小时,早上八点:
0 23-7/2,8 * * * command
每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点:
0 11 4 * 1-3 command
1月1日早上4点:
0 4 1 1 * command