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

标签 python linux ntp

我正在寻找一种方法来输出 NTP 的当前状态(例如启用/禁用)和为系统设置的当前 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 或其他操作系统)

祝你的代码好运!

关于python - 使用 Python 显示同步的 NTP 对等服务器源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70248563/

相关文章:

python - 使用 set()/setp() 设置 matplotlib 中的未知属性

python - 如何从没有特定字符的文本文件中打印一行

linux - ssh keygen 权限被拒绝

ntp - 通过运行命令 sudo ntpd -gq 使用 ntp 同步时出错

c - 确定 (S)NTP 数据包的目标时间戳?

linux - NTP - 时钟未同步到低层服务器

Python 断言属性集

python - 如何在 plone.app.testing 中添加 Members 文件夹?

Python:如何获取一个用户名的组 id(如 id -Gn )

linux - 在 Linux 上使用 AF_LOCAL 或 AF_UNIX 套接字进行多播?