|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import json |
| 4 | +import subprocess |
| 5 | + |
| 6 | + |
| 7 | +def run_command(command_list): |
| 8 | + |
| 9 | + result = subprocess.run( |
| 10 | + command_list, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL |
| 11 | + ) |
| 12 | + |
| 13 | + return result.stdout.decode("utf-8") |
| 14 | + |
| 15 | + |
| 16 | +def time_since_reset_to_seconds(part): |
| 17 | + # time since reset: 3D 08:06:47 |
| 18 | + _part = part.split(":") |
| 19 | + k = _part[0] |
| 20 | + |
| 21 | + # calc seconds |
| 22 | + try: |
| 23 | + v_h = _part[1] |
| 24 | + except IndexError: |
| 25 | + v_h = "0" |
| 26 | + try: |
| 27 | + v_m = _part[2] |
| 28 | + except IndexError: |
| 29 | + v_m = "0" |
| 30 | + try: |
| 31 | + v_s = _part[3] |
| 32 | + except IndexError: |
| 33 | + v_s = "0" |
| 34 | + |
| 35 | + v = 0 |
| 36 | + |
| 37 | + if "D" in v_h: |
| 38 | + v_h_part = v_h.split() |
| 39 | + v += int(v_h_part[0].replace("D", "")) * 86400 |
| 40 | + v += int(v_h_part[1]) * 3600 |
| 41 | + else: |
| 42 | + v += int(v_h) * 3600 |
| 43 | + |
| 44 | + v += int(v_m) * 60 |
| 45 | + |
| 46 | + v += int(v_s) |
| 47 | + |
| 48 | + v = str(v) |
| 49 | + |
| 50 | + return k, v |
| 51 | + |
| 52 | + |
| 53 | +# -------- first command --------------------------- |
| 54 | + |
| 55 | +output = run_command(["ntpq", "-c rv"]) |
| 56 | + |
| 57 | +parts = output.replace("\n", "").split(",") |
| 58 | + |
| 59 | +data_dict = {} |
| 60 | + |
| 61 | +for part in parts: |
| 62 | + if part.count("=") != 1: |
| 63 | + continue |
| 64 | + |
| 65 | + k, v = part.split("=") |
| 66 | + |
| 67 | + data_dict[k.strip()] = v.replace('"', "") |
| 68 | + |
| 69 | +# -------- second command --------------------------- |
| 70 | + |
| 71 | +output2 = run_command(["ntpq", "-c iostats 127.0.0.1"]) |
| 72 | + |
| 73 | +parts = output2.split("\n") |
| 74 | + |
| 75 | +for part in parts: |
| 76 | + if part.count(":") < 1: |
| 77 | + continue |
| 78 | + |
| 79 | + if "time since reset" in part: |
| 80 | + k, v = time_since_reset_to_seconds(part) |
| 81 | + |
| 82 | + elif part.count(":") > 1: |
| 83 | + continue |
| 84 | + |
| 85 | + else: |
| 86 | + k, v = part.split(":") |
| 87 | + |
| 88 | + k = k.strip().replace(" ", "_") |
| 89 | + |
| 90 | + data_dict[k] = v.strip().split()[0] |
| 91 | + |
| 92 | +# ---------------------------------------------------- |
| 93 | + |
| 94 | +result_dict = {"error": 0, "errorString": "", "version": 1, "data": data_dict} |
| 95 | + |
| 96 | +print(json.dumps(result_dict, indent=4, sort_keys=True)) |
0 commit comments