aboutsummaryrefslogtreecommitdiffstats
path: root/hosts/hosts.py
blob: 0d1b66470108aab297e31e738d87208883d5f3be (plain)
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/python3
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

"""The LAN map as JSON: one entry per host note in the vault, each carrying
the ~/.ssh/config aliases that point at it, plus one entry per alias that
points at no note, so every alias the rofi menu listed is still here.

    hosts.py           print the list
    hosts.py --probe   print {name: reachable} for the same list
    hosts.py --check   run the self-check

Each entry carries a `group`: the Proxmox node it runs on, its own name if
other notes name it as their node, "Devices" for anything else on a private
address, "Remote" for the rest.
"""

import ipaddress
import json
import os
import socket
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import urlsplit

VAULT = os.environ.get(
    "HOSTS_DIR", "~/Documents/Obsidian/my KB/Knowledge base/Local Network/services")
SSH_CONFIG = "~/.ssh/config"


def frontmatter(text):
    """The `key: value` lines between the first two `---` lines."""
    # ponytail: flat scalars only, no yaml lib; a list value stays its raw
    # string, which is fine for the fields read here.
    lines = text.splitlines()
    if not lines or lines[0].strip() != "---":
        return {}
    out = {}
    for line in lines[1:]:
        if line.strip() == "---":
            break
        key, sep, value = line.partition(":")
        if sep and key.strip() and not key.startswith(" "):
            out[key.strip()] = value.strip().strip("\"'")
    return out


def ssh_hosts(text):
    """Aliases in an ssh config: {alias, hostname, user, port}."""
    # ponytail: plain "Keyword value" lines only, like blackpearl-sshmenu.sh;
    # Include and Match are not followed, wildcard Host patterns are skipped.
    hosts, cur = [], None
    for line in text.splitlines():
        parts = line.split(None, 1)
        if len(parts) < 2 or parts[0].startswith("#"):
            continue
        key, value = parts[0].lower(), parts[1].strip()
        if key == "host":
            name = value.split()[0]
            cur = None if any(c in name for c in "*?") else {
                "alias": name, "hostname": name, "user": "", "port": ""}
            if cur:
                hosts.append(cur)
        elif cur and key in ("hostname", "user", "port"):
            cur[key] = value
    return hosts


def merge(notes, aliases):
    """notes: [(title, frontmatter)]. Each alias joins the first note whose ip
    or hostname is its HostName, or whose short hostname is the alias."""
    out = []
    for title, fm in notes:
        out.append({
            "name": title,
            "ip": fm.get("ip", ""),
            "port": fm.get("port", ""),
            "url": fm.get("url", ""),
            "hostname": fm.get("hostname", ""),
            "node": fm.get("node", ""),
            "ct_id": fm.get("ct_id", ""),
            "aliases": [],
            "user": "",
        })
    for a in aliases:
        target = a["hostname"]
        host = next((h for h in out if target and target in (h["ip"], h["hostname"])
                     or a["alias"] == h["hostname"].split(".")[0]), None)
        if host:
            host["aliases"].append(a["alias"])
            host["user"] = host["user"] or a["user"]
        else:
            out.append({
                "name": a["alias"], "ip": target, "port": a["port"], "url": "",
                "hostname": target, "node": "", "ct_id": "",
                "aliases": [a["alias"]], "user": a["user"],
            })
    return group(out)


def private(ip):
    try:
        return ipaddress.ip_address(ip).is_private
    except ValueError:
        return False


def group(hosts):
    """Set each host's group and sort: nodes in name order, each with its own
    card first, then Devices, then Remote."""
    nodes = sorted({h["node"] for h in hosts if h["node"]})
    for h in hosts:
        h["group"] = (h["node"] or (h["name"] if h["name"] in nodes else "")
                      or ("Devices" if private(h["ip"]) else "Remote"))
    order = nodes + ["Devices", "Remote"]
    # sorted() is stable, so within a group the note order holds.
    return sorted(hosts, key=lambda h: (order.index(h["group"]),
                                        h["name"] != h["group"]))


