時區校正是相當重要的工作,若時區沒有正確對應,可能會出現驗證憑證問題、存取誤差以及安全性問題。

因此,可以透過 NTP 網路校正的方式來達到Linux多主機時間校正。

在校正前,先統一時區(可依照需求調整),例如 下方式 Linux 設定 UTC 及 台北(Asia/Taipei) 時區的方式

將時區設定為 UTC

sudo timedatectl set-timezone UTC 

將時區設定為台北

sudo timedatectl set-timezone Asia/Taipei

透過 date 查看目前時間。

date

以下使用的是CentOS 系統操作作為範例,提供兩種統一時區方式,只能擇一使用:

1.手動校正

透過以下指令即可手動校正時區,可調整校正的server來源

ntpdate time.windows.com

將校正加入 crontab,排程每10分鐘校正一次

*/10 * * * * /usr/sbin/ntpdate time.windows.com && hwcolck -w

2.使用NTP服務

使用 NTP (ntpd) 服務,由於服務已有自動校正功能,不必再透過 ntpdate + crontab 校正。

yum install ntp -y
vim /etc/ntp.conf

在 ntp.conf ,增加以下 CentOS Linux 預設的時區伺服器(iburst 為加速對時)

# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst

(若主機在台灣,可使用台灣的時區伺服器)

server tock.stdtime.gov.tw
server watch.stdtime.gov.tw
server time.stdtime.gov.tw
server clock.stdtime.gov.tw
server tick.stdtime.gov.tw

啟動ntpd服務

server ntpd start

設定開機啟動ntpd

systemctl enable ntpd

透過 watch 查看 nptd 目前的運作狀況及時間

watch ntpd -p

使用 ntpstat

CVT2HUGO: 查看目前狀況及多久會自動同步更新
> ntpstat

synchronised to NTP server (169.254.169.254) at stratum 3
   time correct to within 22 ms
   polling server every 1024 s

可透過 ```ntpq when 就是多少秒前有更新過時間, delay 是網路延遲多少 10^(-3)秒 offset 是補償多少 10^(-3)秒 jitter是Linux與Bios時間的誤差多少 10^(-3)秒

CVT2HUGO: -p``` 查看是否有跟上層聯繫
> ntpq -p

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*metadata.google 71.79.79.71      2 u  311 1024  377    0.682    0.311   0.294
+b335.cxs.pw     118.163.81.63    2 u  101 1024  377    7.829    0.135   0.242
-0.cl.ntp.edgeun 201.49.148.135   2 u  217 1024  377  232.330   -0.714   1.143
+242-184-213-49. 17.253.116.253   2 u 1021 1024  377    8.471    0.375   0.971
-www.flusengruen 131.188.3.221    2 u   95 1024  377  264.682   -1.062   0.885

如果要 A 主機提供其他主機校正,需要在 /etc/ntp.conf

CVT2HUGO: 開放其他主機IP連線,以及在 A主機開啟 port 123
sudo iptables -A INPUT -m udp -p udp --sport 123 -d 0/0 --dport 123 -j ACCEPT