# Network Time Protocol daemon (简体中文)

本文描述如何设置和运行 NTPd (Network Time Protocol daemon)。NTPd是使用网络时间协议将 GNU/Linux 系统的软件时钟与 Internet 时间服务器同步的最常见的方法。如果正确设置，NTPd 可以使你的计算机作为时间服务器运行。

## 安装

安装 ntp，可以从官方源得到。

## 配置

小贴士: ntp 包带有一个默认的 `/etc/ntp.conf` 配置文件，可以让 NTPd 不需要自定义配置就可以运行

### 配置连接到 NTP 服务器

在你的 `/etc/ntp.conf` 配置文件中定义的第一件事是你机器想同步的服务器。

NTP servers are classified in a hierarchical system with many levels called strata: the devices which are considered independent time sources are classified as stratum 0 sources; the servers directly connected to stratum 0 devices are classified as stratum 1 sources; servers connected to stratum 1 sources are then classified as stratum 2 sources and so on.

It has to be understood that a server's stratum cannot be taken as an indication of its accuracy or reliability. Typically, stratum 2 servers are used for general synchronization purposes: if you do not already know the servers you are going to connect to, you should use the pool.ntp.org servers (alternate link) and choose the server pool that is closest to your location.

下面几行仅仅是例子：

    server 0.us.pool.ntp.org iburst
    server 1.us.pool.ntp.org iburst
    server 2.us.pool.ntp.org iburst
    server 3.us.pool.ntp.org iburst

iburst 选项是推荐的，如果第一次尝试无法建立连接的话，会发送一系列的包。burst 选项总是发送一系列的包，即使第一次尝试也是这样。如果没有明确的允许的话不要使用 burst 选项，有可能被封禁。

### 配置自己的 NTP 服务器

如果建立一个 NTP 服务器，你需要添加 local clock 作为一个服务器，这样，即便它失去网络连接，它也可以继续为网络提供服务;添加 local clock 作为一个 stratum 10 服务器 (使用 fudge 命令)这样它就只会在失去连接时使用本地时钟：

    server 127.127.1.0
    fudge  127.127.1.0 stratum 10

下一步，定义规则允许客户端连接你的服务(localhost 也被认为是一个客户端)。使用 restrict 命令；你应该在文件中已经有一行：

    restrict default nomodify nopeer noquery

This restricts everyone from modifying anything and prevents everyone from querying the status of your time server: `nomodify` prevents reconfiguring your ntpd (with ntpq or ntpdc), and `noquery` prevents dumping status data from your ntpd (also with ntpq or ntpdc).

你也能添加其它选项：

    restrict default kod nomodify notrap nopeer noquery

注意: 这会允许其他人查询你的时间服务器。你需要添加 `noserve` 来停止提供时间。

"restrict"选项的完整文档可以从 `man ntp_acc` 中查找到。详见 https://support.ntp.org/bin/view/Support/AccessRestrictions 。

你需要在这一行之后告诉 ntpd 什么可以访问你的服务器；如果你不是在配置一台 NTP 服务器的话，下面一行就足够了。

    restrict 127.0.0.1

If you want to force DNS resolution to the IPv6 namespace, write `-6` before the IP address or host name (`-4` forces IPv4 instead), for example:

    restrict -6 default kod nomodify notrap nopeer noquery
    restrict -6 ::1    # ::1 is the IPv6 equivalent for 127.0.0.1

Lastly, specify the drift file (which keeps track of your clock's time deviation) and optionally the log file location:

    driftfile /var/lib/ntp/ntp.drift
    logfile /var/log/ntp.log

一份基础的配置文件是这样的 （为了清晰起见，已删掉了所有的注释）：

    /etc/ntp.conf

    server 0.pool.ntp.org iburst
    server 1.pool.ntp.org iburst
    server 2.pool.ntp.org iburst
    server 3.pool.ntp.org iburst

    restrict default kod nomodify notrap nopeer noquery
    restrict -6 default kod nomodify notrap nopeer noquery

    restrict 127.0.0.1
    restrict -6 ::1

    driftfile /var/lib/ntp/ntp.drift
    logfile /var/log/ntp.log

注意: 定义日志文件不是必须的，但是它对于反馈 ntpd 操作是有好处的。

### 其他关于配置 NTP 的资源

总之，永远不要忘记手册页： `man ntp.conf` 有可能可以回答你仍旧有的任何疑问。（见相关的手册页： `man {ntpd|ntp_auth|ntp_mon|ntp_acc|ntp_clock|ntp_misc}`）。

## 不以守护进程使用

想要仅仅同步时钟一次，不想启动守护进程的话，运行：

    # ntpd -qg
    # hwclock -w

`ntpd -qg` 与 `ntpdate` 程序效果相同，而ntpdate 已经不推荐使用. `hwclock -w` 把时间存储到硬件时钟上，这样重启的时候就不会丢失了。

`ntpd` 的 `-g` 选项允许时钟漂移大于警报级别(默认是 15 分钟)而不发出警告。注意这种误差是不正常的，也许意味着失去设置错误，时钟芯片错误，或仅仅是长时间的忽略。如果在这些情况下你不想设置时钟而且输出错误到 syslog，删除 `-g`：

    # ntpd -q

### 启动时同步一次时钟

Warning: Using this method is discouraged on servers and in general on machines that need to run continuously for more than 2 or 3 days, as the system clock will be updated only once at boot time.

Write a oneshot systemd unit:

    /etc/systemd/system/ntp-once.service

    [Unit]
    Description=Network Time Service (once)
    After=network.target nss-lookup.target

    [Service]
    Type=oneshot
    ExecStart=/usr/bin/ntpd -q -g -u ntp:ntp ; /sbin/hwclock -w

    [Install]
    WantedBy=multi-user.target

and enable it:

    # systemctl enable ntp-once

## 作为守护进程运行

### 启动 ntpd

启动：

    # systemctl start ntpd

开机启动：

    # systemctl enable ntpd

或者使用：

    # timedatectl set-ntp 1

### NetworkManager

Note: ntpd should still be running when the network is down if the hwclock daemon is disabled, so you should not use this.

ntpd can be brought up/down along with a network connection through the use of NetworkManager's dispatcher scripts. You can install the needed script from [community]:

    # pacman -S networkmanager-dispatcher-ntpd

### Running in a chroot

Note: Before attempting this, complete the previous section on running as non-root, since chroots are relatively useless at securing processes running as root.

Edit `/etc/conf.d/ntpd.conf` and change

    NTPD_ARGS="-g -u ntp:ntp"

to

    NTPD_ARGS="-g -i /var/lib/ntp -u ntp:ntp"

Then, edit `/etc/ntp.conf` to change the driftfile path such that it is relative to the chroot directory, rather than to the real system root. Change:

    driftfile       /var/lib/ntp/ntp.drift

to

    driftfile       /ntp.drift

Create a suitable chroot environment so that getaddrinfo() will work by creating pertinent directories and files (as root):

    # mkdir /var/lib/ntp/etc /var/lib/ntp/lib /var/lib/ntp/proc
    # touch /var/lib/ntp/etc/resolv.conf /var/lib/ntp/etc/services

and by bind-mounting the aformentioned files:

    /etc/fstab

    ...
    #ntpd chroot mounts
    /etc/resolv.conf  /var/lib/ntp/etc/resolv.conf none bind 0 0
    /etc/services	  /var/lib/ntp/etc/services none bind 0 0
    /lib		          /var/lib/ntp/lib none bind 0 0
    /proc		  /var/lib/ntp/proc none bind 0 0

    # mount -a

Finally, restart the daemon again:

    # rc.d restart ntpd

It is relatively difficult to be sure that your driftfile configuration is actually working without waiting a while, as ntpd does not read or write it very often. If you get it wrong, it will log an error; if you get it right, it will update the timestamp. If you do not see any errors about it after a full day of running, and the timestamp is updated, you should be confident of success.

## Alternatives

Available alternative to NTPd are Chrony, a dial-up friendly and specifically designed for systems that are not online all the time, and OpenNTPD, part of the OpenBSD project and currently not maintained for Linux.

## 参见

- Time (简体中文) (更多关于计算机计时的信息)

## 外部链接

- http://www.ntp.org/
- http://support.ntp.org/
- http://www.pool.ntp.org/
- http://www.eecis.udel.edu/~mills/ntp/html/index.html
- http://www.akadia.com/services/ntp_synchronize.html

Categories:

- Networking (简体中文)
- Daemons and system services (简体中文)
- 简体中文