Skip to content

Instantly share code, notes, and snippets.

@andkirby
Last active August 19, 2020 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andkirby/baf3778d7479f412188c0f81ae99b5a0 to your computer and use it in GitHub Desktop.
Save andkirby/baf3778d7479f412188c0f81ae99b5a0 to your computer and use it in GitHub Desktop.
Reset time on ssh login in a Unix system
########################################
# Reset time on login #
########################################
# you may try to use system last logged time: `last ${USER} -n1 | head -1 | awk '{print $4" "$5" "$6" "$7}'`
time_sync_command='sudo ntpdate -s time.nist.gov'
# max time not logged value
not_logged_max_time_h=6
if ! [[ -f ~/.last_login_time ]]; then
date > ~/.last_login_time
fi
# calculation
((last_time=$(date --date="$(cat ~/.last_login_time)" +%s), \
current_time=$(date --date="$(date)" +%s), \
tdiff=current_time-last_time, last_login_diff=tdiff/3600))
if [[ ${last_login_diff} -ge ${not_logged_max_time_h} ]]; then
echo 'Time sync (.bashrc)...'
${time_sync_command}
fi
date > ~/.last_login_time
@andkirby
Copy link
Author

andkirby commented Aug 19, 2020

For vagrant, please update Vagrantfile with following:

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
...
  # Sync up time with servers
  config.vm.provision(
    :shell,
    :inline => 'sudo ntpdate -s time.nist.gov && echo "VM time is up-to-date." || echo "ERROR: Cannot sync time." > /dev/stderr',
    run:    'always')
...
end

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