Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 713556a33e fix: cleaner filter layout for the client software overview
The filter card gets a balanced layout: tenant group, tenant, a search field
with icon and the buttons in one row, below it the client roles as toggle
pills (applied immediately) and the filter hint. The broken checkbox styling
is gone. The empty state explains how software lists get into NetBox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:28:29 +01:00
MrBlakeandClaude Opus 5.5 7d267ec05d fix: client software overview shows client roles only
The overview is always limited to devices whose role is listed in
software_device_roles, now "Client" and "Windows Client" by default and
matched by name or slug (windows-client from the Windows agent). The role
filter offers only these roles as checkboxes; none ticked means all client
roles, so servers can no longer appear by clearing the filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:25:12 +01:00
MrBlakeandClaude Opus 5.5 e24a12164c 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]>
2026-11-18 14:21:52 +01:00
MrBlakeandClaude Opus 5.5 63b3b31763 feat: client software overview based on netbox-slm
New page "Client Software Übersicht" in a "Software" group of the netbox-inventory
menu (fallback: own Hardware menu). It shows, per tenant or tenant group
including subgroups, the software products recorded with netbox-slm, their
versions and the clients they are installed on: key figures, charts of the most
widespread products and their version distribution, a sortable and searchable
product list, a drill-down per product/version with the list of clients, and a
CSV export. Without an own selection the global tenant filter applies; the
device role filter is pre-set to the configured client roles.

Devices with a client role (software_device_roles, default "Clients") get a
"Software" tab listing their installations with add, edit and delete actions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:18:59 +01:00
18 changed files with 1698 additions and 3 deletions

No files matched your search

+48
View File
@@ -49,6 +49,7 @@ Plugin settings:
- A **Disks** tab for servers, NAS, SAN and MSA devices: slot layout, disks, RAID groups, warranty and age warnings, replacement history, CSV import, HPE MSA disk export import, REST API and GraphQL.
- **CPU & RAM** per server from a built-in catalogue of 700+ Intel and AMD server CPUs since 2012, with cluster capacity and overcommit for NetBox virtualization.
- **Switch front panel** on the device page (Aruba-style, status or VLAN colours) and **switch port usage as PDF**, in the user's NetBox language.
- **Client Software Übersicht** (with the optional [netbox-slm](https://github.com/ICTU/netbox_slm) plugin): software products, versions and the clients they are installed on per tenant or tenant group, with charts and CSV export, plus a **Software** tab for clients.
Navigation settings are stored per user. The active tenant or tenant-group
selection is stored in the browser session.
@@ -225,6 +226,8 @@ sudo systemctl restart netbox netbox-rq
| `hardware_vcpu_ratio_warning` | `4` | Warn when a host or cluster has more vCPUs per physical core |
| `switch_ports_enabled` | `True` | Front panel and **Export switch port usage** button for switches |
| `switch_device_roles` | `["Switch"]` | Device roles (case-insensitive) that get the front panel and export button |
| `software_enabled` | `True` | Client software overview and **Software** device tab (requires netbox-slm) |
| `software_device_roles` | `["Client", "Windows Client"]` | Device roles (name or slug, case-insensitive) shown in the client software overview and given the **Software** tab |
| `wireless_trace_enabled` | `True` | Cable trace continues across wireless links (radio bridges) to the cabled port of the peer radio |
## Usage
@@ -506,6 +509,51 @@ recording and editing use `netbox_utilities.add_devicehardware` and
`netbox_utilities.change_devicehardware`. The catalogue uses the
`netbox_utilities.*_cpumodel` permissions.
### Client software overview
Requires the [netbox-slm](https://github.com/ICTU/netbox_slm) plugin, which stores
software products, versions and installations. *Inventory → Software → Client
Software Übersicht* (in the menu of netbox-inventory, otherwise in the
*Hardware* menu of this plugin) shows for the selected tenants and tenant groups
(including subgroups):
- key figures: clients, share with recorded software, products, versions and
clients running a version past its end of support,
- charts of the most widespread products and their version distribution
(newest version strongest, expired versions hatched red),
- a sortable, searchable list of all products.
Clicking a product shows how many clients run each version and the list of
clients; clicking a version filters that list. The current selection can be
exported as CSV. Without an own selection the global tenant filter applies.
Only devices with a role from `software_device_roles` (name or slug, e.g.
`Windows Client` / `windows-client`) are included; servers and other devices
never appear. The role checkboxes narrow the selection to single client roles.
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
(`netbox_slm.view_softwareproductinstallation` and friends).
### Switch front panel
On the **Device** tab of a switch (role from `switch_device_roles`) a **Ports**
+8 -2
View File
@@ -1,12 +1,12 @@
from netbox.plugins import PluginConfig, get_plugin_config
__version__ = "0.27.3"
__version__ = "0.29.2"
class NetBoxUtilitiesConfig(PluginConfig):
name = "netbox_utilities"
verbose_name = "NetBox Utilities"
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations"
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export, client software overview and bulk operations"
version = __version__
author = "LKE"
base_url = "utilities"
@@ -32,6 +32,8 @@ class NetBoxUtilitiesConfig(PluginConfig):
"switch_ports_enabled": True,
"switch_device_roles": ["Switch"],
"wireless_trace_enabled": True,
"software_enabled": True,
"software_device_roles": ["Client", "Windows Client"],
}
middleware = [
"netbox_utilities.middleware.GlobalTenantFilterMiddleware",
@@ -80,6 +82,10 @@ class NetBoxUtilitiesConfig(PluginConfig):
from .inventory_assets import install_asset_tenant_column
install_asset_tenant_column()
if get_plugin_config("netbox_utilities", "software_enabled") and self.apps.is_installed("netbox_slm"):
from .software_integration import install_software_support
install_software_support()
if get_plugin_config("netbox_utilities", "reorder_rack_bulk_save_enabled"):
from .reorder_rack import install_reorder_rack_bulk_save
@@ -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."
)
)
+6
View File
@@ -19,6 +19,12 @@ def hardware_enabled():
return bool(get_plugin_config("netbox_utilities", "hardware_enabled"))
def software_enabled():
from django.apps import apps
return bool(get_plugin_config("netbox_utilities", "software_enabled")) and apps.is_installed("netbox_slm")
def switch_ports_enabled():
return bool(get_plugin_config("netbox_utilities", "switch_ports_enabled"))
+181
View File
@@ -0,0 +1,181 @@
"""Pure helpers for the client software overview (data from the netbox-slm plugin)."""
import re
from dataclasses import dataclass, field
from datetime import date
DEFAULT_SOFTWARE_DEVICE_ROLES = ("Client", "Windows Client")
# Number of products in the "top products" chart.
TOP_PRODUCTS = 10
def configured_roles(roles=None):
if roles is None:
try:
from netbox.plugins import get_plugin_config
roles = get_plugin_config("netbox_utilities", "software_device_roles")
except Exception: # noqa: BLE001 - outside NetBox (tests) fall back to defaults
roles = None
return {str(role).casefold() for role in (roles if roles is not None else DEFAULT_SOFTWARE_DEVICE_ROLES)}
def is_client_role(role, roles=None):
"""A role counts as client role if its name or slug is configured ("Windows Client" or "windows-client")."""
if role is None:
return False
configured = configured_roles(roles)
slugs = {name.replace(" ", "-") for name in configured}
return (
str(getattr(role, "name", "")).casefold() in configured
or str(getattr(role, "slug", "")).casefold() in configured | slugs
)
def supports_software(device, roles=None):
"""Devices with a configured client role get the "Software" tab."""
return is_client_role(getattr(device, "role", None), roles)
def version_key(name):
"""Natural sort key: "10.2" after "9.11", numbers before text, case-insensitive."""
parts = re.split(r"(\d+)", str(name or "").casefold())
return tuple((0, int(part), "") if part.isdigit() else (1, 0, part) for part in parts if part)
def percent(part, total):
return round(part * 100 / total) if total else 0
@dataclass
class VersionStats:
id: int
name: str
end_of_support: date | None = None
release_type: str = ""
devices: set = field(default_factory=set)
installations: int = 0
# Share of the product's devices, and intensity in the version chart (newest = strongest)
share: int = 0
shade: int = 100
@property
def device_count(self):
return len(self.devices)
def support_expired(self, today=None):
return bool(self.end_of_support and self.end_of_support < (today or date.today()))
@dataclass
class ProductStats:
id: int
name: str
manufacturer: str = ""
versions: dict = field(default_factory=dict)
devices: set = field(default_factory=set)
installations: int = 0
share: int = 0
bar: int = 0
@property
def device_count(self):
return len(self.devices)
@property
def version_count(self):
return len(self.versions)
@property
def versions_by_name(self):
"""Newest version first."""
return sorted(self.versions.values(), key=lambda version: version_key(version.name), reverse=True)
@property
def latest_version(self):
versions = self.versions_by_name
return versions[0] if versions else None
@property
def expired_devices(self):
return {device for version in self.versions.values() if version.support_expired() for device in version.devices}
@dataclass
class SoftwareSummary:
products: list
device_total: int
devices_with_software: int
installations: int
version_count: int
expired_device_count: int
@property
def devices_without_software(self):
return max(self.device_total - self.devices_with_software, 0)
@property
def coverage(self):
return percent(self.devices_with_software, self.device_total)
@property
def product_count(self):
return len(self.products)
@property
def top_products(self):
return self.products[:TOP_PRODUCTS]
def summarize(rows, device_total=None):
"""
Aggregate installation rows into products and versions.
Each row is a mapping with product_id, product_name, manufacturer, version_id, version_name,
end_of_support, release_type and device_id. Devices are counted once per product/version, even
if the same software was recorded twice on a device.
"""
products = {}
all_devices = set()
installations = 0
for row in rows:
installations += 1
product = products.get(row["product_id"])
if product is None:
product = products[row["product_id"]] = ProductStats(
id=row["product_id"], name=row["product_name"], manufacturer=row.get("manufacturer") or ""
)
version = product.versions.get(row["version_id"])
if version is None:
version = product.versions[row["version_id"]] = VersionStats(
id=row["version_id"],
name=row["version_name"],
end_of_support=row.get("end_of_support"),
release_type=row.get("release_type") or "",
)
product.installations += 1
version.installations += 1
product.devices.add(row["device_id"])
version.devices.add(row["device_id"])
all_devices.add(row["device_id"])
total = device_total if device_total is not None else len(all_devices)
ordered = sorted(products.values(), key=lambda product: (-product.device_count, product.name.casefold()))
most = ordered[0].device_count if ordered else 0
for product in ordered:
product.share = percent(product.device_count, total)
product.bar = percent(product.device_count, most)
versions = product.versions_by_name
for index, version in enumerate(versions):
version.share = percent(version.device_count, product.device_count)
# Newest version at 100 %, older ones fade out to 35 %.
version.shade = 100 - round(index * 65 / max(len(versions) - 1, 1))
expired = {device for product in ordered for device in product.expired_devices}
return SoftwareSummary(
products=ordered,
device_total=total,
devices_with_software=len(all_devices),
installations=installations,
version_count=sum(product.version_count for product in ordered),
expired_device_count=len(expired),
)
+68
View File
@@ -0,0 +1,68 @@
"""Hooks the client software overview into NetBox: device tab and "Software" group in the Inventory menu."""
from django.core.signals import request_started
SOFTWARE_GROUP_LABEL = "Software"
INVENTORY_MENU_LABEL = "Inventory"
FALLBACK_MENU_LABEL = "Hardware"
def software_menu_items():
from netbox.plugins import PluginMenuButton, PluginMenuItem
return (
PluginMenuItem(
link="plugins:netbox_utilities:software_overview",
link_text="Client Software Übersicht",
permissions=["netbox_slm.view_softwareproductinstallation"],
buttons=(
PluginMenuButton(
link="plugins:netbox_slm:softwareproductinstallation_add",
title="Installation erfassen",
icon_class="mdi mdi-plus-thick",
permissions=["netbox_slm.add_softwareproductinstallation"],
),
),
),
)
def add_software_group(menus):
"""
Append the "Software" group to the Inventory menu of netbox-inventory.
Falls back to the plugin's own "Hardware" menu if netbox-inventory has no top-level menu.
Returns the menu that received the group, or None.
"""
from netbox.navigation import MenuGroup
menus = list(menus)
target = next((menu for menu in menus if str(menu.label) == INVENTORY_MENU_LABEL), None)
target = target or next((menu for menu in menus if str(menu.label) == FALLBACK_MENU_LABEL), None)
if target is None:
return None
groups = list(target.groups)
if any(str(group.label) == SOFTWARE_GROUP_LABEL for group in groups):
return target
groups.append(MenuGroup(SOFTWARE_GROUP_LABEL, software_menu_items()))
target.groups = groups
return target
def _install_menu_on_first_request(**kwargs):
# All plugins have registered their menus once the first request arrives.
request_started.disconnect(dispatch_uid=__name__)
from netbox.registry import registry
add_software_group(registry["plugins"]["menus"])
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__)
+243
View File
@@ -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
+279
View File
@@ -0,0 +1,279 @@
"""Client software overview and the device "Software" tab, based on netbox-slm installations."""
import csv
from dcim.models import Device, DeviceRole
from django import forms
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.views.generic import View
from netbox.views import generic
from tenancy.models import Tenant, TenantGroup
from utilities.forms.fields import DynamicModelMultipleChoiceField
from utilities.views import ContentTypePermissionRequiredMixin, ViewTab, register_model_view
from . import software
from .tenant_scope import active_tenant_scope
INSTALLATION_PERMISSION = "netbox_slm.view_softwareproductinstallation"
ROW_FIELDS = {
"product_id": "software_product_id",
"product_name": "software_product__name",
"manufacturer": "software_product__manufacturer__name",
"version_id": "version_id",
"version_name": "version__name",
"end_of_support": "version__end_of_support",
"release_type": "version__release_type",
"device_id": "device_id",
}
def installation_model():
from netbox_slm.models import SoftwareProductInstallation
return SoftwareProductInstallation
def client_role_ids():
return [role.pk for role in DeviceRole.objects.all() if software.is_client_role(role)]
def client_roles():
return DeviceRole.objects.filter(pk__in=client_role_ids()).order_by("name")
class SoftwareOverviewFilterForm(forms.Form):
tenant_group_id = DynamicModelMultipleChoiceField(
queryset=TenantGroup.objects.all(), required=False, label="Mandantengruppe"
)
tenant_id = DynamicModelMultipleChoiceField(
queryset=Tenant.objects.all(),
required=False,
label="Mandant",
query_params={"group_id": "$tenant_group_id"},
)
# Only client roles: servers and other devices never appear in the overview.
role_id = forms.ModelMultipleChoiceField(
queryset=DeviceRole.objects.none(),
required=False,
label="Gerätrolle",
widget=forms.CheckboxSelectMultiple(attrs={"class": "form-check-input"}),
)
q = forms.CharField(required=False, label="Software suchen")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["role_id"].queryset = client_roles()
def group_tenant_ids(groups):
group_ids = set()
for group in groups:
group_ids.update(group.get_descendants(include_self=True).values_list("pk", flat=True))
return set(Tenant.objects.filter(group_id__in=group_ids).values_list("pk", flat=True))
class SoftwareOverviewView(ContentTypePermissionRequiredMixin, View):
"""Software products, versions and the clients they are installed on, per tenant or tenant group."""
template_name = "netbox_utilities/software_overview.html"
def get_required_permission(self):
return INSTALLATION_PERMISSION
def get(self, request):
params = request.GET.copy()
params.pop("submitted", None)
form = SoftwareOverviewFilterForm(params)
form.is_valid()
data = getattr(form, "cleaned_data", {})
devices = Device.objects.restrict(request.user, "view")
tenant_ids, scope_label = self.selected_tenant_ids(request, data)
if tenant_ids is not None:
devices = devices.filter(tenant_id__in=tenant_ids)
# Always clients only; no role ticked means all client roles.
devices = devices.filter(role__in=data.get("role_id") or client_role_ids())
installations = (
installation_model()
.objects.restrict(request.user, "view")
.filter(device__isnull=False, device__in=devices)
)
if q := (data.get("q") or "").strip():
installations = installations.filter(
Q(software_product__name__icontains=q)
| Q(software_product__manufacturer__name__icontains=q)
| Q(version__name__icontains=q)
)
product_id = _int(params.get("product"))
version_id = _int(params.get("version"))
if params.get("export") == "csv":
if product_id:
installations = installations.filter(software_product_id=product_id)
if version_id:
installations = installations.filter(version_id=version_id)
return csv_response(installations)
rows = [
{key: row[path] for key, path in ROW_FIELDS.items()}
for row in installations.values(*ROW_FIELDS.values())
]
summary = software.summarize(rows, device_total=devices.count())
filter_query = _query(params, drop=("product", "version", "export"))
context = {
"form": form,
"summary": summary,
"scope_label": scope_label,
"filter_query": filter_query,
"today": timezone.localdate(),
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
}
if product_id:
product = next((item for item in summary.products if item.id == product_id), None)
context.update(product_context(request, installations, product, version_id))
return render(request, self.template_name, context)
@staticmethod
def selected_tenant_ids(request, data):
"""Tenant ids to filter by (None = all) and a label if the global tenant filter applies."""
tenants, groups = data.get("tenant_id"), data.get("tenant_group_id")
if tenants or groups:
ids = {tenant.pk for tenant in tenants or ()}
if groups:
ids |= group_tenant_ids(groups)
return ids, None
scope = active_tenant_scope.get()
if scope is None:
return None, None
selected = getattr(request, "netbox_utilities_tenant_group", None) or getattr(
request, "netbox_utilities_tenant", None
)
return set(scope.tenant_ids), str(selected) if selected else "aktiv"
def product_context(request, installations, product, version_id):
"""Drill-down of one product: its versions and the devices it is installed on."""
if product is None:
return {"product_missing": True}
selected = product.versions.get(version_id) if version_id else None
queryset = installations.filter(software_product_id=product.id)
if selected:
queryset = queryset.filter(version_id=selected.id)
entries = sorted(
queryset.select_related("device", "device__tenant", "device__site", "device__role", "version"),
key=lambda entry: (entry.device.name or "").casefold(),
)
return {
"product": product,
"product_obj": product_object(request, product.id),
"selected_version": selected,
"entries": entries,
}
def product_object(request, product_id):
from netbox_slm.models import SoftwareProduct
return SoftwareProduct.objects.restrict(request.user, "view").filter(pk=product_id).first()
def csv_response(installations):
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = 'attachment; filename="client-software.csv"'
response.write("") # Excel recognises UTF-8 with BOM
writer = csv.writer(response, delimiter=";")
writer.writerow(["Mandant", "Rechner", "Rolle", "Standort", "Hersteller", "Software", "Version", "Support-Ende"])
queryset = installations.select_related(
"device__tenant", "device__role", "device__site", "software_product__manufacturer", "version"
).order_by("device__tenant__name", "device__name", "software_product__name")
for entry in queryset:
device = entry.device
writer.writerow(
[
device.tenant or "",
device.name or "",
device.role or "",
device.site or "",
entry.software_product.manufacturer or "",
entry.software_product,
entry.version,
entry.version.end_of_support or "",
]
)
return response
def _int(value):
try:
return int(value)
except (TypeError, ValueError):
return None
def _query(params, drop=()):
params = params.copy()
for key in drop:
params.pop(key, None)
params["submitted"] = "1"
return params.urlencode()
#
# Device tab
#
def software_tab_badge(device):
"""Number of installations; hidden for devices without client role and without software."""
from .runtime import software_enabled
if not software_enabled():
return None
count = installation_model().objects.filter(device=device).count()
if count:
return str(count)
return "0" if software.supports_software(device) else None
@register_model_view(Device, "software", path="software")
class DeviceSoftwareTabView(generic.ObjectView):
queryset = Device.objects.all()
template_name = "netbox_utilities/device_software.html"
tab = ViewTab(
label="Software",
badge=software_tab_badge,
permission=INSTALLATION_PERMISSION,
weight=2070,
hide_if_empty=True,
)
def get_extra_context(self, request, instance):
entries = sorted(
installation_model()
.objects.restrict(request.user, "view")
.filter(device=instance)
.select_related("software_product", "software_product__manufacturer", "version"),
key=lambda entry: (entry.software_product.name.casefold(), software.version_key(entry.version.name)),
)
tab_url = reverse("dcim:device_software", kwargs={"pk": instance.pk})
overview_url = reverse("plugins:netbox_utilities:software_overview")
if instance.tenant_id:
overview_url += f"?submitted=1&tenant_id={instance.tenant_id}"
return {
"entries": entries,
"today": timezone.localdate(),
"supported": software.supports_software(instance),
"tab_url": tab_url,
"overview_url": overview_url,
"add_url": f"{reverse('plugins:netbox_slm:softwareproductinstallation_add')}?device={instance.pk}"
f"&return_url={tab_url}",
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
"can_change": request.user.has_perm("netbox_slm.change_softwareproductinstallation"),
"can_delete": request.user.has_perm("netbox_slm.delete_softwareproductinstallation"),
}
@@ -562,3 +562,203 @@ a.nbu-disk-slot[draggable="true"] {
border-color: #fd7e14 transparent transparent transparent;
background: none;
}
/* Client Software Übersicht */
.nbu-sw-filter-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem 1.5rem;
margin-top: 1rem;
padding-top: 0.875rem;
border-top: 1px solid var(--tblr-border-color);
}
.nbu-sw-roles {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.nbu-sw-roles-label {
color: var(--tblr-secondary);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
margin-right: 0.25rem;
}
.nbu-sw-role {
border: 1px solid var(--tblr-border-color);
background: var(--tblr-bg-surface);
color: var(--tblr-body-color);
white-space: nowrap;
}
.nbu-sw-role:hover {
border-color: var(--tblr-primary);
color: var(--tblr-primary);
}
.btn-check:checked + .nbu-sw-role {
background: var(--tblr-primary);
border-color: var(--tblr-primary);
color: var(--tblr-primary-fg, #fff);
}
.btn-check:focus-visible + .nbu-sw-role {
box-shadow: 0 0 0 0.2rem rgba(var(--tblr-primary-rgb), 0.25);
}
.nbu-sw-filter-hint {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
font-size: 0.8125rem;
}
.nbu-sw-kpi-label {
color: var(--tblr-secondary);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.nbu-sw-kpi-value {
font-size: 1.75rem;
font-weight: 700;
line-height: 1.2;
font-variant-numeric: tabular-nums;
}
.nbu-sw-kpi-hint {
color: var(--tblr-secondary);
font-size: 0.8125rem;
margin-top: 0.25rem;
}
.nbu-sw-kpi-warning {
border-left: 4px solid var(--tblr-danger);
}
.nbu-sw-kpi-warning .nbu-sw-kpi-value {
color: var(--tblr-danger);
}
.nbu-sw-bars li + li {
margin-top: 0.25rem;
}
.nbu-sw-bar-row {
display: grid;
grid-template-columns: minmax(6rem, 13rem) 1fr minmax(5.5rem, auto);
gap: 0.75rem;
align-items: center;
padding: 0.3rem 0.5rem;
border-radius: var(--tblr-border-radius);
color: inherit;
text-decoration: none;
}
.nbu-sw-bar-row:hover,
.nbu-sw-bar-row:focus-visible,
.nbu-sw-bar-row.active {
background: var(--tblr-bg-surface-secondary, rgba(var(--tblr-primary-rgb), 0.06));
color: inherit;
text-decoration: none;
}
.nbu-sw-bar-row.active {
outline: 2px solid rgba(var(--tblr-primary-rgb), 0.5);
}
.nbu-sw-bar-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.nbu-sw-bar-track {
height: 0.75rem;
border-radius: 999px;
background: rgba(var(--tblr-secondary-rgb, 108, 122, 145), 0.15);
overflow: hidden;
}
.nbu-sw-bar-fill {
display: block;
height: 100%;
min-width: 2px;
border-radius: 999px;
background: color-mix(in srgb, var(--tblr-primary) var(--nbu-sw-shade, 100%), transparent);
}
.nbu-sw-bar-value {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
/* Versionsverteilung als gestapelter Balken, neueste Version links und am kräftigsten */
.nbu-sw-stack {
display: flex;
gap: 2px;
height: 0.75rem;
min-width: 6rem;
border-radius: 999px;
overflow: hidden;
}
.nbu-sw-stack-part {
min-width: 3px;
background: color-mix(in srgb, var(--tblr-primary) var(--nbu-sw-shade, 100%), transparent);
}
.nbu-sw-stack-part.nbu-sw-expired,
.nbu-sw-bar-fill.nbu-sw-expired {
background: repeating-linear-gradient(
135deg,
var(--tblr-danger) 0 4px,
color-mix(in srgb, var(--tblr-danger) 45%, transparent) 4px 8px
);
}
.nbu-sw-sortable {
cursor: pointer;
user-select: none;
white-space: nowrap;
}
.nbu-sw-sortable::after {
content: "\F04BF"; /* mdi-unfold-more-horizontal */
font-family: "Material Design Icons";
margin-left: 0.25rem;
opacity: 0.35;
}
.nbu-sw-sortable[aria-sort="ascending"]::after {
content: "\F0143"; /* mdi-chevron-up */
opacity: 1;
}
.nbu-sw-sortable[aria-sort="descending"]::after {
content: "\F0140"; /* mdi-chevron-down */
opacity: 1;
}
@media (max-width: 575.98px) {
.nbu-sw-bar-row {
grid-template-columns: 1fr minmax(4.5rem, auto);
}
.nbu-sw-bar-row .nbu-sw-bar-track,
.nbu-sw-bar-row .nbu-sw-stack {
grid-column: 1 / -1;
grid-row: 2;
}
}
@@ -0,0 +1,77 @@
{% extends 'dcim/device/base.html' %}
{% load helpers %}
{% block content %}
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">
<i class="mdi mdi-package-variant me-1" aria-hidden="true"></i>Installierte Software
<span class="badge text-bg-secondary ms-1">{{ entries|length }}</span>
</h2>
{% if entries|length > 8 %}
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-device-software"
placeholder="Software filtern …" aria-label="Software filtern">
{% endif %}
<a href="{{ overview_url }}" class="btn btn-sm btn-outline-secondary" title="Client Software Übersicht für den Mandanten dieses Geräts">
<i class="mdi mdi-chart-bar" aria-hidden="true"></i> Übersicht{% if object.tenant %} {{ object.tenant }}{% endif %}
</a>
{% if can_add %}
<a href="{{ add_url }}" class="btn btn-sm btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Software hinzufügen</a>
{% endif %}
</div>
{% if entries %}
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0" id="nbu-sw-device-software">
<thead>
<tr>
<th data-nbu-sort="text">Software</th>
<th data-nbu-sort="text">Hersteller</th>
<th data-nbu-sort="text">Version</th>
<th>Release</th>
<th data-nbu-sort="text">Support-Ende</th>
<th></th>
</tr>
</thead>
<tbody>
{% for entry in entries %}
{% with product=entry.software_product version=entry.version %}
<tr>
<td><a href="{{ product.get_absolute_url }}" class="fw-bold">{{ product }}</a></td>
<td>{{ product.manufacturer|placeholder }}</td>
<td><a href="{{ version.get_absolute_url }}">{{ version }}</a></td>
<td>{{ version.get_release_type_display|placeholder }}</td>
<td>
{% if version.end_of_support %}
{% if version.end_of_support < today %}
<span class="badge text-bg-danger" title="Support abgelaufen">{{ version.end_of_support|isodate }}</span>
{% else %}{{ version.end_of_support|isodate }}{% endif %}
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
<td class="text-end text-nowrap">
{% if can_change %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_edit' pk=entry.pk %}?return_url={{ tab_url|urlencode }}" class="btn btn-sm btn-warning" title="Bearbeiten">
<i class="mdi mdi-pencil" aria-hidden="true"></i>
</a>
{% endif %}
{% if can_delete %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_delete' pk=entry.pk %}?return_url={{ tab_url|urlencode }}" class="btn btn-sm btn-danger" title="Entfernen">
<i class="mdi mdi-trash-can-outline" aria-hidden="true"></i>
</a>
{% endif %}
</td>
</tr>
{% endwith %}
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="card-body text-center text-muted py-5">
<i class="mdi mdi-package-variant-closed mdi-48px d-block mb-2" aria-hidden="true"></i>
Für dieses Gerät ist noch keine Software erfasst.
{% if can_add %}<div class="mt-3"><a href="{{ add_url }}" class="btn btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Software hinzufügen</a></div>{% endif %}
</div>
{% endif %}
</div>
{% include 'netbox_utilities/inc/software_table_js.html' %}
{% endblock %}
@@ -0,0 +1,115 @@
{% load helpers %}
<nav class="mb-2" aria-label="Navigation">
<a href="?{{ filter_query }}" class="btn btn-sm btn-outline-secondary">
<i class="mdi mdi-arrow-left" aria-hidden="true"></i> Alle Software-Produkte
</a>
</nav>
<div class="row row-cards mb-3">
<div class="col-12 col-xl-5">
<div class="card h-100">
<div class="card-header d-flex align-items-center">
<div class="me-auto">
<h2 class="card-title mb-0">{{ product.name }}</h2>
<div class="text-muted small">{{ product.manufacturer|default:"Kein Hersteller" }}</div>
</div>
{% if product_obj %}
<a href="{{ product_obj.get_absolute_url }}" class="btn btn-sm btn-outline-primary" title="Produkt in netbox-slm öffnen">
<i class="mdi mdi-open-in-new" aria-hidden="true"></i> Produkt
</a>
{% endif %}
</div>
<div class="card-body">
<div class="row text-center mb-3">
<div class="col"><div class="nbu-sw-kpi-value">{{ product.device_count }}</div><div class="nbu-sw-kpi-label">Rechner</div></div>
<div class="col"><div class="nbu-sw-kpi-value">{{ product.share }} %</div><div class="nbu-sw-kpi-label">der Rechner</div></div>
<div class="col"><div class="nbu-sw-kpi-value">{{ product.version_count }}</div><div class="nbu-sw-kpi-label">Versionen</div></div>
</div>
{% with item=product %}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% endwith %}
</div>
</div>
</div>
<div class="col-12 col-xl-7">
<div class="card h-100">
<h2 class="card-header">Rechner je Version <span class="text-muted fw-normal small ms-1">anklicken zum Filtern</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for version in product.versions_by_name %}
<li>
<a href="?{{ filter_query }}&product={{ product.id }}{% if selected_version.id != version.id %}&version={{ version.id }}{% endif %}"
class="nbu-sw-bar-row{% if selected_version.id == version.id %} active{% endif %}"
aria-current="{% if selected_version.id == version.id %}true{% else %}false{% endif %}">
<span class="nbu-sw-bar-label">
{{ version.name }}
{% if forloop.first %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
{% if version.support_expired %}<span class="badge text-bg-danger ms-1" title="Support-Ende {{ version.end_of_support|isodate }}">EoS</span>{% endif %}
</span>
<span class="nbu-sw-bar-track"><span class="nbu-sw-bar-fill{% if version.support_expired %} nbu-sw-expired{% endif %}" style="width: {{ version.share }}%; --nbu-sw-shade: {{ version.shade }}%"></span></span>
<span class="nbu-sw-bar-value">{{ version.device_count }}<span class="text-muted"> · {{ version.share }} %</span></span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">
Installiert auf
<span class="badge text-bg-secondary ms-1">{{ entries|length }}</span>
{% if selected_version %}
<a href="?{{ filter_query }}&product={{ product.id }}" class="badge text-bg-primary ms-1 text-decoration-none" title="Versionsfilter entfernen">
Version {{ selected_version.name }} <i class="mdi mdi-close" aria-hidden="true"></i>
</a>
{% endif %}
</h2>
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-devices"
placeholder="Rechner, Mandant, Standort …" aria-label="Rechnerliste filtern">
</div>
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0" id="nbu-sw-devices">
<thead>
<tr>
<th data-nbu-sort="text">Rechner</th>
<th data-nbu-sort="text">Mandant</th>
<th data-nbu-sort="text">Standort</th>
<th data-nbu-sort="text">Rolle</th>
<th data-nbu-sort="text">Version</th>
<th data-nbu-sort="text">Support-Ende</th>
<th></th>
</tr>
</thead>
<tbody>
{% for entry in entries %}
{% with device=entry.device version=entry.version %}
<tr>
<td><a href="{% url 'dcim:device_software' pk=device.pk %}" class="fw-bold">{{ device }}</a></td>
<td>{{ device.tenant|linkify|placeholder }}</td>
<td>{{ device.site|linkify|placeholder }}</td>
<td>{{ device.role|placeholder }}</td>
<td>
{{ version.name }}
{% if product.latest_version.id == version.id %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
</td>
<td>
{% if version.end_of_support %}
<span class="{% if version.end_of_support < today %}text-danger fw-bold{% endif %}">{{ version.end_of_support|isodate }}</span>
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
<td class="text-end">
<a href="{{ entry.get_absolute_url }}" class="btn btn-sm btn-outline-secondary" title="Installation öffnen">
<i class="mdi mdi-open-in-new" aria-hidden="true"></i>
</a>
</td>
</tr>
{% endwith %}
{% empty %}
<tr><td colspan="7" class="text-muted text-center py-4">Keine Installationen.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
@@ -0,0 +1,41 @@
<script>
document.addEventListener("DOMContentLoaded", () => {
// Liste filtern: Zeilen ausblenden, deren Suchtext nicht passt
for (const input of document.querySelectorAll("[data-nbu-sw-search]")) {
const rows = document.querySelectorAll(`${input.dataset.nbuSwSearch} tbody tr`);
input.addEventListener("input", () => {
const terms = input.value.toLowerCase().split(/\s+/).filter(Boolean);
for (const row of rows) {
const text = row.dataset.nbuSearch || row.textContent.toLowerCase();
row.hidden = !terms.every((term) => text.includes(term));
}
});
}
// Sortieren per Klick auf den Spaltenkopf
for (const header of document.querySelectorAll("th[data-nbu-sort]")) {
header.classList.add("nbu-sw-sortable");
header.tabIndex = 0;
const sort = () => {
const table = header.closest("table");
const index = [...header.parentElement.children].indexOf(header);
const numeric = header.dataset.nbuSort === "number";
const ascending = header.getAttribute("aria-sort") !== "ascending";
for (const other of header.parentElement.children) other.removeAttribute("aria-sort");
header.setAttribute("aria-sort", ascending ? "ascending" : "descending");
const body = table.tBodies[0];
const value = (row) => {
const cell = row.children[index];
return numeric ? Number(cell.dataset.value ?? cell.textContent) || 0 : cell.textContent.trim().toLowerCase();
};
const rows = [...body.rows].sort((a, b) => {
const [x, y] = [value(a), value(b)];
const result = numeric ? x - y : x.localeCompare(y, "de", { numeric: true });
return ascending ? result : -result;
});
body.append(...rows);
};
header.addEventListener("click", sort);
header.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); sort(); } });
}
});
</script>
@@ -0,0 +1,7 @@
<span class="nbu-sw-stack" role="img" aria-label="Versionsverteilung {{ item.name }}: {% for version in item.versions_by_name %}{{ version.name }} {{ version.device_count }} Rechner{% if not forloop.last %}, {% endif %}{% endfor %}">
{% for version in item.versions_by_name %}
<span class="nbu-sw-stack-part{% if version.support_expired %} nbu-sw-expired{% endif %}"
style="flex-grow: {{ version.device_count }}; --nbu-sw-shade: {{ version.shade }}%"
title="{{ version.name }}: {{ version.device_count }} Rechner ({{ version.share }} %){% if version.support_expired %} · Support abgelaufen{% endif %}"></span>
{% endfor %}
</span>
@@ -0,0 +1,219 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% block title %}{% if product %}{{ product.name }} · {% endif %}Client Software Übersicht{% endblock %}
{% block controls %}
<div class="btn-list">
<a href="?{{ filter_query }}{% if product %}&product={{ product.id }}{% if selected_version %}&version={{ selected_version.id }}{% endif %}{% endif %}&export=csv"
class="btn btn-purple" title="Aktuelle Auswahl als CSV (Excel) herunterladen">
<i class="mdi mdi-download" aria-hidden="true"></i> CSV exportieren
</a>
{% if can_add %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_add' %}?return_url={{ request.get_full_path|urlencode }}" class="btn btn-primary">
<i class="mdi mdi-plus-thick" aria-hidden="true"></i> Installation erfassen
</a>
{% endif %}
</div>
{% endblock controls %}
{% block content %}
{# Filter #}
<form method="get" class="card mb-3 nbu-sw-filter">
<input type="hidden" name="submitted" value="1">
{% if product %}<input type="hidden" name="product" value="{{ product.id }}">{% endif %}
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-12 col-md-6 col-xl-3">
<label class="form-label" for="{{ form.tenant_group_id.id_for_label }}">Mandantengruppe</label>
{{ form.tenant_group_id }}
</div>
<div class="col-12 col-md-6 col-xl-3">
<label class="form-label" for="{{ form.tenant_id.id_for_label }}">Mandant</label>
{{ form.tenant_id }}
</div>
<div class="col-12 col-md-8 col-xl-4">
<label class="form-label" for="id_q">Software suchen</label>
<div class="input-icon">
<span class="input-icon-addon"><i class="mdi mdi-magnify" aria-hidden="true"></i></span>
<input type="search" name="q" id="id_q" value="{{ form.q.value|default:'' }}" class="form-control"
placeholder="Produkt, Hersteller oder Version">
</div>
</div>
<div class="col-12 col-md-4 col-xl-2 d-flex gap-2">
<button type="submit" class="btn btn-primary flex-grow-1">
<i class="mdi mdi-filter" aria-hidden="true"></i> Anwenden
</button>
<a href="{% url 'plugins:netbox_utilities:software_overview' %}" class="btn btn-outline-secondary btn-icon"
title="Filter zurücksetzen" aria-label="Filter zurücksetzen">
<i class="mdi mdi-filter-remove-outline" aria-hidden="true"></i>
</a>
</div>
</div>
<div class="nbu-sw-filter-footer">
<div class="nbu-sw-roles" role="group" aria-label="Gerätrolle">
<span class="nbu-sw-roles-label">Gerätrolle</span>
{% for choice in form.role_id %}
<input type="checkbox" class="btn-check" name="{{ form.role_id.html_name }}" value="{{ choice.data.value }}"
id="{{ choice.id_for_label }}" autocomplete="off" onchange="this.form.requestSubmit()"
{% if choice.data.selected %}checked{% endif %}>
<label class="btn btn-sm btn-pill nbu-sw-role" for="{{ choice.id_for_label }}">
<i class="mdi mdi-laptop" aria-hidden="true"></i> {{ choice.choice_label }}
</label>
{% empty %}
<span class="text-danger small">Keine Client-Rolle gefunden – <code>software_device_roles</code> prüfen.</span>
{% endfor %}
</div>
<div class="nbu-sw-filter-hint">
{% if scope_label %}
<span class="badge bg-primary-lt"><i class="mdi mdi-filter-check" aria-hidden="true"></i> Globaler Filter: {{ scope_label }}</span>
<span class="text-secondary">Eigene Auswahl hat Vorrang.</span>
{% else %}
<span class="text-secondary">Gruppen schließen Untergruppen ein. Ohne Rollenauswahl: alle Client-Rollen.</span>
{% endif %}
</div>
</div>
</div>
</form>
{# Kennzahlen #}
<div class="row row-cards mb-3">
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Rechner</div>
<div class="nbu-sw-kpi-value">{{ summary.device_total }}</div>
<div class="nbu-sw-kpi-hint">{{ summary.devices_with_software }} mit erfasster Software</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Erfassungsgrad</div>
<div class="nbu-sw-kpi-value">{{ summary.coverage }} %</div>
<div class="progress progress-sm mt-2" role="progressbar" aria-label="Erfassungsgrad" aria-valuenow="{{ summary.coverage }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ summary.coverage }}%"></div>
</div>
<div class="nbu-sw-kpi-hint">{{ summary.devices_without_software }} Rechner ohne Software</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Software-Produkte</div>
<div class="nbu-sw-kpi-value">{{ summary.product_count }}</div>
<div class="nbu-sw-kpi-hint">{{ summary.version_count }} Version{{ summary.version_count|pluralize:"en" }} · {{ summary.installations }} Installation{{ summary.installations|pluralize:"en" }}</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi{% if summary.expired_device_count %} nbu-sw-kpi-warning{% endif %}"><div class="card-body">
<div class="nbu-sw-kpi-label">Support abgelaufen</div>
<div class="nbu-sw-kpi-value">{{ summary.expired_device_count }}</div>
<div class="nbu-sw-kpi-hint">Rechner mit mindestens einer Version nach Support-Ende</div>
</div></div>
</div>
</div>
{% if product_missing %}
<div class="alert alert-warning">Dieses Produkt ist mit der aktuellen Auswahl auf keinem Rechner installiert.
<a href="?{{ filter_query }}">Zur Übersicht</a></div>
{% endif %}
{% if product %}
{% include 'netbox_utilities/inc/software_product.html' %}
{% elif summary.products %}
<div class="row row-cards mb-3">
{# Diagramm: Top-Produkte #}
<div class="col-12 col-xl-6">
<div class="card h-100">
<h2 class="card-header">Verbreitetste Software <span class="text-muted fw-normal small ms-1">Rechner je Produkt</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for item in summary.top_products %}
<li>
<a href="?{{ filter_query }}&product={{ item.id }}" class="nbu-sw-bar-row" title="{{ item.name }}: {{ item.device_count }} Rechner ({{ item.share }} %)">
<span class="nbu-sw-bar-label">{{ item.name }}</span>
<span class="nbu-sw-bar-track"><span class="nbu-sw-bar-fill" style="width: {{ item.bar }}%"></span></span>
<span class="nbu-sw-bar-value">{{ item.device_count }}<span class="text-muted"> · {{ item.share }} %</span></span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{# Diagramm: Versionsverteilung #}
<div class="col-12 col-xl-6">
<div class="card h-100">
<h2 class="card-header">Versionsverteilung <span class="text-muted fw-normal small ms-1">neueste Version am kräftigsten</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for item in summary.top_products %}
<li>
<a href="?{{ filter_query }}&product={{ item.id }}" class="nbu-sw-bar-row">
<span class="nbu-sw-bar-label">{{ item.name }}</span>
{% include 'netbox_utilities/inc/software_version_stack.html' %}
<span class="nbu-sw-bar-value">{{ item.version_count }} Version{{ item.version_count|pluralize:"en" }}</span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
{# Tabelle aller Produkte #}
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">Alle Software-Produkte <span class="badge text-bg-secondary ms-1">{{ summary.product_count }}</span></h2>
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-products"
placeholder="In Liste filtern …" aria-label="Produktliste filtern">
</div>
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0 nbu-sw-table" id="nbu-sw-products">
<thead>
<tr>
<th data-nbu-sort="text">Produkt</th>
<th data-nbu-sort="text">Hersteller</th>
<th data-nbu-sort="number" class="text-end">Rechner</th>
<th data-nbu-sort="number" class="text-end">Anteil</th>
<th data-nbu-sort="number" class="text-end">Versionen</th>
<th style="min-width: 12rem">Verteilung</th>
<th>Neueste Version</th>
<th data-nbu-sort="number" class="text-end">Support abgelaufen</th>
</tr>
</thead>
<tbody>
{% for item in summary.products %}
<tr data-nbu-search="{{ item.name|lower }} {{ item.manufacturer|lower }}{% for version in item.versions_by_name %} {{ version.name|lower }}{% endfor %}">
<td><a href="?{{ filter_query }}&product={{ item.id }}" class="fw-bold">{{ item.name }}</a></td>
<td>{{ item.manufacturer|placeholder }}</td>
<td class="text-end" data-value="{{ item.device_count }}">{{ item.device_count }}</td>
<td class="text-end" data-value="{{ item.share }}">{{ item.share }} %</td>
<td class="text-end" data-value="{{ item.version_count }}">{{ item.version_count }}</td>
<td>{% include 'netbox_utilities/inc/software_version_stack.html' %}</td>
<td>{% with latest=item.latest_version %}{{ latest.name }} <span class="text-muted small">({{ latest.device_count }})</span>{% endwith %}</td>
{% with expired=item.expired_devices|length %}
<td class="text-end" data-value="{{ expired }}">{% if expired %}<span class="badge text-bg-danger">{{ expired }}</span>{% else %}<span class="text-muted">—</span>{% endif %}</td>
{% endwith %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer text-muted small">Spaltenköpfe anklicken zum Sortieren, Produkt anklicken für Versionen und Rechner.</div>
</div>
{% else %}
<div class="card"><div class="card-body text-center text-muted py-5">
<i class="mdi mdi-package-variant-closed mdi-48px d-block mb-2" aria-hidden="true"></i>
<div class="fs-3 fw-semibold text-body mb-1">Für diese Auswahl ist keine Software erfasst</div>
<div class="mx-auto" style="max-width: 36rem;">
Softwarelisten des Windows-Agents und des NetBox Synchronizers werden beim Speichern eines Geräts übernommen.
Bereits vorhandene Berichte überträgt einmalig
<code>manage.py netbox_utilities_sync_software</code>.
</div>
{% if can_add %}<div class="mt-3"><a href="{% url 'plugins:netbox_slm:softwareproductinstallation_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Installation erfassen</a></div>{% endif %}
</div></div>
{% endif %}
{% include 'netbox_utilities/inc/software_table_js.html' %}
{% endblock content %}
+85
View File
@@ -0,0 +1,85 @@
from datetime import date
from types import SimpleNamespace
from django.test import SimpleTestCase
from netbox_utilities import software
def row(product, version, device, *, product_name=None, version_name=None, eos=None):
return {
"product_id": product,
"product_name": product_name or f"Produkt {product}",
"manufacturer": "Hersteller",
"version_id": version,
"version_name": version_name or str(version),
"end_of_support": eos,
"release_type": "S",
"device_id": device,
}
class SoftwareSummaryTest(SimpleTestCase):
def test_counts_devices_once_and_orders_products_by_spread(self):
summary = software.summarize(
[
row(1, 10, 100),
row(1, 10, 100), # same software recorded twice on one device
row(2, 20, 100),
row(2, 21, 101),
row(2, 21, 102),
],
device_total=4,
)
self.assertEqual([product.id for product in summary.products], [2, 1])
self.assertEqual(summary.products[0].device_count, 3)
self.assertEqual(summary.products[0].share, 75)
self.assertEqual(summary.products[1].bar, 33)
self.assertEqual(summary.installations, 5)
self.assertEqual(summary.devices_with_software, 3)
self.assertEqual(summary.devices_without_software, 1)
self.assertEqual(summary.coverage, 75)
self.assertEqual(summary.version_count, 3)
def test_versions_are_sorted_naturally_newest_first(self):
summary = software.summarize(
[row(1, 1, 1, version_name="9.11"), row(1, 2, 2, version_name="10.2"), row(1, 3, 3, version_name="10.10")]
)
product = summary.products[0]
self.assertEqual([version.name for version in product.versions_by_name], ["10.10", "10.2", "9.11"])
self.assertEqual(product.latest_version.name, "10.10")
self.assertEqual([version.shade for version in product.versions_by_name], [100, 68, 35])
def test_expired_support_counts_affected_devices(self):
summary = software.summarize(
[row(1, 1, 1, eos=date(2000, 1, 1)), row(1, 2, 2), row(2, 3, 1, eos=date(2001, 1, 1))]
)
self.assertEqual(summary.expired_device_count, 1)
self.assertEqual(summary.products[0].expired_devices, {1})
def test_empty_selection(self):
summary = software.summarize([], device_total=0)
self.assertEqual(summary.products, [])
self.assertEqual(summary.coverage, 0)
def test_client_role_detection_is_case_insensitive(self):
client = SimpleNamespace(role=SimpleNamespace(name="clients"))
server = SimpleNamespace(role=SimpleNamespace(name="Server"))
self.assertTrue(software.supports_software(client, roles=["Clients"]))
self.assertFalse(software.supports_software(server, roles=["Clients"]))
self.assertFalse(software.supports_software(SimpleNamespace(role=None), roles=["Clients"]))
def test_default_client_roles_match_name_or_slug_but_not_servers(self):
def role(name, slug):
return SimpleNamespace(name=name, slug=slug)
roles = software.DEFAULT_SOFTWARE_DEVICE_ROLES
self.assertTrue(software.is_client_role(role("Client", "client"), roles))
self.assertTrue(software.is_client_role(role("Windows Client", "windows-client"), roles))
self.assertTrue(software.is_client_role(role("Windows-Clients", "windows-client"), roles))
self.assertFalse(software.is_client_role(role("Server", "server"), roles))
@@ -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")
+9
View File
@@ -1,4 +1,6 @@
from django.apps import apps
from django.urls import include, path
from netbox.plugins import get_plugin_config
from utilities.urls import get_model_urls
from . import disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views
@@ -41,3 +43,10 @@ urlpatterns = [
path("devices/<int:pk>/disks/fill/", disk_views.DeviceDiskBulkFillView.as_view(), name="device_disk_fill"),
path("devices/<int:pk>/disks/move/", disk_views.DeviceDiskMoveView.as_view(), name="device_disk_move"),
]
if get_plugin_config("netbox_utilities", "software_enabled") and apps.is_installed("netbox_slm"):
from . import software_views
urlpatterns.append(
path("software/", software_views.SoftwareOverviewView.as_view(), name="software_overview"),
)
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "netbox-utilities"
version = "0.27.3"
version = "0.29.2"
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"