如何在Ubuntu中使用NTP服务器同步时间

时间:2020-03-05 15:29:49  来源:igfitidea点击:

NTP(网络时间协议)是一种协议,它将系统的时间与在线NTP服务器同步到仅几毫秒的准确性。
NTP在UDP端口123上侦听。
在本文中,我们将看到如何在Ubuntu 18.04中使用NTP服务器同步时间,也应该在Ubuntu 16.04上工作。

由于时钟频率的小不一致,系统时间和硬件时间都可以分开。
随着时间的推移,这些漂移积聚,导致显着的时间差异,这可能导致诸如Cron等工具的问题,并在文件上检查时间戳。

如何安装ntp服务器

要在Ubuntu系统上安装NTP服务器,请打开终端并运行以下命令:

apt-get install ntp

要验证安装顺利进行,请运行

dpkg -l | grep "ntp"

输出

ii  ntp                              1:4.2.8p4+dfsg-3ubuntu5.8                  amd64        Network Time Protocol daemon and utility programs

之后,使用以下命令更新系统

apt-get update

在成功更新系统后,验证NTP是否正在使用以下命令运行

systemctl status ntp

要验证NTP是否正常运行以下命令

ntpq -p

此命令查询并显示已连接NTPD的NTP服务器池。

输出

如何使用NTP强制时钟更新

有时,我们可能会遇到一个没有电池支持的实时时钟的系统,时间同步成为问题。
在这种情况下,我们可能需要强制时钟更新,以便在没有任何时间滞后的情况下,系统时间是同步的。
而不是运行已过度的ntpdate命令,而是运行下面的命令。

首先,停止NTP服务

systemctl stop ntp

在下面运行命令

ntpd -gq

输出

"-GQ"选项告诉NTP守护程序以立即无关纠正时间(g)并立即退出(q)。

最后,启动NTP服务

systemctl start ntp

使用timedatecl&timesyncd

NTPDate在Ubuntu的早期版本中逐步淘汰,并支持TimedAtectl。
检查时间状态运行

timedatectl

输出

root@ip-172-31-41-251:/home/ubuntu# timedatectl status
      Local time: Mon 2016-04-09 18:59:18 UTC
  Universal time: Mon 2016-04-09 18:59:18 UTC
        RTC time: Mon 2016-04-09 18:59:17
       Time zone: Etc/UTC (UTC, +0000)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

用于获取TimedAtectl和Timeyncd的时间的名称服务器在`/etc/systemd/timeyyncd.conf中找到

可以在"/etc/systemd/timeynd.conf.d"中找到其他配置文件

我们可以使用的另一种方法可以使用SNTP设置系统时间,如下所示。

sntp -s 24.56.178.140

-s标志代表NTP服务器后的地址。
随时使用任何NTP服务器地址。

最后,我们还可以忽略恐慌阈值,默认为1000秒。
这可以通过以下方式进行:

  • 编辑/etc/default/ntp并确保存在-g选项。
  • 编辑"/etc/ntp.conf",并在顶部置于"修补恐慌0"

当在配置文件上进行更改时,请确保重新加载NTP服务。

systemctl restart ntp