Last active
August 29, 2015 14:03
-
-
Save wzxjohn/532e8032605cebae7505 to your computer and use it in GitHub Desktop.
A simple script to synchronize time with any web server based on Date in HTTP response header
This file contains hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment