diff --git a/README.md b/README.md index f33c4b1..465662b 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,16 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox. Group Policy startup script; the setup guide has a tab with all steps - The agent data runs through the same table and NetBox transfer as the WinRM scan, plus disks and the number of installed programs in the tooltip +- Optional: "Installierte Software in netbox-slm pflegen" in the transfer dialog + records the installed software as installations of the + [netbox-slm](https://git.mrblake.cc/MrBlake/NetBox-SLM) plugin. Missing + manufacturers (publisher without legal suffix, e.g. "Microsoft Corporation" → + "Microsoft"), software products and versions are created; automatic + installations that the agent no longer reports are removed, installations + entered by hand stay. Names and the marker comment match the software + transfer of [NetBox Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities), + so both can run side by side; its **Client Software Übersicht** shows the + result. Without netbox-slm the option is skipped with a log message ### Offline mode (without NetBox) diff --git a/netbox_sync/core/client_sync.py b/netbox_sync/core/client_sync.py index 969179f..2ad97cf 100644 --- a/netbox_sync/core/client_sync.py +++ b/netbox_sync/core/client_sync.py @@ -136,6 +136,8 @@ class ClientSyncEngine: self._platforms = {} self._planned = set() self._asset_endpoint = _UNKNOWN + self._software = None + self.software = False # ------------------------------------------------------------------ # Lookups @@ -227,7 +229,7 @@ class ClientSyncEngine: def new_report(): return {"devices_created": 0, "devices_updated": 0, "devices_unchanged": 0, "objects_created": 0, "interfaces_created": 0, "ips_created": 0, "assets_created": 0, "assets_updated": 0, - "changes": [], "errors": [], "items": []} + "software_installed": 0, "software_removed": 0, "changes": [], "errors": [], "items": []} # ------------------------------------------------------------------ # netbox-inventory plugin (asset management) @@ -301,9 +303,24 @@ class ClientSyncEngine: "description": "UUID", "comments": "Inventarbericht"} return ["Asset aktualisieren: " + ", ".join(labels[key] for key in updates)] + def software_sync(self): + if self._software is None: + from netbox_sync.core.software_slm import SlmSoftwareSync + self._software = SlmSoftwareSync(self.nb, self, self.log) + return self._software + + def _sync_software(self, client, device, dry_run, report): + """Installed software as netbox-slm installations; a problem there never fails the device.""" + try: + return self.software_sync().sync(client, device, dry_run, report) + except Exception as error: # noqa: BLE001 - the device itself is fine; report the software problem + report["errors"].append(f"{client['name']}: Software – {error}") + return [f"Software fehlgeschlagen: {error}"] + def sync(self, clients, site_id, role_id, tenant_id=None, interfaces=True, update_existing=True, dry_run=True, - progress=_noop, cancelled=lambda: False): + progress=_noop, cancelled=lambda: False, software=False): self._planned = set() + self.software = software report = self.new_report() for index, client in enumerate(clients): if cancelled(): @@ -345,6 +362,8 @@ class ClientSyncEngine: + (f" ({', '.join(interface['ips'])})" if interface.get("ips") else "")) report["interfaces_created"] += 1 report["ips_created"] += len(interface.get("ips", [])) + if self.software: + changes.extend(self._sync_software(client, None, dry_run, report)) return changes payload = {"name": name, "device_type": type_id, "role": role_id, "site": site_id, "status": "active"} if platform_id: @@ -391,6 +410,8 @@ class ClientSyncEngine: 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 self.software: + changes.extend(self._sync_software(client, device, dry_run, report)) if not changes: report["devices_unchanged"] += 1 return changes diff --git a/netbox_sync/core/clients.py b/netbox_sync/core/clients.py index 3f2aea7..1cabca5 100644 --- a/netbox_sync/core/clients.py +++ b/netbox_sync/core/clients.py @@ -41,6 +41,7 @@ DEFAULT_CLIENT_OPTIONS = { "netbox_tenant": None, "sync_interfaces": True, "update_existing": True, + "sync_software": False, # installed software of agent clients as netbox-slm installations } # Win32_SystemEnclosure.ChassisTypes diff --git a/netbox_sync/core/software_slm.py b/netbox_sync/core/software_slm.py new file mode 100644 index 0000000..c2a637d --- /dev/null +++ b/netbox_sync/core/software_slm.py @@ -0,0 +1,229 @@ +"""Installed software of agent clients as netbox-slm installations. + +The netbox-slm plugin stores software products, versions and installations; the client software +overview of netbox-utilities shows them per tenant. Names, versions and the marker comment match +netbox-utilities, which transfers the same report from the device comments on every save. Both +ways can run side by side without creating duplicates, and neither removes installations +entered by hand. +""" + +import re + +from netbox_sync.core.netbox import related_id + +_UNKNOWN = object() +# Same text as netbox-utilities: only installations with this comment are removed again. +SYNC_MARKER = "Automatisch aus dem Inventarbericht übernommen (netbox-utilities)." +UNKNOWN_VERSION = "unbekannt" + +_LEGAL_SUFFIX = re.compile( + r"[,\s]+(inc\.?|incorporated|corp\.?|corporation|llc|l\.l\.c\.|ltd\.?|limited|gmbh(\s*&\s*co\.?\s*kg)?|ag|se|" + r"s\.?a\.?|s\.?r\.?l\.?|b\.?v\.?|co\.?|kg|plc|oy|ab|a/s|pty)$", + re.IGNORECASE, +) + + +def _text(value): + """Whitespace collapsed, ``|`` replaced – exactly what netbox-utilities reads from the report table.""" + return " ".join(str(value or "").replace("|", "/").split()) + + +def clean_name(name, version): + """Remove a version the vendor appended to the product name ("Foo 1.2", "Foo - 1.2.3").""" + name = _text(name) + version = str(version or "").strip() + if not version: + return name + match = re.match(r"^(?P.+?)\s*(?:-\s*)?v?(?P\d[\w.\-+]*)$", name) + if match: + tail = match.group("tail") + if version.startswith(tail) or tail.startswith(version): + return match.group("base").rstrip(" -") + return name + + +def publisher_name(publisher): + """Manufacturer name for a software publisher: "Adobe Inc." → "Adobe", "Microsoft Corporation" → "Microsoft".""" + from netbox_sync.core.client_sync import clean_manufacturer + + name = _text(publisher) + mapped = clean_manufacturer(name) + if mapped.casefold() != name.casefold(): + return mapped[:100] + previous = None + while name and name != previous: + previous = name + name = _LEGAL_SUFFIX.sub("", name).strip(" ,.-") + return (name or _text(publisher))[:100] + + +def software_entries(software): + """``(name, version, publisher)`` per program, unique by name and version like netbox-utilities.""" + entries = {} + for item in software or []: + version = _text(item.get("version")) or UNKNOWN_VERSION + name = clean_name(item.get("name"), version)[:128] + if not name: + continue + version = version[:64] + entries.setdefault((name.casefold(), version.casefold()), (name, version, _text(item.get("publisher")))) + return entries + + +class SlmSoftwareSync: + """Brings the netbox-slm installations of a device in line with the scanned software list. + + ``engine`` is the :class:`ClientSyncEngine`; its manufacturer lookup and planned-change notes + are shared, so a manufacturer used by hardware and software is created only once. + """ + + def __init__(self, nb, engine, log): + self.nb = nb + self.engine = engine + self.log = log + self._api = _UNKNOWN + self._products = None # name.casefold() -> record + self._versions = None # (product id, name.casefold()) -> record + self._planned_products = {} # dry run: name.casefold() -> placeholder id + + # ------------------------------------------------------------------ + # Plugin lookups + # ------------------------------------------------------------------ + + def api(self): + """``plugins/slm`` when netbox-slm is installed and readable, else ``None``.""" + if self._api is _UNKNOWN: + try: + api = self.nb.plugins.slm + list(api.softwareproducts.filter(name="netbox-sync-probe")) + self._api = api + except Exception as error: # noqa: BLE001 - plugin missing (404), no permission or no plugins API + self._api = None + self.log(f"netbox-slm nicht verfügbar – Software wird nicht als Installation gepflegt ({error})", + "warning") + return self._api + + def _load(self): + if self._products is not None: + return + api = self.api() + self._products, self._versions = {}, {} + for product in api.softwareproducts.all(): + self._products.setdefault(str(product.name).casefold(), product) + for version in api.softwareproductversions.all(): + key = (related_id(version, "software_product"), str(version.name).casefold()) + self._versions.setdefault(key, version) + + def _find_product(self, name): + """Cache first, then NetBox – netbox-utilities may have created it from the comments meanwhile.""" + key = name.casefold() + if key not in self._products: + found = sorted((item for item in self.api().softwareproducts.filter(name=name) + if str(item.name).casefold() == key), key=lambda item: item.id) + if found: + self._products[key] = found[0] + return self._products.get(key) + + def _find_version(self, product_id, name): + key = (product_id, name.casefold()) + if key not in self._versions: + found = sorted((item for item in self.api().softwareproductversions.filter(software_product_id=product_id, + name=name) + if str(item.name).casefold() == key[1]), key=lambda item: item.id) + if found: + self._versions[key] = found[0] + return self._versions.get(key) + + def _product(self, name, publisher, report, dry_run): + manufacturer = publisher_name(publisher) if publisher else "" + manufacturer_id = self.engine._manufacturer(manufacturer, report, dry_run) if manufacturer else None + product = self._find_product(name) + if product is None: + if dry_run: + key = name.casefold() + if key not in self._planned_products: + self._planned_products[key] = -(len(self._planned_products) + 1) + self.engine._note(report, ("slm-product", key), f"Softwareprodukt anlegen: {name}" + + (f" ({manufacturer})" if manufacturer else "")) + return self._planned_products[key] + payload = {"name": name} + if manufacturer_id: + payload["manufacturer"] = manufacturer_id + elif publisher: + payload["description"] = publisher[:255] + product = self.api().softwareproducts.create(payload) + self._products[name.casefold()] = product + report["objects_created"] += 1 + elif manufacturer and related_id(product, "manufacturer") is None: + # netbox-utilities knows only existing manufacturers and keeps the publisher as description. + self.engine._note(report, ("slm-manufacturer", name.casefold()), + f"Softwareprodukt {name}: Hersteller {manufacturer} setzen") + if not dry_run and manufacturer_id: + updates = {"manufacturer": manufacturer_id} + if (getattr(product, "description", "") or "").strip() == publisher: + updates["description"] = "" + product.update(updates) + product.manufacturer = manufacturer_id + return product.id + + def _version(self, product_id, name, report, dry_run): + version = self._find_version(product_id, name) if product_id > 0 else None + if version is None: + if dry_run: + return None + version = self.api().softwareproductversions.create({"software_product": product_id, "name": name}) + self._versions[(product_id, name.casefold())] = version + report["objects_created"] += 1 + return version.id + + # ------------------------------------------------------------------ + # Sync + # ------------------------------------------------------------------ + + def sync(self, client, device, dry_run, report): + """Create missing products, versions and installations; remove automatic ones that left the list. + + Only agent scans carry a software list – other clients and empty lists change nothing. + """ + if client.get("source") != "agent" or not client.get("software") or self.api() is None: + return [] + self._load() + wanted = software_entries(client["software"]) + present = {} + if device is not None: + for installation in self.api().softwareproductinstallations.filter(device_id=device.id): + key = (self._name(installation, "software_product"), self._name(installation, "version")) + present.setdefault(key, installation) + + new = [] + for key, (name, version, publisher) in wanted.items(): + product_id = self._product(name, publisher, report, dry_run) + if key in present: + continue + version_id = self._version(product_id, version, report, dry_run) + new.append({"device": getattr(device, "id", None), "software_product": product_id, "version": version_id, + "comments": SYNC_MARKER}) + stale = [installation for key, installation in present.items() + if key not in wanted and (getattr(installation, "comments", "") or "") == SYNC_MARKER] + + if not dry_run: + if new: + self.api().softwareproductinstallations.create(new) + if stale: + self.api().softwareproductinstallations.delete(stale) + report["software_installed"] += len(new) + report["software_removed"] += len(stale) + parts = [f"{len(new)} anlegen" if new else "", f"{len(stale)} entfernen" if stale else ""] + return [f"Software-Installationen (netbox-slm): {', '.join(part for part in parts if part)}"] if new or stale \ + else [] + + def _name(self, installation, attribute): + """Name of the nested product/version; the brief nested object normally carries it already.""" + value = getattr(installation, attribute, None) + name = getattr(value, "name", None) if not isinstance(value, (int, dict)) else ( + value.get("name") if isinstance(value, dict) else None) + if name is None: + ident = related_id(installation, attribute) + pool = self._products.values() if attribute == "software_product" else self._versions.values() + name = next((item.name for item in pool if item.id == ident), "") + return str(name).casefold() diff --git a/netbox_sync/ui/actions.py b/netbox_sync/ui/actions.py index 7153268..be61179 100644 --- a/netbox_sync/ui/actions.py +++ b/netbox_sync/ui/actions.py @@ -775,7 +775,8 @@ class Actions: choice = dialog.result self.state.update_client_options( netbox_site=choice["site_id"], netbox_role=choice["role_name"], netbox_tenant=choice["tenant_id"], - sync_interfaces=choice["interfaces"], update_existing=choice["update_existing"]) + sync_interfaces=choice["interfaces"], update_existing=choice["update_existing"], + sync_software=choice["software"]) self._preview_clients(engine, rows, choice) QTimer.singleShot(0, ask) @@ -786,7 +787,7 @@ class Actions: def _run_client_sync(engine, rows, choice, ctx, dry_run, role_id=None): return engine.sync(rows, choice["site_id"], role_id or choice["role_id"], choice["tenant_id"], choice["interfaces"], choice["update_existing"], dry_run=dry_run, - progress=ctx.progress, cancelled=lambda: ctx.cancelled) + progress=ctx.progress, cancelled=lambda: ctx.cancelled, software=choice.get("software", False)) def _preview_clients(self, engine, rows, choice): def show(report): @@ -812,7 +813,10 @@ class Actions: text = (f"{report['devices_created']} Geräte angelegt, {report['devices_updated']} aktualisiert, " 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 "")) + if report.get("assets_created") or report.get("assets_updated") else "") + + (f", {report['software_installed']} Software-Installationen angelegt, " + f"{report['software_removed']} entfernt" + if report.get("software_installed") or report.get("software_removed") else "")) area_log("client")(f"Client-Übertragung: {text}", "success") if report["errors"]: widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning", diff --git a/netbox_sync/ui/client_dialogs.py b/netbox_sync/ui/client_dialogs.py index 77af9cd..76fac36 100644 --- a/netbox_sync/ui/client_dialogs.py +++ b/netbox_sync/ui/client_dialogs.py @@ -115,8 +115,17 @@ class ClientTargetDialog(_Dialog): "unverändert.") self.update_existing = checkbox("Vorhandene Geräte aktualisieren (Modell, Plattform, Seriennummer)", options.get("update_existing", True)) + self.software = checkbox("Installierte Software in netbox-slm pflegen (nur Agent-Clients)", + options.get("sync_software", False), + tooltip="Legt für die vom NetBox Windows Agent gemeldete Software fehlende " + "Hersteller, Softwareprodukte, Versionen und Installationen im Plugin " + "netbox-slm an und entfernt automatisch angelegte Installationen, die " + "nicht mehr gemeldet werden. Von Hand erfasste Installationen bleiben " + "unverändert. Die Client-Software-Übersicht von netbox-utilities zeigt " + "diese Daten an.") self.root.addWidget(self.interfaces) self.root.addWidget(self.update_existing) + self.root.addWidget(self.software) self.root.addWidget(label("Zuordnung über den Gerätenamen (ohne Groß-/Kleinschreibung). Standort und Rolle " "vorhandener Geräte bleiben unverändert.", muted=True, wrap=True)) self.root.addWidget(self.error_banner) @@ -144,6 +153,7 @@ class ClientTargetDialog(_Dialog): "site_id": site, "role_id": role, "role_name": role_text, "tenant_id": tenant, "interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(), + "software": self.software.isChecked(), } super().accept() @@ -166,6 +176,9 @@ class ClientPreviewDialog(_Dialog): assets = report.get("assets_created", 0) + report.get("assets_updated", 0) if assets: items.append((f"{assets} Assets", "info")) + software = report.get("software_installed", 0) + report.get("software_removed", 0) + if software: + items.append((f"{software} Software-Installationen", "info")) if report["errors"]: items.append((f"{len(report['errors'])} Probleme", "error")) for text, kind in items: diff --git a/tests/fake_netbox.py b/tests/fake_netbox.py index 85d182f..109307a 100644 --- a/tests/fake_netbox.py +++ b/tests/fake_netbox.py @@ -66,11 +66,19 @@ class Endpoint: return found[0] if found else None def create(self, payload): + if isinstance(payload, list): # bulk create + return [self.create(item) for item in payload] record = Record(self, id=next(_ids), cable=None, **payload) self.records.append(record) self.created.append(payload) return record + def delete(self, objects): + ids = {getattr(item, "id", item) for item in objects} + self.deleted = getattr(self, "deleted", []) + sorted(ids) + self.records = [record for record in self.records if record.id not in ids] + return True + class FakeNetBox: netbox_version = "4.3.0" diff --git a/tests/test_software_slm.py b/tests/test_software_slm.py new file mode 100644 index 0000000..1555590 --- /dev/null +++ b/tests/test_software_slm.py @@ -0,0 +1,135 @@ +from types import SimpleNamespace + +from fake_netbox import Endpoint, FakeNetBox, Record + +from netbox_sync.core.client_sync import ClientSyncEngine +from netbox_sync.core.clients import apply_scan, new_row +from netbox_sync.core.software_slm import SYNC_MARKER, clean_name, publisher_name, software_entries +from test_clients import RAW, _setup + +SOFTWARE = [ + {"name": "7-Zip 24.08", "version": "24.08", "publisher": "Igor Pavlov"}, + {"name": "Mozilla Firefox 140.0", "version": "140.0", "publisher": "Mozilla"}, + {"name": "Microsoft Edge", "version": "142.0.1", "publisher": "Microsoft Corporation"}, + {"name": "Tool", "version": "", "publisher": ""}, +] + + +def _with_slm(nb): + nb.plugins = SimpleNamespace(slm=SimpleNamespace(softwareproducts=Endpoint(), softwareproductversions=Endpoint(), + softwareproductinstallations=Endpoint())) + return nb.plugins.slm + + +def _agent(software=SOFTWARE): + return apply_scan(new_row("pc01.firma.local"), dict(RAW, source="agent", software=software)) + + +def test_names_match_netbox_utilities(): + assert clean_name("Mozilla Firefox 140.0", "140.0") == "Mozilla Firefox" + assert clean_name("Foo - 1.2.3", "1.2.3.4") == "Foo" + assert clean_name("Office 2024", "16.0") == "Office 2024" + assert publisher_name("Microsoft Corporation") == "Microsoft" + assert publisher_name("Adobe Inc.") == "Adobe" and publisher_name("Google LLC") == "Google" + assert publisher_name("Igor Pavlov") == "Igor Pavlov" + entries = software_entries(SOFTWARE + [{"name": "tool", "version": None, "publisher": ""}]) + assert entries[("tool", "unbekannt")] == ("Tool", "unbekannt", "") + assert len(entries) == 4 + + +def test_software_is_off_by_default(): + nb, _client = _setup() + slm = _with_slm(nb) + engine = ClientSyncEngine(nb) + engine.load_targets() + engine.sync([_agent()], 1, 2, dry_run=False) + assert slm.softwareproductinstallations.records == [] + + +def test_software_creates_manufacturers_products_versions_and_installations(): + nb, _client = _setup() + slm = _with_slm(nb) + engine = ClientSyncEngine(nb) + engine.load_targets() + preview = engine.sync([_agent()], 1, 2, dry_run=True, software=True) + assert preview["errors"] == [] and preview["software_installed"] == 4 + assert "Softwareprodukt anlegen: Microsoft Edge (Microsoft)" in preview["changes"] + assert "Hersteller anlegen: Igor Pavlov" in preview["changes"] + assert slm.softwareproducts.created == [] and nb.dcim.manufacturers.created == [] + + report = engine.sync([_agent()], 1, 2, dry_run=False, software=True) + assert report["errors"] == [] and report["software_installed"] == 4 + device = nb.dcim.devices.records[0] + products = {item.name: item for item in slm.softwareproducts.records} + assert set(products) == {"7-Zip", "Mozilla Firefox", "Microsoft Edge", "Tool"} + manufacturers = {item.id: item.name for item in nb.dcim.manufacturers.records} + assert manufacturers[products["Microsoft Edge"].manufacturer] == "Microsoft" + assert not hasattr(products["Tool"], "manufacturer") + versions = {(item.software_product, item.name) for item in slm.softwareproductversions.records} + assert (products["Tool"].id, "unbekannt") in versions + installations = slm.softwareproductinstallations.records + assert len(installations) == 4 and all(item.device == device.id and item.comments == SYNC_MARKER + for item in installations) + + # second run: nothing to do + again = ClientSyncEngine(nb) + again.load_targets() + report = again.sync([_agent()], 1, 2, dry_run=True, software=True) + assert report["software_installed"] == 0 and report["software_removed"] == 0 and report["changes"] == [] + + +def _installation(slm, nb, device_id, product, version, comments): + slm.softwareproductinstallations.records.append(Record( + slm.softwareproductinstallations, id=len(slm.softwareproductinstallations.records) + 900, device=device_id, + software_product=SimpleNamespace(id=product.id, name=product.name), + version=SimpleNamespace(id=version.id, name=version.name), comments=comments)) + + +def test_removed_software_goes_but_manual_installations_stay(): + nb, _client = _setup() + slm = _with_slm(nb) + engine = ClientSyncEngine(nb) + engine.load_targets() + engine.sync([_agent()], 1, 2, dry_run=False, software=True) + device = nb.dcim.devices.records[0] + product = slm.softwareproducts.create({"name": "Lizenz-Tool"}) + version = slm.softwareproductversions.create({"software_product": product.id, "name": "1.0"}) + _installation(slm, nb, device.id, product, version, "von Hand") + # nested objects as the REST API returns them + for item in slm.softwareproductinstallations.records: + if isinstance(item.software_product, int): + product_record = slm.softwareproducts.get(item.software_product) + version_record = slm.softwareproductversions.get(item.version) + item.software_product = SimpleNamespace(id=product_record.id, name=product_record.name) + item.version = SimpleNamespace(id=version_record.id, name=version_record.name) + + again = ClientSyncEngine(nb) + again.load_targets() + report = again.sync([_agent(SOFTWARE[:2])], 1, 2, dry_run=False, software=True) + assert report["software_removed"] == 2 and report["software_installed"] == 0 + left = {item.software_product.name for item in slm.softwareproductinstallations.records} + assert left == {"7-Zip", "Mozilla Firefox", "Lizenz-Tool"} + + +def test_products_from_netbox_utilities_get_the_manufacturer(): + nb, _client = _setup() + slm = _with_slm(nb) + slm.softwareproducts.records.append(Record(slm.softwareproducts, id=50, name="Microsoft Edge", manufacturer=None, + description="Microsoft Corporation")) + engine = ClientSyncEngine(nb) + engine.load_targets() + report = engine.sync([_agent(SOFTWARE[2:3])], 1, 2, dry_run=False, software=True) + product = slm.softwareproducts.records[0] + assert report["errors"] == [] and len(slm.softwareproducts.records) == 1 + assert product.description == "" and product.manufacturer == nb.dcim.manufacturers.records[-1].id + assert slm.softwareproductinstallations.records[0].software_product == 50 + + +def test_without_slm_plugin_software_is_skipped(): + nb, _client = _setup() + logged = [] + engine = ClientSyncEngine(nb, lambda text, level="info": logged.append(level)) + engine.load_targets() + report = engine.sync([_agent()], 1, 2, dry_run=False, software=True) + assert report["errors"] == [] and report["software_installed"] == 0 and "warning" in logged + assert len(nb.dcim.devices.records) == 1