為滿足多台伺服器時間同步需求,建立內部 NTP (Network Time Protocol) 伺服器可確保叢集、資料庫、日誌系統時間一致性。本文以 CentOS 5.6 為例,說明安裝、設定 /etc/ntp.conf、/etc/ntp/step-tickers、/etc/sysconfig/ntpd 完整流程。
yum install ntp.i* -y
# 預設限制:拒絕所有查詢、修改、陷阱、對等
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery # IPv6
# 允許本機完整存取
restrict 127.0.0.1
restrict -6 ::1
# 允許內部網段同步時間 (不允許修改伺服器設定)
restrict 10.0.0.0 mask 255.0.0.0 nomodify notrap
restrict 192.168.0.0 mask 255.255.0.0 nomodify notrap
# 上層公共 NTP 伺服器 (微軟時間伺服器範例)
restrict 207.46.232.182 mask 255.255.255.255 nomodify notrap noquery
server 207.46.232.182
# 本地時鐘作為後備 (stratum 10)
server 127.127.1.0 # local clock
fudge 127.127.1.0 stratum 10
# 頻率誤差記錄檔
driftfile /var/lib/ntp/drift
# 金鑰檔 (對稱金鑰加密驗證用)
keys /etc/ntp/keys
# 日誌檔
logfile /var/log/ntp.log
| 參數 | 效果 |
|---|---|
ignore | 拒絕所有 NTP 服務 (含時間查詢) |
noquery | 拒絕時間查詢 (ntpq, ntpdc),但允許時間同步 |
notrap | 拒絕 trap 遠端事件登錄 |
nomodify | 禁止客戶端修改伺服器參數 (如 ntpdc 設定指令),但允許時間同步 |
notrust | 拒絕未通過加密驗證的客戶端 |
nokod | 停用 KoD (Kiss-o'-Death) 封包,可能遭受 DoS 攻擊 |
207.46.232.182
127.127.1.0
NTP 服務啟動時會立即與此檔案列出的伺服器進行時間校正,避免啟動初期時間偏差過大。
SYNC_HWCLOCK=YES
啟用後,系統關機/定期會將系統時間寫入 BIOS (RTC),確保重開機後時間正確。
service ntpd start
chkconfig ntpd on
# 查看同步狀態
ntpq -p
# 輸出範例:
# remote refid st t when poll reach delay offset jitter
# *==============================================================================
# *time.windows.com 10.3.7.10 2 u 45 64 377 1.234 -0.567 0.123
# 127.127.1.0 .LOCL. 10 l 12 64 377 0.000 0.000 0.001
* 表示目前同步來源。st (stratum) 階層:1 為參考時鐘 (GPS/原子鐘),2 為直接連接 stratum 1,以此類推;本地時鐘設為 10 確保優先使用上層伺服器。reach 八進位連通歷史 (377 = 最近 8 次皆成功)。客戶端安裝 ntpdate 或 ntpd,指向內部 NTP 伺服器 IP 即可。
ntpdate -u 內部NTP_IP (一次性校時) 或設定 ntpd 持續同步。
開放 UDP 123 連接埠:
iptables -A INPUT -p udp --dport 123 -j ACCEPT