# Ubuntu/Debian系统sudo apt updatesudo apt install linuxptp# CentOS/RHEL系统sudo yum install linuxptp# Fedora系统sudo dnf install linuxptp
确保你的网络接口支持硬件时间戳(PTP 需要硬件支持才能达到最高精度):
# 检查是否支持硬件时间戳ethtool -T eth0 # 将eth0替换为你的网络接口名
linuxptp提供了两个主要程序:
ptp4l:PTP 协议的实现
phc2sys:用于同步系统时钟和 PTP 硬件时钟 (PHC)
创建配置文件:
sudo vim /etc/ptp4l.conf
基本配置内容:
# 网络接口interface eth0# PTP模式,master表示主时钟,slave表示从时钟masterOnly 1 # 1为主时钟,0为从时钟# 时间源timeSource 0xA0# 优先级priority1 128priority2 128
sudo systemctl list-unit-files | grep -E 'chrony|ntp|timesyncd'
将列出来的服务全部关闭并禁用:
sudo systemctl stop ntp-systemd-netif.path ntp-systemd-netif.service ntp.service systemd-timesyncd.servicesudo systemctl disable ntp-systemd-netif.path ntp-systemd-netif.service ntp.service systemd-timesyncd.service
作为主时钟启动
# 启动ptp4l作为主时钟sudo ptp4l -i eth0 -m -S# 启动phc2sys同步系统时钟和硬件时钟sudo phc2sys -s eth0 -c CLOCK_REALTIME -w -m
作为从时钟启动
# 启动ptp4l作为从时钟sudo ptp4l -i eth0 -m -s# 启动phc2sys同步系统时钟和硬件时钟sudo phc2sys -s eth0 -c CLOCK_REALTIME -w -m
参数说明:
-i:指定网络接口
-m:输出详细日志
-S:作为主时钟运行
-s:作为从时钟运行
网卡地址假设为 enp6s0:
为了让 PTP 服务在系统启动时自动运行,可以创建 systemd 服务文件:
sudo nano /etc/systemd/system/ptp4l.service
文件内容:
[Unit]Description=PTP clock synchronization serviceAfter=network.target[Service]Type=simpleExecStart=/usr/sbin/ptp4l -i enp6s0 -m -S # 根据需要修改为主时钟或从时钟模式Restart=always[Install]WantedBy=multi-user.target
然后启动并设置开机自启:
sudo systemctl daemon-reloadsudo systemctl start ptp4lsudo systemctl enable ptp4l
为了让 PTP 服务在系统启动时自动运行,可以创建 systemd 服务文件:
sudo nano /etc/systemd/system/ptpphc2sys.service
文件内容:
[Unit]Description=PTP phc2sys serviceAfter=network.target[Service]Type=simpleExecStart=/usr/sbin/phc2sys -s enp6s0 -c CLOCK_REALTIME -w -mRestart=always[Install]WantedBy=multi-user.target
然后启动并设置开机自启:
sudo systemctl daemon-reloadsudo systemctl start ptpphc2syssudo systemctl enable ptpphc2sys
对phc2sys也做类似配置,创建对应的服务文件。
网卡地址假设为eth0:
为了让 PTP 服务在系统启动时自动运行,可以创建 systemd 服务文件:
sudo nano /etc/systemd/system/ptp4l.service
文件内容:
[Unit]Description=PTP clock synchronization serviceAfter=network.target[Service]Type=simpleExecStart=/usr/sbin/ptp4l -i eth0 -m -s # 根据需要修改为主时钟或从时钟模式Restart=always[Install]WantedBy=multi-user.target
然后启动并设置开机自启:
sudo systemctl daemon-reloadsudo systemctl start ptp4lsudo systemctl enable ptp4l
为了让 PTP 服务在系统启动时自动运行,可以创建 systemd 服务文件:
sudo nano /etc/systemd/system/ptpphc2sys.service
文件内容:
[Unit]Description=PTP phc2sys serviceAfter=network.target[Service]Type=simpleExecStart=/usr/sbin/phc2sys -s eth0 -c CLOCK_REALTIME -w -mRestart=always[Install]WantedBy=multi-user.target
然后启动并设置开机自启:
sudo systemctl daemon-reloadsudo systemctl start ptpphc2syssudo systemctl enable ptpphc2sys
对phc2sys也做类似配置,创建对应的服务文件。
可以使用以下命令检查 PTP 同步状态:
# 查看ptp4l状态sudo ptp4l -i eth0 -m -t# 检查时钟偏移sudo pmc -u -b 0 'GET PORT_DATA_SET'
通过以上步骤,你可以在 Linux 系统上配置 PTP 时钟同步,实现高精度的网络时间同步。根据你的需求,可以将某些节点配置为主时钟,其他节点配置为从时钟,以构建一个精确的时间同步网络。