diff --git a/README.md b/README.md index c0e4a92..ba3f035 100644 --- a/README.md +++ b/README.md @@ -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 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 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 diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index 6782ee8..b37fb30 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,6 +1,6 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.28.0" +__version__ = "0.29.0" class NetBoxUtilitiesConfig(PluginConfig): diff --git a/netbox_utilities/management/commands/netbox_utilities_sync_software.py b/netbox_utilities/management/commands/netbox_utilities_sync_software.py new file mode 100644 index 0000000..3dcc4f4 --- /dev/null +++ b/netbox_utilities/management/commands/netbox_utilities_sync_software.py @@ -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." + ) + ) diff --git a/netbox_utilities/software_integration.py b/netbox_utilities/software_integration.py index cd53285..f339dc3 100644 --- a/netbox_utilities/software_integration.py +++ b/netbox_utilities/software_integration.py @@ -60,5 +60,9 @@ def _install_menu_on_first_request(**kwargs): def install_software_support(): # Registers the device "Software" tab before NetBox builds the dcim URLs. 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__) diff --git a/netbox_utilities/software_sync.py b/netbox_utilities/software_sync.py new file mode 100644 index 0000000..aa5c6ea --- /dev/null +++ b/netbox_utilities/software_sync.py @@ -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(" +## 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 | + +""" + + +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") diff --git a/pyproject.toml b/pyproject.toml index acf85c5..dad93c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] 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" readme = "README.md" requires-python = ">=3.12"