def target(h):
    """What to probe: (host, tcp port), port None meaning ICMP. A service is
    up when its port answers, not merely when its CT does."""
    url = urlsplit(h["url"]) if h["url"] else None
    port = h["port"] or (url and (url.port or {"http": 80, "https": 443}.get(url.scheme)))
    return h["ip"] or h["hostname"], int(port) if port else None


def reachable(h):
    host, port = target(h)
    if not host:
        return False
    if port:
        try:
            socket.create_connection((host, port), timeout=1).close()
            return True
        except OSError:
            return False
    return subprocess.run(["ping", "-c1", "-W1", host], stdout=subprocess.DEVNULL,
                          stderr=subprocess.DEVNULL).returncode == 0


def probe(hosts):
    # ponytail: one thread per host, ~1s for the whole list; a pool cap
    # if the list ever reaches the hundreds.
    with ThreadPoolExecutor(max_workers=max(1, len(hosts))) as pool:
        return dict(zip((h["name"] for h in hosts), pool.map(reachable, hosts)))


def load():
    notes = [(p.stem, frontmatter(p.read_text(errors="replace")))
             for p in sorted(Path(VAULT).expanduser().glob("*.md"))]
    cfg = Path(SSH_CONFIG).expanduser()
    aliases = ssh_hosts(cfg.read_text(errors="replace")) if cfg.exists() else []
    return merge(notes, aliases)


def main():
    hosts = load()
    json.dump(probe(hosts) if "--probe" in sys.argv else hosts, sys.stdout)


def check():
    fm = frontmatter("---\ntags: [a, b]\nip: 10.0.0.7\nport: 5000\n"
                     "node: HP server\n---\nbody: not this\n")
    assert fm == {"tags": "[a, b]", "ip": "10.0.0.7", "port": "5000",
                  "node": "HP server"}, fm
    assert frontmatter("no frontmatter\n") == {}

    cfg = ssh_hosts("Host *\n  User x\nHost box\n  HostName 10.0.0.7\n"
                    "  User root\nHost web\n  HostName web.example.org\n"
                    "Host lone\n  Port 2222\n")
    assert [h["alias"] for h in cfg] == ["box", "web", "lone"], cfg
    assert cfg[0]["user"] == "root" and cfg[2]["port"] == "2222"

    hosts = merge([("Box", fm), ("Web", {"hostname": "web.example.org"}),
                   ("Media", {"ip": "10.0.0.9", "hostname": "media.example.org"})],
                  cfg + ssh_hosts("Host media\n  HostName 10.0.0.99\n"))
    by = {h["name"]: h for h in hosts}
    assert by["Box"]["aliases"] == ["box"] and by["Box"]["user"] == "root"
    assert by["Web"]["aliases"] == ["web"]
    assert by["Media"]["aliases"] == ["media"], "short hostname match"
    assert by["lone"]["port"] == "2222" and by["lone"]["node"] == ""
    assert len(hosts) == 4
    assert by["lone"]["group"] == "Remote" and by["Box"]["group"] == "HP server"

    g = group([{"name": "dev", "node": "", "ip": "10.0.0.3"},
               {"name": "svc", "node": "N", "ip": "10.0.0.4"},
               {"name": "far", "node": "", "ip": "example.org"},
               {"name": "N", "node": "", "ip": "10.0.0.2"}])
    assert [(h["name"], h["group"]) for h in g] == [
        ("N", "N"), ("svc", "N"), ("dev", "Devices"), ("far", "Remote")], g

    t = lambda **kw: target({"ip": "", "hostname": "", "port": "", "url": "", **kw})
    assert t(ip="10.0.0.7", port="5000") == ("10.0.0.7", 5000)
    assert t(ip="10.0.0.7", url="https://x.example.org") == ("10.0.0.7", 443)
    assert t(ip="10.0.0.7", url="http://x.example.org:81") == ("10.0.0.7", 81)
    assert t(hostname="example.org") == ("example.org", None)
    print("ok")


if __name__ == "__main__":
    check() if "--check" in sys.argv else main()