Tips Linux Dhclient Force Time Update
Introduction
Using
dhclient
exit hooks scripts allows to force an update of the system date using
ntp/ntpd
.
Similar to %FOREACH{"mytopic" in="TipsLinuxDhclientDynamicHostname"}%
$mytopic %NEXT{"mytopic"}%
dhclient
and its scripting capabilities on enter and exit hooks allows to react on dynamic network environments.
Provided you have root privileges this can be achieved by creating a script file
ntp_force_update
created in
/etc/dhcp/dhclient-exit-hooks.d/
(on Debian), which is sourced by
dhclient
after having updated/received its DHCP informations.
#!/bin/sh
# Filename: /etc/dhcp/dhclient-exit-hooks.d/ntp_force_update
# Purpose: Used by dhclient-script to set the time of the system
#
# Do not update hostname for virtual machine IP assignments
if [ "$interface" != "eth0" ] && [ "$interface" != "eth1" ] && [ "$interface" != "wlan0" ]
then
return
fi
if [ "$reason" != BOUND ] && [ "$reason" != RENEW ] && [ "$reason" != REBIND ] && [ "$reason" != REBOOT ]
then
return
fi
service ntp status >/dev/null 2>&1 &&
(
sleep 5 &&
service ntp stop &&
ntpd -qg ;
service ntp start;
touch /tmp/force_update
) &
systemctl status systemd-timesyncd.service >/dev/null 2>&1 &&
(
sleep 5 &&
systemctl status systemd-timesyncd.service stop &&
timedatectl ;
systemctl status systemd-timesyncd.service start;
touch /tmp/force_update
) &
Applying those code lines:
%FOREACH{"file" in="/etc/dhcp/dhclient-exit-hooks.d/ntp_force_update"}%
curl -s https://wiki.gsi.de/pub/Epics/TipsLinuxDhclientForceTimeUpdate/_etc_dhcp_dhclient-exit-hooks.d_ntp_force_update -o $file &&
dos2unix $file &&
chmod a+r $file
%NEXT{"file"}%
Local testing at the prompt:
dhclient
--
PeterZumbruch - 2018-05-02