Ubuntu 安装 ntp 客户端 ntpdate 和 ntp 服务器

  1. 1. Ubuntu 安装 ntp 客户端 ntpdate 和 ntp 服务器
    1. 1.1. 安装 ntpdate 客户端
      1. 1.1.1. 个人推荐的国内 ntp 服务器列表
    2. 1.2. 安装/配置/启动 ntp 服务器
      1. 1.2.1. 安装
      2. 1.2.2. 配置
      3. 1.2.3. 启动
      4. 1.2.4. 只监听 IPv4/6
      5. 1.2.5. not in sync, skipping this server
    3. 1.3. 参考资料

Ubuntu 安装 ntp 客户端 ntpdate 和 ntp 服务器

搭建 ntp 服务器方便局域网使用,省的每次对时都耗时多几秒。

安装 ntpdate 客户端

要要想做 ntp 服务器首先要保证自己的时间正确。

1
2
3
4
# 安装 ntp 客户端
sudo apt install ntpdate
# 对时并写入主板
sudo ntpdate -vu ntp.ntsc.ac.cn && sudo hwclock -w

个人推荐的国内 ntp 服务器列表

尽可能选择延迟最低的服务器作为首选服务器。

  • 国家授时中心
    ntp.ntsc.ac.cn

  • 中国授时
    cn.ntp.org.cn

安装/配置/启动 ntp 服务器

安装

1
sudo apt install ntp

配置

编辑/etc/ntp.conf可以修改 ntp 服务器配置,以下是我的配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 权限
restrict default kod nomodify notrap nopeer noquery <==拒绝 IPv4 的用户
restrict -6 default kod nomodify notrap nopeer noquery <==拒绝 IPv6 的用户
restrict 127.0.0.1 <==底下两个是默认值,放行本机来源
restrict -6 ::1
restrict 10.0.0.0 mask 255.0.0.0 nomodify <==放行局域网
restrict 192.168.0.0 mask 255.255.0.0 nomodify <==放行局域网

# 上层时间服务器
server ntp.ntsc.ac.cn prefer <==优先,国家授时中心
server cn.ntp.org.cn <==中国授时

# 预设时间差异分析档案与暂不用到的 keys 等,不需要更动它:
driftfile /var/lib/ntp/drift
keys /etc/ntp/keys

启动

保存配置文件后执行操作

1
2
3
4
# 编辑后启动服务
sudo service ntp start
# 查看服务状态,一般都会绑定 123 端口
sudo service ntp status

需要注意的是,如果时间差过大,将无法从上层服务器获取正确的时间

只监听 IPv4/6

编辑/etc/default/ntp修改NTPD_OPTS='-g'NTPD_OPTS='-g -4'是只监听 IPv4,同理修改为NTPD_OPTS='-g -6'为只监听 IPv6。

not in sync, skipping this server

如果刚搭建好的服务器从别的机器尝试同步时间出现这个错误不必担心,因为服务器时间尚未同步,可以静等一段时间再试,或者在 ntp 服务器上执行sudo ntpdate -vu ntp.ntsc.ac.cn,与上层服务器手动同步一次。

参考资料

  1. 鸟哥的 Linux 私房菜 – NTP 时间服务器

  2. https://unix.stackexchange.com/questions/415653/ntpd-configured-for-ipv6-not-binding-ipv6-port