feat: write the agent's hardware and software inventory into the device comments

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 12:13:23 +01:00
1 parent 76f12069b5
commit 1f338902a7
3 files changed
+121 -2

No files matched your search

+76
View File
@@ -7,11 +7,77 @@ written; the report lists what would change.
"""
import re
import time
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
from netbox_sync.core.clients import os_label
REPORT_START = "<!-- netbox-sync:inventory -->"
REPORT_END = "<!-- /netbox-sync:inventory -->"
def inventory_report(client):
"""Markdown hardware and software report of an agent scan, or ``""`` for other sources."""
if client.get("source") != "agent":
return ""
lines = ["## Inventar (NetBox Windows Agent)", ""]
for caption, value in (
("System", " ".join(part for part in (client.get("manufacturer"), client.get("model")) if part)),
("Seriennummer", client.get("serial")),
("Betriebssystem", " ".join(part for part in (client.get("os"), client.get("os_display_version"),
f"(Build {client['os_build']})" if client.get("os_build")
else "") if part)),
("CPU", f"{client['cpu']} ({client.get('cores') or '?'} Kerne)" if client.get("cpu") else ""),
("RAM", f"{client['memory'] / 1024 ** 3:.0f} GB" if client.get("memory") else ""),
("Erfasst", client.get("scanned_at") and time.strftime("%d.%m.%Y %H:%M", time.localtime(client["scanned_at"]))),
):
if value:
lines.append(f"- **{caption}:** {value}")
if client.get("disks"):
lines += ["", "### Datenträger"]
lines += [f"- {disk['model']} – {disk['size'] / 1e9:.0f} GB" + (f" – S/N {disk['serial']}" if disk.get("serial")
else "") for disk in client["disks"]]
if client.get("memory_modules"):
lines += ["", "### Arbeitsspeicher"]
lines += [f"- {item['bank'] or 'RAM'}: {item['capacity'] / 1024 ** 3:.0f} GB"
+ (f" {item['manufacturer']}" if item.get("manufacturer") else "")
+ (f" {item['part_number']}" if item.get("part_number") else "") for item in client["memory_modules"]]
software = client.get("software") or []
if software:
lines += ["", f"### Installierte Software ({len(software)})", "", "| Programm | Version | Hersteller |",
"|---|---|---|"]
lines += [f"| {_cell(item['name'])} | {_cell(item['version'])} | {_cell(item['publisher'])} |"
for item in software]
return "\n".join(lines)
def _cell(text):
return str(text or "").replace("|", "/").replace("\n", " ").strip()
def merge_report(comments, report):
"""Replace the managed report block in ``comments`` and keep everything written by hand."""
comments = comments or ""
block = f"{REPORT_START}\n{report}\n{REPORT_END}"
if REPORT_START in comments and REPORT_END in comments:
before, rest = comments.split(REPORT_START, 1)
after = rest.split(REPORT_END, 1)[1]
return f"{before}{block}{after}"
return f"{comments.rstrip()}\n\n{block}" if comments.strip() else block
def _without_timestamp(text):
"""The scan time changes every scan – it alone is no reason to update the report."""
return re.sub(r"^- \*\*Erfasst:\*\*.*$", "", text or "", flags=re.MULTILINE)
def _report_body(comments):
if REPORT_START in (comments or "") and REPORT_END in comments:
return comments.split(REPORT_START, 1)[1].split(REPORT_END, 1)[0].strip()
return None
def _noop(*_args, **_kwargs):
pass
@@ -191,6 +257,8 @@ class ClientSyncEngine:
if device is None:
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
+ (f" · S/N {serial}" if serial else ""))
if client.get("source") == "agent":
changes.append(f"Inventarbericht in den Kommentaren ({len(client.get('software') or [])} Programme)")
report["devices_created"] += 1
if dry_run:
if interfaces:
@@ -207,6 +275,9 @@ class ClientSyncEngine:
payload["serial"] = serial
if tenant_id:
payload["tenant"] = tenant_id
report_text = inventory_report(client)
if report_text:
payload["comments"] = merge_report("", report_text)
device = self.nb.dcim.devices.create(payload)
self.existing[name.casefold()] = device.id
elif not update_existing:
@@ -226,6 +297,11 @@ class ClientSyncEngine:
if tenant_id and related_id(device, "tenant") is None:
updates["tenant"] = tenant_id
changes.append("Mandant setzen")
report_text = inventory_report(client)
current = getattr(device, "comments", "") or ""
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
updates["comments"] = merge_report(current, report_text)
changes.append(f"Inventarbericht aktualisieren ({len(client.get('software') or [])} Programme)")
if updates:
report["devices_updated"] += 1
if not dry_run:
+7 -2
View File
@@ -276,8 +276,13 @@ def apply_scan(row, raw, now=None):
"source": raw.get("source", "winrm"),
"agent_version": raw.get("agent_version", ""),
"software_count": len(raw.get("software") or []),
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
for disk in raw.get("disks") or []],
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
"publisher": item.get("publisher", "")} for item in raw.get("software") or []],
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0),
"serial": disk.get("serial", "")} for disk in raw.get("disks") or []],
"memory_modules": [{"bank": item.get("bank", ""), "manufacturer": item.get("manufacturer", ""),
"part_number": item.get("part_number", ""), "capacity": int(item.get("capacity") or 0)}
for item in raw.get("memory_modules") or []],
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
})
+38
View File
@@ -222,3 +222,41 @@ def test_scan_runs_in_process(monkeypatch):
status = {row["host"]: row["status"] for row in results}
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
assert len(seen) == 3
def test_agent_software_goes_into_a_managed_comment_block():
nb, client = _setup()
raw = dict(RAW, source="agent", agent_version="0.2.0",
software=[{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"},
{"name": "A | B", "version": "", "publisher": ""}],
disks=[{"model": "Micron SSD", "size": 512105932800, "serial": "M1"}],
memory_modules=[{"bank": "DIMM 0", "manufacturer": "Samsung", "part_number": "M425", "capacity": 2 ** 34}])
agent_client = apply_scan(new_row("pc01.firma.local"), raw)
engine = ClientSyncEngine(nb)
engine.load_targets()
preview = engine.sync([agent_client], 1, 2, dry_run=True)
assert "Inventarbericht in den Kommentaren (2 Programme)" in preview["items"][0][1]
engine.sync([agent_client], 1, 2, dry_run=False)
device = nb.dcim.devices.records[0]
assert "| 7-Zip | 24.08 | Igor Pavlov |" in device.comments and "| A / B |" in device.comments
assert "Micron SSD – 512 GB – S/N M1" in device.comments and "DIMM 0: 16 GB Samsung M425" in device.comments
# Hand-written notes survive, an unchanged inventory (only a new scan time) is no update.
device.comments = "Notiz vom Admin\n\n" + device.comments
again = ClientSyncEngine(nb)
again.load_targets()
rescanned = dict(agent_client, scanned_at=agent_client["scanned_at"] + 3600)
assert again.sync([rescanned], 1, 2, dry_run=True)["devices_updated"] == 0
changed = dict(rescanned, software=rescanned["software"] + [{"name": "Firefox", "version": "140", "publisher": ""}])
report = again.sync([changed], 1, 2, dry_run=False)
assert "Inventarbericht aktualisieren (3 Programme)" in report["items"][0][1]
assert device.comments.startswith("Notiz vom Admin") and device.comments.count("<!-- netbox-sync:inventory -->") == 1
assert "| Firefox | 140 | |" in device.comments
def test_winrm_scan_leaves_comments_alone():
nb, client = _setup()
engine = ClientSyncEngine(nb)
engine.load_targets()
engine.sync([client], 1, 2, dry_run=False)
assert "comments" not in nb.dcim.devices.created[0]