Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6622cf48f | ||
|
|
1f338902a7 |
No files matched your search
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#define AppName "NetBox Synchronizer"
|
#define AppName "NetBox Synchronizer"
|
||||||
#ifndef AppVersion
|
#ifndef AppVersion
|
||||||
#define AppVersion "4.20.1"
|
#define AppVersion "4.20.2"
|
||||||
#endif
|
#endif
|
||||||
#define AppPublisher "Louis-Alexander Kerst"
|
#define AppPublisher "Louis-Alexander Kerst"
|
||||||
#define AppExeName "NetBoxSynchronizer.exe"
|
#define AppExeName "NetBoxSynchronizer.exe"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||||
|
|
||||||
APP_NAME = "NetBox Synchronizer"
|
APP_NAME = "NetBox Synchronizer"
|
||||||
APP_VERSION = "4.20.1"
|
APP_VERSION = "4.20.2"
|
||||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,77 @@ written; the report lists what would change.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
||||||
from netbox_sync.core.clients import os_label
|
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):
|
def _noop(*_args, **_kwargs):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -191,6 +257,8 @@ class ClientSyncEngine:
|
|||||||
if device is None:
|
if device is None:
|
||||||
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
|
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
|
||||||
+ (f" · S/N {serial}" if serial 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
|
report["devices_created"] += 1
|
||||||
if dry_run:
|
if dry_run:
|
||||||
if interfaces:
|
if interfaces:
|
||||||
@@ -207,6 +275,9 @@ class ClientSyncEngine:
|
|||||||
payload["serial"] = serial
|
payload["serial"] = serial
|
||||||
if tenant_id:
|
if tenant_id:
|
||||||
payload["tenant"] = 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)
|
device = self.nb.dcim.devices.create(payload)
|
||||||
self.existing[name.casefold()] = device.id
|
self.existing[name.casefold()] = device.id
|
||||||
elif not update_existing:
|
elif not update_existing:
|
||||||
@@ -226,6 +297,11 @@ class ClientSyncEngine:
|
|||||||
if tenant_id and related_id(device, "tenant") is None:
|
if tenant_id and related_id(device, "tenant") is None:
|
||||||
updates["tenant"] = tenant_id
|
updates["tenant"] = tenant_id
|
||||||
changes.append("Mandant setzen")
|
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:
|
if updates:
|
||||||
report["devices_updated"] += 1
|
report["devices_updated"] += 1
|
||||||
if not dry_run:
|
if not dry_run:
|
||||||
|
|||||||
@@ -276,8 +276,13 @@ def apply_scan(row, raw, now=None):
|
|||||||
"source": raw.get("source", "winrm"),
|
"source": raw.get("source", "winrm"),
|
||||||
"agent_version": raw.get("agent_version", ""),
|
"agent_version": raw.get("agent_version", ""),
|
||||||
"software_count": len(raw.get("software") or []),
|
"software_count": len(raw.get("software") or []),
|
||||||
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
|
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
|
||||||
for disk in raw.get("disks") or []],
|
"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.
|
# 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")],
|
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -222,3 +222,41 @@ def test_scan_runs_in_process(monkeypatch):
|
|||||||
status = {row["host"]: row["status"] for row in results}
|
status = {row["host"]: row["status"] for row in results}
|
||||||
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
||||||
assert len(seen) == 3
|
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]
|
||||||
Reference in new issue
Block a user