BDubs
BDubs

Reputation: 73

Display synchronized NTP peer server source using Python

I am looking for a way to output the current status of NTP (e.g. enabled/disabled) and the current NTP sources set for the system.

I am having a difficult time listing the NTP sources without calling out to something like ntpstat which may or may not exist on the server.

Finding the NTP status is easy enough using:

import pydbus 
timedated = pydbus.SystemBus().get(".timedate1") 
print(timedated.NTPSynchronized)

Is there a method to output the synchronized NTP Server (e.g. synchronized to NTP server (5.196.181.37)?

Upvotes: 3

Views: 847

Answers (1)

Rob G
Rob G

Reputation: 683

If you are using Ubuntu, you can use:

  • timedatectl
  • timedatectl show-timesync
  • systemctl status systemd-timesyncd --no-pager

NOTE - Tested on Ubuntu 20.04, using Python 3.8

Use timedatectl show-timesync if you just want the server and the server name:

import pexpect

command_output, exitstatus = pexpect.run("timedatectl show-timesync", withexitstatus=True)
print([line.strip() for line in command_output.decode(
    "unicode_escape").split("\n") if "ServerName=" in line])
print([line.strip() for line in command_output.decode(
    "unicode_escape").split("\n") if "ServerAddress=" in line])

Output:

['ServerName=ntp.ubuntu.com']
['ServerAddress=91.189.89.199']

Here's a function to get more NTP info; you can capture the output and parse it, as needed:

import pexpect

def run(list_of_commands):
    """Runs CLI commands. Exceptions must be handled by the instantiating module.
    :param list list_of_commands: A list of commands to run through the CLI.
    """
    for c in list_of_commands:
        print("Command: {0}".format(c))
        command_output, exitstatus = pexpect.run(c, withexitstatus=True)
        print(
            # For Python 2.x, use 'string_escape'. For Python 3.x, use 'unicode_escape'.
            # Do not use utf-8; Some characters, such as backticks, will cause exceptions
            "Output:\n{0}\nExit status: {1}\n".format(
                command_output.decode("unicode_escape").strip(), exitstatus))


run(["timedatectl",
     "timedatectl show-timesync",
     "systemctl status systemd-timesyncd --no-pager", ])

Output:

Command: timedatectl
Output:
Local time: Fri 2021-12-10 20:06:33 EST  
           Universal time: Sat 2021-12-11 01:06:33 UTC  
                 RTC time: Sat 2021-12-11 01:06:33      
                Time zone: America/New_York (EST, -0500)
System clock synchronized: yes                          
              NTP service: active                       
          RTC in local TZ: no
Exit status: 0

Command: timedatectl show-timesync
Output:
FallbackNTPServers=ntp.ubuntu.com
ServerName=ntp.ubuntu.com
ServerAddress=91.189.89.199
RootDistanceMaxUSec=5s
PollIntervalMinUSec=32s
PollIntervalMaxUSec=34min 8s
PollIntervalUSec=17min 4s
NTPMessage={ Leap=0, Version=4, Mode=4, Stratum=2, Precision=-24, RootDelay=1.144ms, RootDispersion=29.327ms, Reference=11FD22FB, OriginateTimestamp=Fri 2021-12-10 19:59:42 EST, ReceiveTimestamp=Fri 2021-12-10 19:59:42 EST, TransmitTimestamp=Fri 2021-12-10 19:59:42 EST, DestinationTimestamp=Fri 2021-12-10 19:59:42 EST, Ignored=no PacketCount=6, Jitter=46.493ms }
Frequency=18285308
Exit status: 0

Command: systemctl status systemd-timesyncd --no-pager
Output:
 systemd-timesyncd.service - Network Time Synchronization
     Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2021-12-10 19:42:36 EST; 27min ago
       Docs: man:systemd-timesyncd.service(8)
   Main PID: 544 (systemd-timesyn)
     Status: "Initial synchronization to time server 91.189.89.199:123 (ntp.ubuntu.com)."
      Tasks: 2 (limit: 2294)
     Memory: 1.2M
     CGroup: /system.slice/systemd-timesyncd.service
             └─544 /lib/systemd/systemd-timesyncd

Dec 10 19:42:36 stack-VirtualBox systemd[1]: Starting Network Time Synchronization...
Dec 10 19:42:36 stack-VirtualBox systemd[1]: Started Network Time Synchronization.
Dec 10 19:43:09 stack-VirtualBox systemd-timesyncd[544]: Initial synchronization to time server 91.189.89.199:123 (ntp.ubuntu.com).
Exit status: 0

(ntpstat and ntpq came with my version of CentOS 7, so I guessed that you may be using Debian or another OS)

Good luck with your code!

Upvotes: 4

Related Questions