oracle7-slim / workbench /machine_probe.py
psiloceyeben's picture
Release 12.0 (slim): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
6e2225f verified
Raw History Blame Contribute Delete
6.48 kB
# 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))