在 Debian 12 上使用 ntpd(Network Time Protocol Daemon)进行时间同步可以提供高精度和稳定的时间服务。以下是详细的设置步骤:

1. 安装 NTP 服务

首先,确保系统包是最新的,然后安装 ntp

1
2
sudo apt update
sudo apt install -y ntp

2. 配置 NTP 服务器

ntpd 的配置文件位于 /etc/ntp.conf。安装完成后,您可以编辑此文件以指定 NTP 服务器和调整其他设置。

1
sudo nano /etc/ntpsec/ntp.conf

在文件中找到以 poolserver 开头的行,这是默认的 NTP 服务器。可以将它们替换为您想要使用的 NTP 服务器。例如,使用公共的 NTP 服务器:

1
2
3
4
5
# 默认的服务器配置
pool 0.debian.pool.ntp.org iburst
pool 1.debian.pool.ntp.org iburst
pool 2.debian.pool.ntp.org iburst
pool 3.debian.pool.ntp.org iburst

选项说明

  • iburst:当服务器首次连接时,允许 ntpd 快速发送一组请求包,能加速初次同步速度。

如果有特定的本地服务器,也可以添加,例如:

1
2
server ntp.server1.com iburst
server ntp.server2.com iburst

3. 配置 NTP 访问权限(可选)

如果您不希望其他设备从您的服务器同步时间,可以限制访问权限。在 /etc/ntp.conf 中找到以下配置,并根据需求更改:

1
2
3
restrict default kod nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
  • restrict default 这一行的设置限制了对时间服务的访问,默认禁止所有远程查询。

4. 启动并启用 NTP 服务

完成配置后,启动 ntpd 服务,并将其设置为开机自动启动:

1
sudo systemctl enable --now ntp

5. 检查 NTP 状态

可以使用以下命令查看 ntpd 的运行状态和同步情况:

1
sudo systemctl status ntp

此外,可以使用 ntpq 命令来查看 NTP 服务器的同步状态:

1
ntpq -p

该命令将显示 NTP 服务器的列表以及延迟、抖动等信息。输出示例:

1
2
3
4
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*ntp.server1.com .GPS. 1 u 17 64 377 24.5 0.004 0.002
+ntp.server2.com .PPS. 1 u 21 64 377 25.0 0.010 0.008

其中 * 表示当前同步的服务器,+ 表示备选服务器。

6. 验证系统时间同步状态

使用以下命令确认系统时间是否已同步:

1
timedatectl status

如果显示 System clock synchronized: yes,则表示时间已成功同步。

7. 调整系统时间偏差(可选)

如果系统时间与 NTP 服务器时间有较大偏差,可以强制同步时间:

1
sudo ntpd -gq

此命令会强制同步时间后退出。-g 选项允许较大偏差的调整,而 -q 表示同步完成后退出。完成后重启 NTP 服务:

1
sudo systemctl restart ntp

这样,Debian 12 就会通过 ntpd 服务与指定的 NTP 服务器保持时间同步。