Created
January 30, 2024 17:43
-
-
Save rocka/c5a16116c23019081f89afe052031be5 to your computer and use it in GitHub Desktop.
A janky script to sync system time from various public APIs in case NTP is unusable
This file contains 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
[Unit] | |
Description=Sync system time from various network APIs | |
[Service] | |
User=root | |
Type=oneshot | |
ExecStart=/usr/local/lib/time-sync.sh |
This file contains 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 | |
function timestamp_to_time { | |
date -d "@$1" "+%F %T" | |
} | |
function time_to_timestamp { | |
date -d "$1" "+%s" | |
} | |
function timestamp_taobao { | |
local ts=$(curl -s 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp' | jq -r '.data.t') | |
echo $(( $ts / 1000 )) | |
} | |
function timestamp_tencent { | |
local ts=$(curl -s 'http://vv.video.qq.com/checktime?otype=json') | |
ts="${ts/QZOutputJson\=/}" | |
ts="${ts/\;/}" | |
echo "$ts" | jq -r '.t' | |
} | |
function timestamp_suning { | |
local ts=$(curl -s 'http://f.m.suning.com/api/ct.do' | jq -r '.currentTime') | |
echo $(( $ts / 1000 )) | |
} | |
function timestamp_suning_2 { | |
time_to_timestamp "$(curl -s 'http://quan.suning.com/getSysTime.do' | jq -r '.sysTime2')" | |
} | |
declare -a fns=( | |
timestamp_taobao | |
timestamp_tencent | |
timestamp_suning | |
timestamp_suning_2 | |
) | |
for fn in "${fns[@]}" | |
do | |
ts="-1" | |
echo "Trying API ${fn} ..." | |
ts=$("${fn}") | |
echo "Got timestamp: ${ts}" | |
if [ "${ts}" -gt "1700000000" ] | |
then | |
echo "Timestamp seems valid, set to system time ..." | |
date -s "@${ts}" | |
exit 0 | |
fi | |
done |
This file contains 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
[Unit] | |
Description=Run time-sync daily | |
[Timer] | |
OnCalendar=*-*-* 01:00:00 | |
Persistent=true | |
[Install] | |
WantedBy=timers.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment