NTP(Network Time Protocol) 是一种用于同步计算机系统时钟的协议。它通过互联网或其他网络将计算机的时钟与高精度的时间服务器同步,以确保所有系统都具有准确的时间。
在大多数 Linux 发行版中,可以使用包管理器安装 NTP 服务。
Debian/Ubuntu:
sudo apt update
sudo apt install ntp
CentOS/RHEL:
sudo yum install ntp
编辑 /etc/ntp.conf
文件,添加或修改以下内容:
# 指定 NTP 服务器
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
# 允许本地网络中的设备同步时间
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
Systemd (Debian/Ubuntu/CentOS/RHEL):
sudo systemctl start ntp
sudo systemctl enable ntp
原因:
解决方法:
sudo iptables -A INPUT -p udp --dport 123 -j ACCEPT
原因:
解决方法:
ntpd
的平滑调整功能,避免时间跳跃。在 /etc/ntp.conf
中添加:
tinker step 0.4
原因:
解决方法:
/etc/ntp.conf
文件的语法和权限。sudo journalctl -xe
以下是一个简单的 Python 脚本,用于检查当前系统时间并与 NTP 服务器同步:
import ntplib
from time import ctime
def sync_time():
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
print(f"Current time: {ctime(response.tx_time)}")
# 这里可以添加代码将响应时间设置为系统时间
if __name__ == "__main__":
sync_time()
通过以上步骤和示例代码,您可以有效地在 Linux 系统上配置和使用 NTP 服务来同步时间。
领取专属 10元无门槛券
手把手带您无忧上云