Skip to content

Instantly share code, notes, and snippets.

@cynicastic
Last active June 23, 2019 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cynicastic/ced78fac27de4394b67977802d76c0d9 to your computer and use it in GitHub Desktop.
Save cynicastic/ced78fac27de4394b67977802d76c0d9 to your computer and use it in GitHub Desktop.
Fetch time from ntp server (call from Asuswrt-Merlin init-start script)
#!/bin/sh
#
# Script: fetch-ntp
#
# script to get time from time server as quickly as possible
#
# this works best when the router is NOT the NTP server for your LAN,
# that is, the IP address you are pointing at here is the same IP
# address listed in the Administration -> System -> NTP Server
#
# if your router is the primary NTP server for your LAN, comment out
# the two NVRAM lines below to prevent issues with other services
#
# call from init-start as "/jffs/scripts/fetch-ntp ww.xx.yy.zz cc &"
# where ww.xx.yy.zz is IP address (duh!) and cc is number of seconds
# to loop; if cc is not specified, defaults to 60 seconds
# Do not use URL! use IP only so we don't wait for DNS to come up
# `&` at end is critical - spawns this as an asynchronous task and continues
# verify at least 1 parameter (hopefully the ip) passed, no other error checking
if [ "X$1" = "X" ]; then exit; fi
ntp_ip=$1
if [ "X$2" = "X" ]
then
cycles=60 # might as well have a default ...
else
cycles=$2
fi
count=$cycles
while [ $count -gt 0 ]
do
sleep 1 # give it a chance to wake up
count=`expr $count - 1`
if ping -w 1 -c 1 $ntp_ip > /dev/null 2>&1 # Give me a ping, Vasily. One ping only, please.
then
if /usr/sbin/ntpd -q -n -p $ntp_ip
then
logger -t "SCRIPT_$(basename $0)" "Time synced ($(date)) from $ntp_ip in `expr $cycles - $count` cycles"
nvram set ntp_ready=1 # comment out this line if ntp_id is not your primary NTP server for your LAN
nvram commit # comment out this line if ntp_id is not your primary NTP server for your LAN
exit 0
else
logger -t "SCRIPT_$(basename $0)" "FAILED to sync time from $ntp_ip! (valid ip)"
exit 1
fi
fi
done
logger -t "SCRIPT_$(basename $0)" "FAILED to find time server $ntp_ip in $cycles cycles!"
exit 1
#eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment