feat: transfer client software lists from inventory reports into netbox-slm
The NetBox Windows Agent and the NetBox Synchronizer write the installed software as a report into the device comments. On every device save the report is parsed (agent bullet list and synchronizer table) and the device's netbox-slm installations are brought in line: missing products, versions and installations are created, installations that left the report are removed. Installations entered by hand are never touched. Deleting a device removes its automatic installations first, since netbox-slm protects devices with installations. The command netbox_utilities_sync_software transfers existing reports once. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
63b3b31763
commit
e24a12164c
7 files changed
+379
-2
No files matched your search
@@ -529,6 +529,25 @@ exported as CSV. Without an own selection the global tenant filter applies.
|
|||||||
The device role filter is pre-set to `software_device_roles`; clearing it
|
The device role filter is pre-set to `software_device_roles`; clearing it
|
||||||
includes all devices.
|
includes all devices.
|
||||||
|
|
||||||
|
Software lists of the **NetBox Windows Agent** (mode `netbox`) and the
|
||||||
|
**NetBox Synchronizer** desktop app (agent scan) arrive as an inventory report
|
||||||
|
in the device comments. Every time such a device is saved, its software list is
|
||||||
|
transferred into netbox-slm: missing products, versions and installations are
|
||||||
|
created, and installations that disappeared from the report are removed. Only
|
||||||
|
installations created this way (comment *Automatisch aus dem
|
||||||
|
Inventarbericht übernommen*) are removed; entries made by hand stay. A product
|
||||||
|
gets the dcim manufacturer of the same name as the publisher, if one exists,
|
||||||
|
otherwise the publisher goes into its description. Agent lines without a
|
||||||
|
recognisable version (at least one dot) get the version `unbekannt`. Deleting a
|
||||||
|
device removes its automatic installations first, so netbox-slm does not block
|
||||||
|
the deletion.
|
||||||
|
|
||||||
|
Devices that already have a report are transferred once with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
/opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py netbox_utilities_sync_software
|
||||||
|
```
|
||||||
|
|
||||||
Devices with one of these roles get a **Software** tab listing their
|
Devices with one of these roles get a **Software** tab listing their
|
||||||
installations with add, edit and delete buttons. Other devices show the tab
|
installations with add, edit and delete buttons. Other devices show the tab
|
||||||
only if software is recorded for them. Permissions are those of netbox-slm
|
only if software is recorded for them. Permissions are those of netbox-slm
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from netbox.plugins import PluginConfig, get_plugin_config
|
from netbox.plugins import PluginConfig, get_plugin_config
|
||||||
|
|
||||||
__version__ = "0.28.0"
|
__version__ = "0.29.0"
|
||||||
|
|
||||||
|
|
||||||
class NetBoxUtilitiesConfig(PluginConfig):
|
class NetBoxUtilitiesConfig(PluginConfig):
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = (
|
||||||
|
"Transfer the software lists of inventory reports (NetBox Windows Agent, NetBox Synchronizer) "
|
||||||
|
"in device comments into netbox-slm installations."
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument("--device", type=int, action="append", help="Only this device ID (repeatable)")
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
from dcim.models import Device
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
|
from netbox_utilities.software_sync import sync_device_software
|
||||||
|
|
||||||
|
devices = Device.objects.filter(
|
||||||
|
Q(comments__icontains="installed software") | Q(comments__icontains="installierte software")
|
||||||
|
)
|
||||||
|
if options.get("device"):
|
||||||
|
devices = devices.filter(pk__in=options["device"])
|
||||||
|
|
||||||
|
total_created = total_removed = synced = 0
|
||||||
|
for device in devices.iterator():
|
||||||
|
try:
|
||||||
|
created, removed = sync_device_software(device)
|
||||||
|
except Exception as error: # noqa: BLE001 - report the device and continue with the next one
|
||||||
|
self.stderr.write(f"{device} (#{device.pk}): {error}")
|
||||||
|
continue
|
||||||
|
synced += 1
|
||||||
|
total_created += created
|
||||||
|
total_removed += removed
|
||||||
|
if created or removed:
|
||||||
|
self.stdout.write(f"{device}: +{created} / -{removed}")
|
||||||
|
self.stdout.write(
|
||||||
|
self.style.SUCCESS(
|
||||||
|
f"{synced} Geräte abgeglichen, {total_created} Installationen angelegt, {total_removed} entfernt."
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -60,5 +60,9 @@ def _install_menu_on_first_request(**kwargs):
|
|||||||
def install_software_support():
|
def install_software_support():
|
||||||
# Registers the device "Software" tab before NetBox builds the dcim URLs.
|
# Registers the device "Software" tab before NetBox builds the dcim URLs.
|
||||||
from . import software_views # noqa: F401
|
from . import software_views # noqa: F401
|
||||||
|
from .software_sync import install_software_sync
|
||||||
|
|
||||||
|
# Software lists of the Windows agent and the NetBox Synchronizer arrive in the device comments.
|
||||||
|
install_software_sync()
|
||||||
|
|
||||||
request_started.connect(_install_menu_on_first_request, dispatch_uid=__name__)
|
request_started.connect(_install_menu_on_first_request, dispatch_uid=__name__)
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
"""
|
||||||
|
Transfer the software list of inventory reports in device comments into netbox-slm.
|
||||||
|
|
||||||
|
Two writers put a software list into the comments of a client device:
|
||||||
|
|
||||||
|
* the NetBox Windows Agent (mode ``netbox``)::
|
||||||
|
|
||||||
|
## Installed software (2)
|
||||||
|
- 7-Zip 23.01 (x64) 23.01 — Igor Pavlov
|
||||||
|
- Mozilla Firefox (x64 de) 120.0 — Mozilla
|
||||||
|
|
||||||
|
* the NetBox Synchronizer desktop app (agent scan in mode ``listen``)::
|
||||||
|
|
||||||
|
### Installierte Software (2)
|
||||||
|
|
||||||
|
| Programm | Version | Hersteller |
|
||||||
|
|---|---|---|
|
||||||
|
| 7-Zip 23.01 (x64) | 23.01 | Igor Pavlov |
|
||||||
|
|
||||||
|
On every device save the installations recorded this way are brought in line with the report.
|
||||||
|
Installations entered by hand are never changed or removed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Marks installations created from a report; only these are removed again when a report drops them.
|
||||||
|
SYNC_MARKER = "Automatisch aus dem Inventarbericht übernommen (netbox-utilities)."
|
||||||
|
UNKNOWN_VERSION = "unbekannt"
|
||||||
|
|
||||||
|
_HEADING = re.compile(r"^\s*#{1,6}\s*(installed software|installierte software)\b", re.IGNORECASE)
|
||||||
|
_ANY_HEADING = re.compile(r"^\s*#{1,6}\s")
|
||||||
|
# At least one dot, so a year in a product name ("Office 2024") is not taken for a version.
|
||||||
|
_VERSION = re.compile(r"^v?\d+(?:\.\w+)+(?:[\-_+]\w+)*$", re.IGNORECASE)
|
||||||
|
_TABLE_SEPARATOR = re.compile(r"^\|?\s*:?-{2,}")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SoftwareEntry:
|
||||||
|
name: str
|
||||||
|
version: str
|
||||||
|
publisher: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def key(self):
|
||||||
|
return self.name.casefold(), self.version.casefold()
|
||||||
|
|
||||||
|
|
||||||
|
def has_software_report(comments):
|
||||||
|
return any(_HEADING.match(line) for line in str(comments or "").splitlines())
|
||||||
|
|
||||||
|
|
||||||
|
def _software_lines(comments):
|
||||||
|
"""Lines of the first software section, up to the next heading."""
|
||||||
|
inside = False
|
||||||
|
for line in str(comments or "").splitlines():
|
||||||
|
if _HEADING.match(line):
|
||||||
|
if inside:
|
||||||
|
return
|
||||||
|
inside = True
|
||||||
|
continue
|
||||||
|
if inside:
|
||||||
|
if _ANY_HEADING.match(line) or line.strip().startswith("<!--"):
|
||||||
|
return
|
||||||
|
yield line.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_table_row(line):
|
||||||
|
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
|
||||||
|
if len(cells) < 2 or _TABLE_SEPARATOR.match(line) or cells[0].casefold() in {"programm", "name", "software"}:
|
||||||
|
return None
|
||||||
|
return cells[0], cells[1], cells[2] if len(cells) > 2 else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_bullet(line):
|
||||||
|
"""``- Name Version — Publisher``: the version is the last word if it looks like one."""
|
||||||
|
text = line[1:].strip()
|
||||||
|
publisher = ""
|
||||||
|
if " — " in text:
|
||||||
|
text, publisher = (part.strip() for part in text.rsplit(" — ", 1))
|
||||||
|
words = text.rsplit(" ", 1)
|
||||||
|
if len(words) == 2 and _VERSION.match(words[1]):
|
||||||
|
return words[0], words[1], publisher
|
||||||
|
return text, "", publisher
|
||||||
|
|
||||||
|
|
||||||
|
def clean_name(name, version):
|
||||||
|
"""Remove a version the vendor appended to the product name ("Foo 1.2", "Foo - 1.2.3")."""
|
||||||
|
name = " ".join(str(name or "").split())
|
||||||
|
version = str(version or "").strip()
|
||||||
|
if not version:
|
||||||
|
return name
|
||||||
|
match = re.match(r"^(?P<base>.+?)\s*(?:-\s*)?v?(?P<tail>\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 parse_software_report(comments):
|
||||||
|
"""Software entries of a report in device comments; an empty list without a report."""
|
||||||
|
entries = {}
|
||||||
|
for line in _software_lines(comments):
|
||||||
|
if line.startswith("|"):
|
||||||
|
parsed = _parse_table_row(line)
|
||||||
|
elif line.startswith(("- ", "* ")):
|
||||||
|
parsed = _parse_bullet(line)
|
||||||
|
else:
|
||||||
|
parsed = None
|
||||||
|
if not parsed or not parsed[0].strip():
|
||||||
|
continue
|
||||||
|
raw_name, version, publisher = (" ".join(str(part or "").split()) for part in parsed)
|
||||||
|
version = version or UNKNOWN_VERSION
|
||||||
|
entry = SoftwareEntry(clean_name(raw_name, version)[:128], version[:64], publisher[:255])
|
||||||
|
entries.setdefault(entry.key, entry)
|
||||||
|
return list(entries.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _product_for(entry, products, manufacturers):
|
||||||
|
from netbox_slm.models import SoftwareProduct
|
||||||
|
|
||||||
|
key = entry.name.casefold()
|
||||||
|
product = products.get(key)
|
||||||
|
if product is None:
|
||||||
|
product = SoftwareProduct.objects.filter(name__iexact=entry.name).order_by("pk").first()
|
||||||
|
if product is None:
|
||||||
|
product = SoftwareProduct(name=entry.name, manufacturer=manufacturers.get(entry.publisher.casefold()))
|
||||||
|
if product.manufacturer is None and entry.publisher:
|
||||||
|
product.description = entry.publisher
|
||||||
|
product.full_clean()
|
||||||
|
product.save()
|
||||||
|
products[key] = product
|
||||||
|
return product
|
||||||
|
|
||||||
|
|
||||||
|
def _version_for(product, entry, versions):
|
||||||
|
from netbox_slm.models import SoftwareProductVersion
|
||||||
|
|
||||||
|
key = (product.pk, entry.version.casefold())
|
||||||
|
version = versions.get(key)
|
||||||
|
if version is None:
|
||||||
|
version = (
|
||||||
|
SoftwareProductVersion.objects.filter(software_product=product, name__iexact=entry.version)
|
||||||
|
.order_by("pk")
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if version is None:
|
||||||
|
version = SoftwareProductVersion(software_product=product, name=entry.version)
|
||||||
|
version.full_clean()
|
||||||
|
version.save()
|
||||||
|
versions[key] = version
|
||||||
|
return version
|
||||||
|
|
||||||
|
|
||||||
|
def sync_device_software(device):
|
||||||
|
"""
|
||||||
|
Bring the netbox-slm installations of a device in line with the report in its comments.
|
||||||
|
|
||||||
|
Returns (created, removed). Devices without a report are left untouched, so removing the
|
||||||
|
report by hand does not delete anything.
|
||||||
|
"""
|
||||||
|
from dcim.models import Manufacturer
|
||||||
|
from django.db import transaction
|
||||||
|
from netbox_slm.models import SoftwareProductInstallation
|
||||||
|
|
||||||
|
comments = getattr(device, "comments", "")
|
||||||
|
if not has_software_report(comments):
|
||||||
|
return 0, 0
|
||||||
|
entries = parse_software_report(comments)
|
||||||
|
manufacturers = {
|
||||||
|
manufacturer.name.casefold(): manufacturer
|
||||||
|
for manufacturer in Manufacturer.objects.filter(
|
||||||
|
name__in={entry.publisher for entry in entries if entry.publisher}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
with transaction.atomic():
|
||||||
|
existing = SoftwareProductInstallation.objects.filter(device=device).select_related(
|
||||||
|
"software_product", "version"
|
||||||
|
)
|
||||||
|
present = {}
|
||||||
|
for installation in existing:
|
||||||
|
key = (installation.software_product.name.casefold(), installation.version.name.casefold())
|
||||||
|
present.setdefault(key, installation)
|
||||||
|
|
||||||
|
wanted = {entry.key: entry for entry in entries}
|
||||||
|
products, versions, created = {}, {}, 0
|
||||||
|
for key, entry in wanted.items():
|
||||||
|
if key in present:
|
||||||
|
continue
|
||||||
|
product = _product_for(entry, products, manufacturers)
|
||||||
|
version = _version_for(product, entry, versions)
|
||||||
|
SoftwareProductInstallation.objects.create(
|
||||||
|
device=device, software_product=product, version=version, comments=SYNC_MARKER
|
||||||
|
)
|
||||||
|
created += 1
|
||||||
|
|
||||||
|
stale = [
|
||||||
|
installation.pk
|
||||||
|
for key, installation in present.items()
|
||||||
|
if key not in wanted and installation.comments == SYNC_MARKER
|
||||||
|
]
|
||||||
|
removed = SoftwareProductInstallation.objects.filter(pk__in=stale).delete()[0] if stale else 0
|
||||||
|
return created, removed
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_after_save(sender, instance, raw=False, **kwargs):
|
||||||
|
if raw or not has_software_report(getattr(instance, "comments", "")):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
sync_device_software(instance)
|
||||||
|
except Exception: # noqa: BLE001 - a broken report must never block saving the device
|
||||||
|
logger.exception("Software of device %s could not be transferred to netbox-slm", instance.pk)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_synced_installations(device):
|
||||||
|
"""netbox-slm protects devices with installations; the automatic ones go with the device."""
|
||||||
|
from netbox_slm.models import SoftwareProductInstallation
|
||||||
|
|
||||||
|
return SoftwareProductInstallation.objects.filter(device=device, comments=SYNC_MARKER).delete()[0]
|
||||||
|
|
||||||
|
|
||||||
|
def install_software_sync():
|
||||||
|
from dcim.models import Device
|
||||||
|
from django.db.models.signals import post_save
|
||||||
|
|
||||||
|
post_save.connect(_sync_after_save, sender=Device, dispatch_uid=f"{__name__}.device")
|
||||||
|
|
||||||
|
if getattr(Device.delete, "_netbox_utilities_software", False):
|
||||||
|
return
|
||||||
|
original_delete = Device.delete
|
||||||
|
|
||||||
|
def delete(self, *args, **kwargs):
|
||||||
|
if self.pk:
|
||||||
|
remove_synced_installations(self)
|
||||||
|
return original_delete(self, *args, **kwargs)
|
||||||
|
|
||||||
|
delete._netbox_utilities_software = True
|
||||||
|
Device.delete = delete
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from netbox_utilities.software_sync import (
|
||||||
|
UNKNOWN_VERSION,
|
||||||
|
SoftwareEntry,
|
||||||
|
clean_name,
|
||||||
|
has_software_report,
|
||||||
|
parse_software_report,
|
||||||
|
)
|
||||||
|
|
||||||
|
AGENT_REPORT = """Updated automatically by the NetBox Windows Agent.
|
||||||
|
|
||||||
|
## Hardware
|
||||||
|
- System: LENOVO 21MW
|
||||||
|
|
||||||
|
## Installed software (4)
|
||||||
|
- 7-Zip 23.01 (x64) 23.01 — Igor Pavlov
|
||||||
|
- Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130 14.38.33130.0 — Microsoft Corporation
|
||||||
|
- Microsoft Office Professional Plus 2024 — Microsoft Corporation
|
||||||
|
- Notepad++ (64-bit x64) 8.6.2
|
||||||
|
"""
|
||||||
|
|
||||||
|
SYNCHRONIZER_REPORT = """Handnotiz
|
||||||
|
|
||||||
|
<!-- netbox-sync:inventory -->
|
||||||
|
## Inventar (NetBox Windows Agent)
|
||||||
|
|
||||||
|
### Installierte Software (2)
|
||||||
|
|
||||||
|
| Programm | Version | Hersteller |
|
||||||
|
|---|---|---|
|
||||||
|
| Mozilla Firefox (x64 de) | 120.0 | Mozilla |
|
||||||
|
| Mozilla Firefox (x64 de) | 120.0 | Mozilla |
|
||||||
|
| Google Chrome | 119.0.6045.160 | Google LLC |
|
||||||
|
<!-- /netbox-sync:inventory -->
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class SoftwareReportParserTest(SimpleTestCase):
|
||||||
|
def test_agent_bullets(self):
|
||||||
|
self.assertEqual(
|
||||||
|
parse_software_report(AGENT_REPORT),
|
||||||
|
[
|
||||||
|
SoftwareEntry("7-Zip 23.01 (x64)", "23.01", "Igor Pavlov"),
|
||||||
|
SoftwareEntry(
|
||||||
|
"Microsoft Visual C++ 2015-2022 Redistributable (x64)", "14.38.33130.0", "Microsoft Corporation"
|
||||||
|
),
|
||||||
|
SoftwareEntry("Microsoft Office Professional Plus 2024", UNKNOWN_VERSION, "Microsoft Corporation"),
|
||||||
|
SoftwareEntry("Notepad++ (64-bit x64)", "8.6.2", ""),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_synchronizer_table_without_duplicates(self):
|
||||||
|
self.assertEqual(
|
||||||
|
parse_software_report(SYNCHRONIZER_REPORT),
|
||||||
|
[
|
||||||
|
SoftwareEntry("Mozilla Firefox (x64 de)", "120.0", "Mozilla"),
|
||||||
|
SoftwareEntry("Google Chrome", "119.0.6045.160", "Google LLC"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_without_report(self):
|
||||||
|
self.assertFalse(has_software_report("Nur eine Notiz\n## Hardware"))
|
||||||
|
self.assertEqual(parse_software_report("## Hardware\n- CPU: x"), [])
|
||||||
|
self.assertTrue(has_software_report(AGENT_REPORT))
|
||||||
|
|
||||||
|
def test_clean_name_strips_appended_version_only(self):
|
||||||
|
self.assertEqual(clean_name("Foo Tool 1.2.3", "1.2.3"), "Foo Tool")
|
||||||
|
self.assertEqual(clean_name("Bar - 14.38", "14.38.1"), "Bar")
|
||||||
|
self.assertEqual(clean_name("Office 2024", "16.0"), "Office 2024")
|
||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "netbox-utilities"
|
name = "netbox-utilities"
|
||||||
version = "0.28.0"
|
version = "0.29.0"
|
||||||
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations for NetBox 4.6/4.7"
|
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations for NetBox 4.6/4.7"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
|
|||||||
Reference in new issue
Block a user