Skip to content

Instantly share code, notes, and snippets.

@wzxjohn wzxjohn/http_time.sh
Last active Aug 29, 2015

Embed
What would you like to do?
A simple script to synchronize time with any web server based on Date in HTTP response header
#!/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
You can’t perform that action at this time.