NTP同步方式在Linux下一般兩種:使用ntpdate命令直接同步和使用NTPD服務平滑同步。
使用ntpdate命令直接同步的方式存在風險,比如一些定時任務在已有時間內執行過,直接同步導致時間變回任務執行前的時間段,定時任務會重復執行。
使用NTPD服務平滑同步的方式不會讓一個時間點在一天內經歷兩次,而是平滑同步時間,它每次同步時間的偏移量不會太陡,是慢慢來的。
查看是否安裝NTP包
rpm -qa |grep ntp
如果有輸出ntp和ntpdate版本信息,即已安裝。
ntp 可用systemctl管理
# 查看服務狀態service ntpd status# 啟動ntpd服務systemctl start ntpd.service# 停止ntpd服務systemctl stop ntpd.service# 設置開機自啟動systemctl enable ntpd.service# 停止開機自啟動systemctl disable ntpd.service# 查看服務當前狀態systemctl status ntpd.service# 重新啟動服務systemctl restart ntpd.service# 查看所有已啟動的服務systemctl list-units –type=service
作為ntp客戶端,如何同步服務器端的時間?
以公用的一些時間同步服務器為例
systemctl stop ntpd # 使用ntpdate同步前需要關閉ntpd服務,不然會失敗ntpdate cn.pool.ntp.orgsystemctl enable ntpd.servicesystemctl start ntpd.service# cn.pool.ntp.org 中國開源免費NTP服務器# ntp1.aliyun.com 阿里云NTP服務器# ntp2.aliyun.com 阿里云NTP服務器# time1.aliyun.com 阿里云NTP服務器# time2.aliyun.com 阿里云NTP服務器
如何配置服務器作為內網內的時間同步服務器?(NTP服務器的配置)
配置內網NTP-Server(10.0.0.12)
配置NTPD服務的服務器需要能訪問外網,這里挑選了一臺可以訪問外網的Linux服務器配置內網的NTPD服務,作為NTP-Server,其他幾臺內網通過它來進行時間同步。
這里假設其IP為10.0.0.12,其他幾臺內網的服務器IP分別為10.0.0.13、10.0.0.14。
在配置NTPD服務之前,先手動同步一下時間
systemctl stop ntpd # 使用ntpdate同步前需要關閉ntpd服務,不然會失敗ntpdate cn.pool.ntp.orgsystemctl enable ntpd.servicesystemctl start ntpd.service
修改NTPD服務的配置文件/etc/ntp.conf
[root@localhost ~]# vim /etc/ntp.conf#和上層NTP服務器頻率誤差的記錄文件driftfile /var/lib/ntp/drift#對于默認的client拒絕所有操作,下面的restrict開通指定權限restrict default nomodify notrap nopeer noquery#允許本機地址的一切操作restrict 127.0.0.1restrict ::1#允許192.168.203段機器同步時間,指定可以和NTP通信的IP或者網段restrict 192.168.203.0 mask 255.255.255.0 nomodify notrap#遠程的同步時間服務器地址(需要同步外網時間必改)#prefer表示優先同步的主機server cn.pool.ntp.org preferserver ntp1.aliyun.com iburstserver ntp2.aliyun.com iburstserver ntp3.aliyun.com iburstserver ntp4.aliyun.com iburstserver ntp5.aliyun.com iburst#遠程時間服務器不可用時,以本地時間作為服務時間server 127.127.1.0#stratum指定層數,越小,離時間源,越近。 層級1為國際時間源服務器…fudge 127.127.1.0 stratum 10#允許上層服務器主動修改本機時間(需要同步外網時間必改)restrict cn.pool.ntp.org nomodify notrap noqueryrestrict ntp1.aliyun.com iburst nomodify notrap noqueryrestrict ntp2.aliyun.com iburst nomodify notrap noqueryrestrict ntp3.aliyun.com iburst nomodify notrap noqueryrestrict ntp4.aliyun.com iburst nomodify notrap noqueryrestrict ntp5.aliyun.com iburst nomodify notrap noqueryincludefile /etc/ntp/crypto/pw#指定日志文件logfile /var/log/ntp#指定日志級別,info、all、event三種可以選擇logconfig all#啟用公鑰加密#crypto#密鑰文件keys /etc/ntp/keys
設置ntp client客戶端配置文件
vim /etc/ntp.confserver 10.0.0.12
重啟ntp服務
[root@localhost /]# systemctl stop firewalld[root@localhost /]# setenforce 0[root@localhost /]# vim /etc/seLinux/configSELinux=disabled[root@localhost /]# systemctl restart ntpd
查看ntp服務同步狀況
ntpd -q