From f8e6c62461d4da85901224f2399fa1a86a8ab433 Mon Sep 17 00:00:00 2001 From: Evan Pratten Date: Wed, 8 May 2024 15:18:53 -0400 Subject: [PATCH] Add ntp-get --- scripts/ntp-get | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100755 scripts/ntp-get diff --git a/scripts/ntp-get b/scripts/ntp-get new file mode 100755 index 0000000..f9282c8 --- /dev/null +++ b/scripts/ntp-get @@ -0,0 +1,53 @@ +#! /usr/bin/env python3 +import argparse +import sys +import logging +import ntplib +from datetime import datetime + +logger = logging.getLogger(__name__) + +def main() -> int: + # Handle program arguments + ap = argparse.ArgumentParser(prog='ntp-get', description='A debugging tool for reading NTP server times.') + ap.add_argument("hosts", help="The NTP servers to query", nargs='+') + ap.add_argument("-f", "--format", help="The output format", choices=["unix", "iso", "human"], default="human") + ap.add_argument("--timeout", help="The query timeout", type=float, default=0.25) + ap.add_argument('-v', '--verbose', help='Enable verbose logging', action='store_true') + args = ap.parse_args() + + # Configure logging + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format='%(levelname)s: %(message)s', + ) + + # Figure out the longest hostname + max_host_len = max([len(host) for host in args.hosts]) + + # Create an NTP client + client = ntplib.NTPClient() + + # Query the NTP servers + for host in args.hosts: + try: + # Do query + logger.debug(f"Querying {host}") + response = client.request(host, timeout=args.timeout) + dt = datetime.fromtimestamp(response.tx_time) + logger.debug(f"Response from {host}: {dt}") + + # Display result + if args.format == "iso": + print(f"{host.rjust(max_host_len)}: {dt.isoformat()}") + elif args.format == "unix": + print(f"{host.rjust(max_host_len)}: {response.tx_time}") + elif args.format == "human": + print(f"{host.rjust(max_host_len)}: {dt.strftime('%Y-%m-%d %H:%M:%S & %fms')}") + except Exception as e: + logger.error(f"Failed to query {host}: {e}") + + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file