feat: maintain netbox-inventory assets for clients and show the agent's software list

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 12:29:58 +01:00
1 parent d6622cf48f
commit 98c8647501
7 files changed
+239 -4

No files matched your search

+75 -1
View File
@@ -78,6 +78,9 @@ def _report_body(comments):
return None
_UNKNOWN = object()
def _noop(*_args, **_kwargs):
pass
@@ -132,6 +135,7 @@ class ClientSyncEngine:
self._device_types = {}
self._platforms = {}
self._planned = set()
self._asset_endpoint = _UNKNOWN
# ------------------------------------------------------------------
# Lookups
@@ -222,7 +226,71 @@ class ClientSyncEngine:
@staticmethod
def new_report():
return {"devices_created": 0, "devices_updated": 0, "devices_unchanged": 0, "objects_created": 0,
"interfaces_created": 0, "ips_created": 0, "changes": [], "errors": [], "items": []}
"interfaces_created": 0, "ips_created": 0, "assets_created": 0, "assets_updated": 0,
"changes": [], "errors": [], "items": []}
# ------------------------------------------------------------------
# netbox-inventory plugin (asset management)
# ------------------------------------------------------------------
def asset_endpoint(self):
"""``plugins/inventory/assets`` when the netbox-inventory plugin is installed, else ``None``."""
if self._asset_endpoint is _UNKNOWN:
try:
endpoint = self.nb.plugins.inventory.assets
list(endpoint.filter(serial="netbox-sync-probe"))
self._asset_endpoint = endpoint
except Exception as error: # noqa: BLE001 - plugin missing (404), no permission or no plugins API
self._asset_endpoint = None
if hasattr(self.nb, "plugins"):
self.log(f"netbox-inventory nicht verfügbar – Assets werden übersprungen ({error})", "info")
return self._asset_endpoint
def _sync_asset(self, client, device, type_id, dry_run, report):
"""Create or update the inventory asset of a client (found by serial number)."""
endpoint = self.asset_endpoint()
serial = clean_serial(client.get("serial"))
if endpoint is None or not serial:
return []
assets = list(endpoint.filter(serial=serial))
if len(assets) > 1:
return [f"Asset übersprungen – {len(assets)} Assets mit der Seriennummer {serial}"]
report_text = inventory_report(client)
description = f"Windows-Client; UUID {client['uuid']}" if client.get("uuid") else "Windows-Client"
if not assets:
report["assets_created"] += 1
if not dry_run:
payload = {"name": client["name"], "serial": serial, "status": "used", "device_type": type_id,
"description": description}
if device is not None:
payload["device"] = device.id
if report_text:
payload["comments"] = merge_report("", report_text)
endpoint.create(payload)
return ["Asset im Inventory-Plugin anlegen"]
asset = assets[0]
updates = {}
if (getattr(asset, "name", "") or "") != client["name"]:
updates["name"] = client["name"]
if str(getattr(getattr(asset, "status", None), "value", getattr(asset, "status", "")) or "") != "used":
updates["status"] = "used"
if type_id is not None and related_id(asset, "device_type") != type_id:
updates["device_type"] = type_id
if device is not None and related_id(asset, "device") != device.id:
updates["device"] = device.id
if client.get("uuid") and (getattr(asset, "description", "") or "") != description:
updates["description"] = description
current = getattr(asset, "comments", "") or ""
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
updates["comments"] = merge_report(current, report_text)
if not updates:
return []
report["assets_updated"] += 1
if not dry_run:
asset.update(updates)
labels = {"name": "Name", "status": "Status", "device_type": "Gerätetyp", "device": "Gerät",
"description": "UUID", "comments": "Inventarbericht"}
return ["Asset aktualisieren: " + ", ".join(labels[key] for key in updates)]
def sync(self, clients, site_id, role_id, tenant_id=None, interfaces=True, update_existing=True, dry_run=True,
progress=_noop, cancelled=lambda: False):
@@ -261,6 +329,7 @@ class ClientSyncEngine:
changes.append(f"Inventarbericht in den Kommentaren ({len(client.get('software') or [])} Programme)")
report["devices_created"] += 1
if dry_run:
changes.extend(self._sync_asset(client, None, type_id, dry_run, report))
if interfaces:
for interface in client.get("interfaces", []):
changes.append(f"Schnittstelle {interface['name']} anlegen"
@@ -308,6 +377,11 @@ class ClientSyncEngine:
device.update(updates)
if interfaces:
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
try:
changes.extend(self._sync_asset(client, device, type_id, dry_run, report))
except Exception as error: # noqa: BLE001 - the device itself is fine; report the asset problem
report["errors"].append(f"{name}: Asset – {error}")
changes.append(f"Asset fehlgeschlagen: {error}")
if not changes:
report["devices_unchanged"] += 1
return changes
+1
View File
@@ -274,6 +274,7 @@ def apply_scan(row, raw, now=None):
"installed": raw.get("installed", ""),
"last_boot": raw.get("last_boot", ""),
"source": raw.get("source", "winrm"),
"uuid": raw.get("uuid", ""),
"agent_version": raw.get("agent_version", ""),
"software_count": len(raw.get("software") or []),
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
+1
View File
@@ -217,6 +217,7 @@ def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
"model": system.get("Model") or "",
"product_name": product.get("Name") or "",
"product_version": product.get("Version") or "",
"uuid": product.get("UUID") or "",
"serial": bios.get("SerialNumber") or "",
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
+3 -1
View File
@@ -810,7 +810,9 @@ class Actions:
self.state.client_engine = engine
self.state.clients_changed.emit()
text = (f"{report['devices_created']} Geräte angelegt, {report['devices_updated']} aktualisiert, "
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen")
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen"
+ (f", {report['assets_created']} Assets angelegt, {report['assets_updated']} aktualisiert"
if report.get("assets_created") or report.get("assets_updated") else ""))
area_log("client")(f"Client-Übertragung: {text}", "success")
if report["errors"]:
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning",
+73 -2
View File
@@ -1,15 +1,83 @@
"""Dialogs for transferring scanned Windows clients to NetBox."""
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
import csv
from PySide6.QtCore import Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QFileDialog, QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
from netbox_sync.ui.dialogs import _Dialog, _mark_invalid
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Banner, SearchableComboBox, checkbox, form_dialog_buttons, label
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.widgets import (
Badge,
Banner,
SearchableComboBox,
SearchField,
Table,
button,
checkbox,
error,
form_dialog_buttons,
label,
)
ROLE_HINTS = ("client", "arbeitsplatz", "workstation", "pc", "notebook")
class ClientSoftwareDialog(_Dialog):
"""Installed software of one client (from the NetBox Windows Agent), searchable and exportable."""
def __init__(self, parent, row):
software = row.get("software") or []
super().__init__(parent, f"Software – {row['name']}",
f"{len(software)} Programme laut NetBox-Agent (maschinenweit installierte Software)"
+ (f" · erfasst {row['scanned_text']}" if row.get("scanned_text") else ""), width=760)
self.resize(900, 640)
self.row = row
self.search = SearchField("Programm, Version, Hersteller …")
self.root.addWidget(self.search)
columns = [Column("name", "Programm", 420), Column("version", "Version", 150),
Column("publisher", "Hersteller", 260)]
self.model = RowTableModel(columns, row_id=lambda item: (item["name"], item["version"]))
self.model.set_rows(software)
self.proxy = FilterProxy(self.model)
self.search.textChanged.connect(self.proxy.set_text)
table = Table()
table.setModel(self.proxy)
table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
table.setColumnWidth(index, column.width)
self.root.addWidget(table, 1)
buttons = QHBoxLayout()
buttons.addWidget(button("Als CSV speichern …", "download", on_click=self.save_csv))
buttons.addWidget(button("Kopieren", "copy", on_click=self.copy))
buttons.addStretch(1)
buttons.addWidget(button("Schließen", variant="primary", on_click=self.accept))
self.root.addLayout(buttons)
def _lines(self):
return [(item["name"], item["version"], item["publisher"]) for item in self.row.get("software") or []]
def copy(self):
QGuiApplication.clipboard().setText("\n".join("\t".join(line) for line in self._lines()))
def save_csv(self):
path, _filter = QFileDialog.getSaveFileName(self, "Software speichern", f"{self.row['name']}-software.csv",
"CSV (*.csv)")
if not path:
return
try:
# utf-8-sig and semicolons so that Excel opens it directly
with open(path, "w", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream, delimiter=";")
writer.writerow(("Programm", "Version", "Hersteller"))
writer.writerows(self._lines())
except OSError as problem:
error(self, "Speichern fehlgeschlagen", str(problem))
class ClientTargetDialog(_Dialog):
"""Choose site, role and tenant for the new devices."""
@@ -95,6 +163,9 @@ class ClientPreviewDialog(_Dialog):
(f"{report['interfaces_created']} Schnittstellen", "info"),
(f"{report['ips_created']} IP-Adressen", "info"),
]
assets = report.get("assets_created", 0) + report.get("assets_updated", 0)
if assets:
items.append((f"{assets} Assets", "info"))
if report["errors"]:
items.append((f"{len(report['errors'])} Probleme", "error"))
for text, kind in items:
+30
View File
@@ -12,6 +12,7 @@ from PySide6.QtWidgets import (
QGridLayout,
QHBoxLayout,
QLineEdit,
QMenu,
QPlainTextEdit,
QRadioButton,
QSpinBox,
@@ -23,7 +24,10 @@ from netbox_sync.core import agent_client
from netbox_sync.core.client_sync import clean_manufacturer
from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label
from netbox_sync.ui import widgets
from netbox_sync.ui.client_dialogs import ClientSoftwareDialog
from netbox_sync.ui.client_help import ClientHelpDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
from netbox_sync.ui.credentials import ask_credentials
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
@@ -235,6 +239,10 @@ class ClientsPage(Page):
Column("chassis", "Bauform", 95),
Column("user", "Angemeldet", 140),
Column("ips", "IP-Adressen", 160, value=_ips),
Column("software", "Software", 90,
value=lambda row: f"{len(row['software'])} Programme" if row.get("software") else "",
sort=lambda row: len(row.get("software") or []), color=lambda row: "accent",
tooltip=lambda row: "Doppelklick: vollständige Liste" if row.get("software") else ""),
Column("last_logon", "AD-Anmeldung", 105, value=lambda row: _date((row.get("ad") or {}).get("last_logon")),
sort=lambda row: (row.get("ad") or {}).get("last_logon") or 0),
]
@@ -246,6 +254,8 @@ class ClientsPage(Page):
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
card.add(self.table, 1)
footer = QHBoxLayout()
@@ -506,8 +516,28 @@ class ClientsPage(Page):
def _toggle(self, index):
row = self.proxy.row_at(index)
if self.model.columns[index.column()].key == "software" and row.get("software"):
self.show_software(row)
return
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def show_software(self, row):
ClientSoftwareDialog(self.window, dict(row, scanned_text=time.strftime(
"%d.%m.%Y %H:%M", time.localtime(row["scanned_at"])) if row.get("scanned_at") else "")).exec()
def _context_menu(self, position):
index = self.table.indexAt(position)
if not index.isValid():
return
row = self.proxy.row_at(index)
menu = QMenu(self)
action = menu.addAction(icon("list", theme.color("text_muted")), "Software anzeigen …",
lambda: self.show_software(row))
action.setEnabled(bool(row.get("software")))
if not row.get("software"):
action.setText("Software anzeigen … (nur mit NetBox-Agent)")
menu.exec(self.table.viewport().mapToGlobal(position))
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
+56
View File
@@ -260,3 +260,59 @@ def test_winrm_scan_leaves_comments_alone():
engine.load_targets()
engine.sync([client], 1, 2, dry_run=False)
assert "comments" not in nb.dcim.devices.created[0]
def _with_inventory_plugin(nb):
from types import SimpleNamespace
from fake_netbox import Endpoint
nb.plugins = SimpleNamespace(inventory=SimpleNamespace(assets=Endpoint()))
return nb.plugins.inventory.assets
def test_new_client_gets_an_asset_linked_to_the_device():
nb, client = _setup()
assets = _with_inventory_plugin(nb)
agent_row = apply_scan(new_row("pc01.firma.local"), dict(RAW, source="agent", uuid="4C4C-1234",
software=[{"name": "7-Zip", "version": "24", "publisher": ""}]))
engine = ClientSyncEngine(nb)
engine.load_targets()
preview = engine.sync([agent_row], 1, 2, dry_run=True)
assert preview["assets_created"] == 1 and "Asset im Inventory-Plugin anlegen" in preview["items"][0][1]
assert assets.created == []
engine.sync([agent_row], 1, 2, dry_run=False)
device = nb.dcim.devices.records[0]
asset = assets.created[0]
assert asset["serial"] == "PW0K84A9" and asset["device"] == device.id and asset["status"] == "used"
assert asset["device_type"] == device.device_type and asset["description"] == "Windows-Client; UUID 4C4C-1234"
assert "| 7-Zip | 24 | |" in asset["comments"]
again = ClientSyncEngine(nb)
again.load_targets()
report = again.sync([agent_row], 1, 2, dry_run=True)
assert report["assets_created"] == 0 and report["assets_updated"] == 0 and report["items"][0][1] == []
def test_existing_asset_is_linked_and_updated_by_serial():
nb, client = _setup()
assets = _with_inventory_plugin(nb)
assets.records.append(Record(assets, id=500, name="Lager-Notebook", serial="PW0K84A9", status="stored",
device=None, device_type=None, description="", comments="Kaufbeleg 4711"))
engine = ClientSyncEngine(nb)
engine.load_targets()
report = engine.sync([client], 1, 2, dry_run=False)
asset = assets.records[0]
device = nb.dcim.devices.records[0]
assert report["assets_updated"] == 1 and report["assets_created"] == 0
assert asset.device == device.id and asset.status == "used" and asset.name == "PC01"
assert asset.comments == "Kaufbeleg 4711" # WinRM scan: no inventory report, comments untouched
assert any(change.startswith("Asset aktualisieren: Name, Status, Gerätetyp, Gerät") for change in report["items"][0][1])
def test_without_inventory_plugin_no_asset_is_touched():
nb, client = _setup()
engine = ClientSyncEngine(nb)
engine.load_targets()
report = engine.sync([client], 1, 2, dry_run=False)
assert report["errors"] == [] and report["assets_created"] == 0 and engine.asset_endpoint() is None