Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Last active November 1, 2023 05:01
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaytaylor/60c8a4e22431c4271200cab68186deb7 to your computer and use it in GitHub Desktop.
Save jaytaylor/60c8a4e22431c4271200cab68186deb7 to your computer and use it in GitHub Desktop.
Use google.com timestamp to set Linux system clock (useful when proxies prevent NTP

set_system_clock_from_google.sh

Sets system time based on what is reported by google.com. Useful for cases where it is not possible to use the standard ntpdate command. For eample, if a Linux machine is on a network which is only able to reach the internet through an HTTP proxy.

Inspired by ryenus' answer @ https://superuser.com/a/807326/72342

Installation

# Download latest set_system_clock_from_google.sh script.
curl -sS --remote-name-all $( \
    curl -sS https://api.github.com/gists/60c8a4e22431c4271200cab68186deb7 \
        | jq -r '.files[].raw_url' \
        | grep -v '\/\._' \
)

# Set permissions and move to local sbin.
chmod a+x set_system_clock_from_google.sh
sudo chown root:root set_system_clock_from_google.sh
sudo mv set_system_clock_from_google.sh /usr/local/sbin/

Cronjob Scheduling

Here is a command to install a cronjob which syncs the system clock at the top of every hour:

(sudo crontab -l 2>/dev/null; echo '1 * * * * /usr/local/sbin/set_system_clock_from_google.sh') \
    | sudo crontab -

Verify installation

List all root cronjobs and verify the job has been added:

sudo crontab -l

Example output

1 * * * * /usr/local/sbin/set_system_clock_from_google.sh

Run or test it manually

Verbose output is available when the -v flag is passed.

/usr/local/sbin/set_system_clock_from_google.sh -v
#!/usr/bin/env bash
##
# @author Jay Taylor (https://jaytaylor.com)
#
# @date 2018-08-28
#
# @description Sets system time based on what is reported by google.com. Useful
# for cases when you have a Linux machine on a network which is only able to
# reach the internet through an HTTP proxy.
#
# Inspired by ryenus' answer @ https://superuser.com/a/807326/72342
#
set -o errexit
set -o pipefail
set -o nounset
if [ "${UID:-}" != '0' ]; then
echo "ERROR: $0 must be run as root" 1>&2
exit 1
fi
if [ "${1:-}" = '-v' ]; then
set -o xtrace
shift
fi
utc_stamp="$( \
curl --head -sS -H 'Cache-Control: no-cache' 'https://google.com/' \
| grep '^Date:' \
| cut -d' ' -f3-6 \
)Z"
if [ "${utc_stamp}" = 'Z' ]; then
echo 'ERROR: setting system clock aborted due to empty $utc_stamp var value' 1>&2
exit 1
fi
echo "INFO: setting system clock to: ${utc_stamp}" 1>&2
date -s "${utc_stamp}"
@EDortta
Copy link

EDortta commented Oct 22, 2018

Great!
This script indeed solved my problem of some servers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment