Skip to content

Instantly share code, notes, and snippets.

@dogukancagatay
Created March 14, 2024 08:27
Show Gist options
  • Save dogukancagatay/56aa339b13beba69eb994021d9a52d98 to your computer and use it in GitHub Desktop.
Save dogukancagatay/56aa339b13beba69eb994021d9a52d98 to your computer and use it in GitHub Desktop.
Python script to force timedatectl NTP time sync
import socket
import struct
import subprocess
import time
REF_TIME_1970 = 2208988800 # Reference time
def get_ntp_time(addr="0.de.pool.ntp.org") -> int | None:
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
client.settimeout(5)
data = b"\x1b" + 47 * b"\0"
client.sendto(data, (addr, 123))
data, _ = client.recvfrom(1024)
if data:
t = struct.unpack("!12I", data)[10]
t -= REF_TIME_1970
return t
finally:
client.close()
return None
if __name__ == "__main__":
subprocess.run(["timedatectl", "set-ntp", "false"], capture_output=True)
t = get_ntp_time()
if t:
time.clock_settime(time.CLOCK_REALTIME, float(t))
subprocess.run(["hwclock", "--systohc"], capture_output=True)
subprocess.run(["timedatectl", "set-ntp", "true"], capture_output=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment