#!/usr/bin/env python3 """Technitium DNS admin helper for the forgeway DNS work. Credentials come from `pass` inside this process; the session token is kept in memory and sent as a form field. Nothing secret is ever printed or put on a command line. tech.py zones tech.py records tech.py add-cname tech.py add-a tech.py add-zone # primary zone tech.py delete = lounge | serenity (primary Technitium at each site) """ from __future__ import annotations import json import subprocess import sys import urllib.parse import urllib.request PRIMARY = { "lounge": ("http://172.19.1.202:5380", "technitium/lounge/ns1-admin-password"), "serenity": ("http://172.24.1.202:5380", "technitium/serenity/ns1-admin-password"), # secondaries, for resync / inspection only — never add records here "lounge-ns2": ("http://172.19.10.202:5380", "technitium/lounge/ns2-admin-password"), "serenity-ns2": ("http://172.24.10.202:5380", "technitium/serenity/ns2-admin-password"), } def _pass(entry: str) -> str: return subprocess.run(["pass", entry], capture_output=True, text=True, check=True).stdout.strip() class Tech: def __init__(self, site: str): self.base, entry = PRIMARY[site] self.token = self._call("/api/user/login", {"user": "admin", "pass": _pass(entry)}, auth=False)["token"] def _call(self, path: str, params: dict, auth: bool = True) -> dict: if auth: params = {**params, "token": self.token} data = urllib.parse.urlencode(params).encode() req = urllib.request.Request(f"{self.base}{path}", data=data, method="POST") with urllib.request.urlopen(req, timeout=20) as r: body = json.loads(r.read().decode()) if body.get("status") != "ok": raise SystemExit(f"{path}: {body.get('status')} {body.get('errorMessage', '')}") # login puts its fields (incl. token) at the top level; everything else nests under "response" return body.get("response", body) def zones(self) -> list[dict]: return self._call("/api/zones/list", {})["zones"] def records(self, zone: str) -> list[dict]: return self._call("/api/zones/records/get", {"domain": zone, "zone": zone, "listZone": "true"})["records"] def add(self, zone: str, name: str, rtype: str, **kw) -> dict: fqdn = zone if name in ("@", "") else f"{name}.{zone}" return self._call("/api/zones/records/add", {"domain": fqdn, "zone": zone, "type": rtype, "ttl": "300", **kw}) def delete(self, zone: str, name: str, rtype: str, **kw) -> dict: fqdn = zone if name in ("@", "") else f"{name}.{zone}" return self._call("/api/zones/records/delete", {"domain": fqdn, "zone": zone, "type": rtype, **kw}) def add_zone(self, zone: str) -> dict: return self._call("/api/zones/create", {"zone": zone, "type": "Primary"}) def main(argv: list[str]) -> int: if len(argv) < 3: print(__doc__) return 2 site, cmd, args = argv[1], argv[2], argv[3:] t = Tech(site) if cmd == "zones": for z in sorted(t.zones(), key=lambda z: z["name"]): print(f"{z['name']:45s} {z['type']:10s} {'DISABLED' if z.get('disabled') else ''}") elif cmd == "records": for r in t.records(args[0]): rd = r.get("rData", {}) val = rd.get("ipAddress") or rd.get("cname") or rd.get("nameServer") or json.dumps(rd)[:80] print(f"{r['name']:50s} {r['type']:6s} ttl={r['ttl']:<6} {val}") elif cmd == "add-cname": print(json.dumps(t.add(args[0], args[1], "CNAME", cname=args[2]).get("addedRecord", {}))[:200]) elif cmd == "add-a": print(json.dumps(t.add(args[0], args[1], "A", ipAddress=args[2]).get("addedRecord", {}))[:200]) elif cmd == "add-zone": print(json.dumps(t.add_zone(args[0]))[:200]) elif cmd == "api": # generic read: tech.py api /api/zones/options/get zone=x [key ...] path, params, keys = args[0], {}, [] for a in args[1:]: (params.__setitem__(*a.split("=", 1)) if "=" in a else keys.append(a)) out = t._call(path, params) print(json.dumps({k: out.get(k) for k in keys} if keys else out, indent=1)[:3000]) elif cmd == "logtail": # /api/logs/download returns plain text, not JSON: tech.py logtail [n] params = urllib.parse.urlencode({"fileName": args[0], "limit": 5000, "token": t.token}).encode() req = urllib.request.Request(f"{t.base}/api/logs/download", data=params, method="POST") with urllib.request.urlopen(req, timeout=30) as r: lines = r.read().decode(errors="replace").splitlines() n = int(args[1]) if len(args) > 1 else 40 print("\n".join(l[:230] for l in lines[-n:])) elif cmd == "resync": # secondary zone: pull a fresh copy from its primary now instead of # waiting for the SOA refresh timer print(json.dumps(t._call("/api/zones/resync", {"zone": args[0]}))[:200]) elif cmd == "delete": zone, name, rtype, value = args key = "cname" if rtype == "CNAME" else "ipAddress" print(json.dumps(t.delete(zone, name, rtype, **{key: value}))[:200]) else: print(__doc__) return 2 return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv))