File size: 6,484 Bytes
6e2225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# Runs ON each server (piped over ssh stdin), prints one JSON object.
# Read-only: reads /proc, systemctl, ss, nginx -T, cert files, curls its own vhosts via 127.0.0.1.
import json, os, re, shutil, socket, subprocess, time, glob
from concurrent.futures import ThreadPoolExecutor

def sh(cmd, t=15):
    try:
        return subprocess.run(cmd, shell=False, capture_output=True, text=True, timeout=t).stdout
    except Exception:
        return ""

def meminfo():
    m = {}
    for line in open("/proc/meminfo"):
        k, v = line.split(":", 1)
        m[k] = int(v.split()[0]) * 1024
    return m

SYSTEM = re.compile(r"^(systemd-|dbus|ssh|cron|rsyslog|snapd|getty|serial-getty|user@|polkit|udisks|ModemManager|"
                    r"networkd-dispatcher|unattended-upgrades|multipathd|qemu-guest-agent|irqbalance|packagekit|"
                    r"fwupd|accounts-daemon|chrony|atd|upower|thermald|cloud-|hv-|open-vm|apport|lvm2|"
                    r"setvtrgb|keyboard-setup|console-setup|plymouth|rtkit|wpa_supplicant|NetworkManager|"
                    r"containerd|php.*-fpm|postfix|exim|uuidd|blk-availability|haveged|gpu-manager)")

def unit_of(pid):
    try:
        for line in open(f"/proc/{pid}/cgroup"):
            m = re.search(r"/([^/]+\.service)", line)
            if m:
                return m.group(1)
    except Exception:
        pass
    return None

out = {"probed_at": int(time.time()), "hostname": socket.gethostname()}
osr = dict(re.findall(r'^(\w+)="?([^"\n]*)"?', open("/etc/os-release").read(), re.M))
out["os"] = osr.get("PRETTY_NAME", "")
out["cpus"] = os.cpu_count()
cpu_model = re.search(r"model name\s*:\s*(.+)", open("/proc/cpuinfo").read())
out["cpu_model"] = cpu_model.group(1).strip() if cpu_model else ""
out["load"] = [float(x) for x in open("/proc/loadavg").read().split()[:3]]
mi = meminfo()
out["mem"] = {"total": mi["MemTotal"], "used": mi["MemTotal"] - mi["MemAvailable"],
              "swap_total": mi.get("SwapTotal", 0), "swap_used": mi.get("SwapTotal", 0) - mi.get("SwapFree", 0)}
du = shutil.disk_usage("/")
out["disk"] = {"total": du.total, "used": du.used, "free": du.free}
out["uptime_s"] = int(float(open("/proc/uptime").read().split()[0]))
out["reboot_required"] = os.path.exists("/var/run/reboot-required")

# services
running = sh(['systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain']).split("\n")
names = [l.split()[0] for l in running if l.strip()]
out["service_count"] = len(names)
failed = sh(['systemctl', 'list-units', '--type=service', '--state=failed', '--no-legend', '--plain']).split("\n")
out["failed"] = [l.split()[0] for l in failed if l.strip() and l.split()[0].endswith(".service")]

# listening ports -> owning unit
ports = {}
for l in sh(['ss', '-ltnpH']).split("\n"):
    parts = l.split()
    if len(parts) < 5:
        continue
    addr = parts[3]
    host, _, port = addr.rpartition(":")
    pid = re.search(r"pid=(\d+)", l)
    proc = re.search(r'\(\("([^"]+)"', l)
    unit = unit_of(pid.group(1)) if pid else None
    key = unit or (proc.group(1) if proc else "?")
    ports.setdefault(key, set()).add((int(port), host.strip("[]") in ("0.0.0.0", "*", "::")))

svcs = []
for n in names:
    if SYSTEM.match(n):
        continue
    p = sorted(ports.get(n, []))
    svcs.append({"name": n[:-8] if n.endswith(".service") else n,
                 "ports": [x[0] for x in p], "public": any(x[1] for x in p)})
out["services"] = svcs

# docker
dk = sh(['docker', 'ps', '--format', '{{.Names}}|{{.Image}}|{{.Ports}}|{{.Status}}'])
out["containers"] = [dict(zip(["name", "image", "ports", "status"], l.split("|"))) for l in dk.split("\n") if l.strip()]

# nginx vhosts
sites = {}
conf = sh(['nginx', '-T'], 20)
depth, block = 0, None
for raw in conf.split("\n"):
    line = raw.split("#", 1)[0].strip()
    if raw.startswith("# configuration file"):
        depth, block = 0, None
        continue
    if re.match(r"^server\s*\{", line) and block is None:
        block = {"names": [], "proxy": None, "ssl": False, "root": None, "start": depth}
    if block is not None:
        m = re.match(r"server_name\s+([^;]+);", line)
        if m:
            block["names"] += m.group(1).split()
        m = re.search(r"proxy_pass\s+https?://[^:/;]+:(\d+)", line)
        if m and not block["proxy"]:
            block["proxy"] = int(m.group(1))
        if re.match(r"listen\s+.*443", line):
            block["ssl"] = True
        m = re.match(r"root\s+([^;]+);", line)
        if m and not block["root"]:
            block["root"] = m.group(1)
    depth += line.count("{") - line.count("}")
    if block is not None and depth <= block["start"]:
        for n in block["names"]:
            if n in ("_", "localhost") or re.match(r"^[\d.]+$", n) or n.startswith("~"):
                continue
            s = sites.setdefault(n, {"domain": n, "port": None, "ssl": False, "static": False})
            s["port"] = s["port"] or block["proxy"]
            s["ssl"] = s["ssl"] or block["ssl"]
            s["static"] = s["static"] or (block["root"] is not None and not block["proxy"])
        block = None

def check(s):
    d = s["domain"]
    if len(d) > 253 or not re.fullmatch(
        r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.?", d
    ):
        s["code"] = None
        return s
    scheme, port = ("https", 443) if s["ssl"] else ("http", 80)
    code = sh(["curl", "-q", "-sk", "--noproxy", "*", "--proto", f"={scheme}", "-o", "/dev/null",
               "-w", "%{http_code}", "-m", "5", "--resolve", f"{d}:{port}:127.0.0.1",
               f"{scheme}://{d}/"], 8).strip()
    s["code"] = int(code) if code.isdigit() else 0
    return s

with ThreadPoolExecutor(12) as ex:
    out["sites"] = sorted(ex.map(check, list(sites.values())[:120]), key=lambda s: s["domain"])

# certs
certs = []
for c in glob.glob("/etc/letsencrypt/live/*/cert.pem"):
    end = sh(["openssl", "x509", "-enddate", "-noout", "-in", c]).strip().split("=", 1)[-1]
    try:
        days = int((time.mktime(time.strptime(end, "%b %d %H:%M:%S %Y %Z")) - time.time()) // 86400)
    except Exception:
        days = None
    certs.append({"name": c.split("/")[-2], "days_left": days})
out["certs"] = sorted(certs, key=lambda c: (c["days_left"] is None, c["days_left"] or 0))

print(json.dumps(out))