linux 下部署NTP服務器 時間同步

NTP 是網絡時間協議(Network Time Protocol)的簡稱,通過 udp 123 端口進行網絡時鐘同步

一、安裝

# 既可做服務端也可做客戶端
yum install -y ntp

# 開啓服務,讓其他客戶端與本機同步,注意防火牆狀態
systemctl start ntpd

# 開機自啓
systemctl enable ntpd

二、ntp 常用配置 /etc/ntp.conf

# 記錄和上級時間服務器的時間差異
driftfile /var/lib/ntp/drift

# ntp 日誌
logfile /var/log/ntp.log
# 日誌級別 all event info
logconfig all

# 設置默認策略,允許同步時間,不允許修改
restrict default nomodify notrap nopeer noquery

# 允許本機地址的一切操作,-6 爲 IPV6
restrict 127.0.0.1
restrict -6 ::1

# 允許網段內客戶端連接此服務器同步時間,但是拒絕讓他們修改服務器上的時間
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

# https://www.ntppool.org/zone/cn
# 利用 server 設定上層 NTP 服務器,可設置多個。prefer 表示優先
server s1b.time.edu.cn prefer

# 在 /ntp.conf 中定義的 server 都不可用時,將使用 local 時間作爲 ntp 服務提供給 ntp 客戶端。建議配置,否則 ntp 服務器無法與公網 ntp 服務器同步時,其客戶端也會無法同步
server  127.127.1.0
fudge  127.127.1.0 stratum 10

restrict 控制相關權限

# 格式:restrict [IP地址] mask [netmask_IP] [parameter]
# IP地址:可以是 default,指所有的 IP
# netmask_IP:子網掩碼
# parameter 有以下幾個:
## ignore  :拒絕所有類型的 NTP 聯機
## nomodify:客戶端不能使用 ntpc 與 ntpq 修改服務器的時間參數,但客戶端仍可通過這部主機來進行網絡校時
## noquery :客戶端不能夠使用 ntpq 與 ntpc 等來查詢時間服務器,等於不提供 NTP 的網絡校時
## notrap :不提供 trap 這個遠程事件登錄(remote event logging)的功能,用於遠程事件日誌記錄
## notrust :Client 除非通過認證,否則該 Client 來源將被視爲不信任網域,會拒絕沒有認證的客戶端
## nopeer :用於阻止主機嘗試與服務器對等,並允許欺詐性服務器控制時鐘
## kod : 向不安全的訪問者發送 Kiss-Of-Death 報文

三、使用

# 國家授時中心
210.72.145.44
# 阿里雲
ntp.aliyun.com

s1a.time.edu.cn 北京郵電大學
s1b.time.edu.cn 清華大學
s1c.time.edu.cn 北京大學
s1d.time.edu.cn 東南大學
s1e.time.edu.cn 清華大學
s2a.time.edu.cn 清華大學
s2b.time.edu.cn 清華大學
s2c.time.edu.cn 北京郵電大學
s2d.time.edu.cn 西南地區網絡中心
s2e.time.edu.cn 西北地區網絡中心
s2f.time.edu.cn 東北地區網絡中心
s2g.time.edu.cn 華東南地區網絡中心
s2h.time.edu.cn 四川大學網絡管理中心
s2j.time.edu.cn 大連理工大學網絡中心
s2k.time.edu.cn CERNET桂林主節點
s2m.time.edu.cn 北京大學
ntp.sjtu.edu.cn 202.120.2.101 上海交通大學

ntp 常用命令

ntpdate 命令參數

# 查看ntp版本
ntpq -c version

# 上層 ntp 的狀態
ntpq -p

# ntp 同步狀態
ntpstat

# 向 NTP 服務器同步自己的時間,需關閉 ntpd 服務,-u 指定使用無特權的端口發送數據包 -d 調試
ntpdate -u s1a.time.edu.cn

系統時鐘與硬件時鐘之間同步

# 設置硬件時鐘
# -w,--systohc
hwclock -w

# 設置系統時鐘
# -s, --hctosys
hwclock -s

# 修改配置文件方式
vim /etc/sysconfig/ntpd
# 將系統時間寫入BIOS,與 hwclock -w 效果相同
SYNC_HWCLOCK=yes

ntpd 與 ntpdate

ntpd 不僅僅是時間同步服務器,它還可以做客戶端與標準時間服務器進行同步時間,而且是平滑同步,並非ntpdate立即同步,在生產環境中慎用ntpdate,也正如此兩者不可同時運行。

時鐘的躍變,對於某些程序會導致很嚴重的問題。

四、關於定時同步

開機時自動同步可編輯 /etc/ntp/step-tickers 文件

vim /etc/ntp/step-tickers

# List of NTP servers used by the ntpdate service.

ntp.aliyun.com
time2.aliyun.com
ntp2.aliyun.com

定時同步可使用 crontab,添加定時任務

systemctl start crond

systemctl enable crond

# 添加
crontab –e

# 每兩個小時同步一次
0 */2 * * * ntpdate s2m.time.edu.cn && hwclock -w

# 查看
crontab –l

 

轉載:https://www.linuxidc.com/Linux/2019-04/157889.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章