How to use ntpdate behind a proxy?

Expanding on the answer by carveone:

sudo date -s "$(wget -S  "http://www.google.com/" 2>&1 | grep -E '^[[:space:]]*[dD]ate:' | sed 's/^[[:space:]]*[dD]ate:[[:space:]]*//' | head -1l | awk '{print $1, $3, $2,  $5 ,"GMT", $4 }' | sed 's/,//')"

This seems like a clear case for tlsdate.

 tlsdate: secure parasitic rdate replacement

  tlsdate sets the local clock by securely connecting with TLS to remote
  servers and extracting the remote time out of the secure handshake. Unlike
  ntpdate, tlsdate uses TCP, for instance connecting to a remote HTTPS or TLS
  enabled service, and provides some protection against adversaries that try
  to feed you malicious time information.

I do not think i have ever seen so many recommendations to use unsanitized data from internet as an argument to a sudo invocation.

Github: https://github.com/ioerror/tlsdate


One Liner

Assuming environment variable http_proxy is already set:

sudo date -s "$(curl -H'Cache-Control:no-cache' -sI google.com | grep '^Date:' | cut -d' ' -f3-6)Z"

we can verify the retrieved date/time first:

# local  date/time
date -d "$(curl -HCache-Control:no-cache -sI google.com | grep '^Date:' | cut -d' ' -f3-6)Z"

# or UTC date/time
date -ud "$(curl -HCache-Control:no-cache -sI google.com | grep '^Date:' | cut -d' ' -f3-6)"    

Notes

Just in case, certain options might be needed for curl:

  • curl -x $proxy

    to explicitly set the proxy server to use, when the http_proxy environment variable is not set, default to protocol http and port 1080 (manual).

  • curl -H 'Cache-Control: no-cache'

    to explicitly disable caching, especially when used in a cron job and/or behind a proxy server.

Alternate form tested with RHEL 6 that uses the '-u' option to date instead of appending the "Z" to the output:

sudo date -u --set="$(curl -H 'Cache-Control: no-cache' -sD - http://google.com |grep '^Date:' |cut -d' ' -f3-6)"

BTW, google.com is preferred over www.google.com, because the former results in a 301 redirect response, which is much smaller (569 vs 20k+ characters) but still good to use.

Tags:

Proxy

Ntp

Ntpdate