Linux 服務(wù)器可以通過(guò)命令來(lái)進(jìn)行時(shí)間同步耻陕。
一诗宣、ntpdate
同步網(wǎng)絡(luò)時(shí)間
# 安裝 ntpdate
$ sudo yum install -y ntpdate
# 執(zhí)行時(shí)間同步
$ sudo ntpdate -u ntp.api.bz
NTP 常用服務(wù)器:
210.72.145.44 ................ 中國(guó)國(guó)家授時(shí)中心
ntp.api.bz ................... NTP服務(wù)器(上海)
time.nist.gov ............... 美國(guó)
ntp.fudan.edu.cn ............ 復(fù)旦
time.windows.com ............ 微軟公司授時(shí)主機(jī)(美國(guó))
asia.pool.ntp.org ............ 臺(tái)警大授時(shí)中心(臺(tái)灣)
經(jīng)測(cè)試中國(guó)國(guó)家授時(shí)中心與 NTP 上海服務(wù)器可以正常同步時(shí)間召庞,注意需要加上 -u
參數(shù)篮灼。
注意:若不加上 -u
參數(shù)诅诱,會(huì)提示:no server suitable for synchronization found娘荡;
-u
:從 man ntpdate
中可以看出 -u
參數(shù)可以越過(guò)防火墻與主機(jī)同步。
二央拖、通過(guò) Web 服務(wù)器同步
通過(guò) HTTP 的 HEAD 方法訪問(wèn) Web 服務(wù)器可以獲取到頭信息:
$ curl -I baidu.com
返回結(jié)果:
HTTP/1.1 200 OK
Date: Mon, 29 Jul 2019 17:37:34 GMT
Server: Apache
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: "51-47cf7e6ee8400"
Accept-Ranges: bytes
Content-Length: 81
Cache-Control: max-age=86400
Expires: Tue, 30 Jul 2019 17:37:34 GMT
Connection: Keep-Alive
Content-Type: text/html
其中,cURL 可以:
-
curl -x $proxy
指定代理服務(wù)器 -
curl -H 'Cache-Control: no-cache'
避免緩存
可以通過(guò)解析 Date
字段值來(lái)設(shè)置時(shí)間。由于 Date
字段值是 GMT 時(shí)間赢底,所以需要按 UTC 時(shí)間處理幸冻。
(一)顯示時(shí)間
1洽损、根據(jù)當(dāng)前區(qū)域設(shè)置顯示時(shí)間流码,后面?zhèn)魅氲臅r(shí)間需要以最后的 Z
來(lái)區(qū)分傳入的時(shí)間是否為 UTC 時(shí)間:
$ date -d "$(curl -H 'Cache-Control: no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)Z"
顯示為 CST 時(shí)間:
2019年 07月 30日 星期二 08:00:00 CST
2漫试、指定顯示 UTC 時(shí)間驾荣,后面?zhèn)魅氲臅r(shí)間不管最后是否帶有 Z
都被理解為 UTC 時(shí)間
$ date -ud "$(curl -H 'Cache-Control: no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)"
顯示為 UTC 時(shí)間:
2019年 07月 29日 星期一 18:14:36 UTC
(二)設(shè)置時(shí)間
1播掷、在時(shí)間后跟 Z
表示傳入的時(shí)間按 UTC 時(shí)間處理
$ sudo date -s "$(curl -H 'Cache-Control: no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)Z"
設(shè)置后回顯 CST 時(shí)間
2019年 07月 30日 星期二 02:19:16 CST
2、通過(guò) -u
指定為 UTC 時(shí)間眯亦,是否加 Z
都可以
$ sudo date -us "$(curl -H 'Cache-Control: no-cache' -sI baidu.com | grep '^Date:' | cut -d' ' -f3-6)"
設(shè)置后回顯 UTC 時(shí)間
2019年 07月 29日 星期一 18:19:53 UTC
參數(shù)說(shuō)明:
-s, --set=STRING
set time described by STRING
-u, --utc, --universal
print or set Coordinated Universal Time (UTC)
三、手工同步
1宫静、使用 date
命令查看當(dāng)前時(shí)間
結(jié)果如下:
Tue Jul 30 01:20:43 CST 2019
2、使用 date -s
設(shè)置當(dāng)前時(shí)間
$ sudo date -s '16:30:00'
結(jié)果如下:
Wed Feb 4 16:30:00 CST 2015
3捌袜、使用 date -s "YYYY-MM-DD hh:mm[:ss]"
如:
$ date -s "2015-02-04 16:30:00"
# 將時(shí)間寫入 BIOS 避免重啟失效
$ hwclock -w
四虏等、參考資料
(完)