使用 Python 显示同步的 NTP 对等服务器源

Display synchronized NTP peer server source using Python

我正在寻找一种方法来输出 NTP 的当前状态(例如 enabled/disabled)和为系统设置的当前 NTP 源。

我在列出 NTP 源时遇到了困难,而没有调用 ntpstat 之类的东西,服务器上可能存在也可能不存在。

使用以下方法很容易找到 NTP 状态:

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

有没有办法输出同步的NTP服务器(例如同步到NTP服务器(5.196.181.37)?

如果您使用的是Ubuntu,您可以使用:

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

NOTE - Tested on Ubuntu 20.04, using Python 3.8

如果您只需要服务器和服务器名称,请使用 timedatectl show-timesync

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])

输出:

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

这是获取更多NTP信息的函数;您可以根据需要捕获输出并解析它:

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", ])

输出:

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

(ntpstatntpq 附带我的 CentOS 7 版本,所以我猜你可能正在使用 Debian 或其他 OS)

祝您代码顺利!