Linux中使用NTP保持精确时间的方法详解

2019-10-10 13:47:25于丽

Hardware clock is on UTC time 表明了你的计算机的 RTC 是使用 UTC 时间的,虽然它把该时间转换为你的本地时间。如果它被设置为本地时间,它将显示 Hardware clock is on local time。

你应该有一个 /etc/adjtime 文件。如果没有的话,使用如下命令同步你的 RTC 为系统时间,

$ sudo hwclock -w

这个命令将生成该文件,内容看起来类似如下:

$ cat /etc/adjtime
0.000000 1516661953 0.000000
1516661953
UTC

新发明的 systemd 方式是去运行 timedatectl 命令,运行它不需要 root 权限:

$ timedatectl
 Local time: Mon 2018-01-22 14:17:51 PST
 Universal time: Mon 2018-01-22 22:17:51 UTC
 RTC time: Mon 2018-01-22 22:17:51
 Time zone: America/Los_Angeles (PST, -0800)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

RTC in local TZ: no 表明它使用 UTC 时间。那么怎么改成使用本地时间?这里有许多种方法可以做到。最简单的方法是使用一个图形配置工具,比如像 openSUSE 中的 YaST。你也可使用 timedatectl:

$ timedatectl set-local-rtc 0

或者编辑 /etc/adjtime,将 UTC 替换为 LOCAL。

systemd-timesyncd 客户端

现在,我已经累了,但是我们刚到非常精彩的部分。谁能想到计时如此复杂?我们甚至还没有了解到它的皮毛;阅读 man 8 hwclock 去了解你的计算机如何保持时间的详细内容。

systemd 提供了 systemd-timesyncd.service 客户端,它可以查询远程时间服务器并调整你的本地系统时间。在 /etc/systemd/timesyncd.conf 中配置你的(时间)服务器。大多数 Linux 发行版都提供了一个默认配置,它指向他们维护的时间服务器上,比如,以下是 Fedora 的:

[Time]
#NTP=
#FallbackNTP=0.fedora.pool.ntp.org 1.fedora.pool.ntp.org

你可以输入你希望使用的其它时间服务器,比如你自己的本地 NTP 服务器,在 NTP= 行上输入一个以空格分隔的服务器列表。(别忘了取消这一行的注释)NTP= 行上的任何内容都将覆盖掉 FallbackNTP 行上的配置项。

如果你不想使用 systemd 呢?那么,你将需要 NTP 就行。

配置 NTP 服务器和客户端

配置你自己的局域网 NTP 服务器是一个非常好的实践,这样你的网内计算机就不需要不停查询公共 NTP 服务器。在大多数 Linux 上的 NTP 都来自 ntp 包,它们大多都提供 /etc/ntp.conf 文件去配置时间服务器。查阅 NTP 时间服务器池 去找到你所在的区域的合适的 NTP 服务器池。然后在你的 /etc/ntp.conf 中输入 4 - 5 个服务器,每个服务器用单独的一行:

driftfile /var/ntp.drift
logfile /var/log/ntp.log
server 0.europe.pool.ntp.org
server 1.europe.pool.ntp.org
server 2.europe.pool.ntp.org
server 3.europe.pool.ntp.org