因为偶尔遇到由于各种原因,我们在使用ntpdate的时候无法成功的跟服务器同步时间的现象,而一般情况下我们对时间的精度要求都不是太高,所以想到可以使用根据HTTP头里面的信息来校时的做法。
之前看到一个使用php编写的脚本,但是考虑到很多机器是没有php环境的,因此选用shell来进行代码的编写,尽量保证通用。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#Set localtime based on server's http response time | |
#By Orange | |
host="www.google.com" | |
#server host name | |
timeout="5" | |
#acceptable time out for curl | |
proxyHost="" | |
proxyPort="" | |
proxyUser="" | |
proxyPass="" | |
#define proxy settings | |
export TIMEFORMAT=$'Time cost: %lR' | |
header=$((time curl --proxy "$proxyHost:$proxyPort" --proxy-user "$proxyUser:$proxyPass" --connect-timeout $timeout --silent --head $host) | tr -d '\r' 2>&1) | |
#command to get server's http response header | |
error_code=$? | |
if [[ $error_code -ne 0 ]]; then | |
echo "cUrl error on code $error_code" | |
exit $error_code | |
fi | |
#Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 | |
regex1="Date: ((Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-9]{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT)" | |
#Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 | |
regex2="Date: ((Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day, [0-9]{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT)" | |
#Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format | |
regex3="Date: ((Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) *[0-9]{1,2} [0-9]{1,2}:[0-9]{2}:[0-9]{2} [0-9]{4})" | |
#use regex to Match time in server's http response header | |
if [[ $header =~ $regex1 ]]; then | |
server_time=${BASH_REMATCH[1]} | |
#get date time | |
elif [[ $header =~ $regex2 ]]; then | |
server_time=${BASH_REMATCH[1]} | |
#get date time | |
elif [[ $header =~ $regex3 ]]; then | |
server_time=${BASH_REMATCH[1]} | |
#get date time | |
else | |
error_code=$? | |
echo "Get time from server failed! Error code $error_code" | |
exit $error_code | |
fi | |
#date_str=$(date --date="$server_time") | |
#convert date format | |
set_result=$(date -s "$server_time") | |
#set local time | |
error_code=$? | |
if [[ $error_code -ne 0 ]]; then | |
echo "Set time with date -s error on code $error_code" | |
exit $error_code | |
else | |
echo $set_result | |
regex="(Time cost: [0-9]*m[0-9]*\.[0-9]*s)" | |
if [[ $header =~ $regex ]]; then | |
echo ${BASH_REMATCH[1]} | |
fi | |
fi |
PS:这篇文章正好测试一下Gist插件,看看效果如何。