Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b8ab882f0 | ||
|
|
839c5ad2ac | ||
|
|
ef12531c8e | ||
|
|
98c8647501 | ||
|
|
d6622cf48f | ||
|
|
1f338902a7 |
No files matched your search
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#define AppName "NetBox Synchronizer"
|
#define AppName "NetBox Synchronizer"
|
||||||
#ifndef AppVersion
|
#ifndef AppVersion
|
||||||
#define AppVersion "4.20.1"
|
#define AppVersion "4.20.4"
|
||||||
#endif
|
#endif
|
||||||
#define AppPublisher "Louis-Alexander Kerst"
|
#define AppPublisher "Louis-Alexander Kerst"
|
||||||
#define AppExeName "NetBoxSynchronizer.exe"
|
#define AppExeName "NetBoxSynchronizer.exe"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||||
|
|
||||||
APP_NAME = "NetBox Synchronizer"
|
APP_NAME = "NetBox Synchronizer"
|
||||||
APP_VERSION = "4.20.1"
|
APP_VERSION = "4.20.4"
|
||||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,80 @@ written; the report lists what would change.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
import time
|
||||||
|
|
||||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
||||||
from netbox_sync.core.clients import os_label
|
from netbox_sync.core.clients import os_label
|
||||||
|
|
||||||
|
|
||||||
|
REPORT_START = "<!-- netbox-sync:inventory -->"
|
||||||
|
REPORT_END = "<!-- /netbox-sync:inventory -->"
|
||||||
|
|
||||||
|
|
||||||
|
def inventory_report(client):
|
||||||
|
"""Markdown hardware and software report of an agent scan, or ``""`` for other sources."""
|
||||||
|
if client.get("source") != "agent":
|
||||||
|
return ""
|
||||||
|
lines = ["## Inventar (NetBox Windows Agent)", ""]
|
||||||
|
for caption, value in (
|
||||||
|
("System", " ".join(part for part in (client.get("manufacturer"), client.get("model")) if part)),
|
||||||
|
("Seriennummer", client.get("serial")),
|
||||||
|
("Betriebssystem", " ".join(part for part in (client.get("os"), client.get("os_display_version"),
|
||||||
|
f"(Build {client['os_build']})" if client.get("os_build")
|
||||||
|
else "") if part)),
|
||||||
|
("CPU", f"{client['cpu']} ({client.get('cores') or '?'} Kerne)" if client.get("cpu") else ""),
|
||||||
|
("RAM", f"{client['memory'] / 1024 ** 3:.0f} GB" if client.get("memory") else ""),
|
||||||
|
("Erfasst", client.get("scanned_at") and time.strftime("%d.%m.%Y %H:%M", time.localtime(client["scanned_at"]))),
|
||||||
|
):
|
||||||
|
if value:
|
||||||
|
lines.append(f"- **{caption}:** {value}")
|
||||||
|
if client.get("disks"):
|
||||||
|
lines += ["", "### Datenträger"]
|
||||||
|
lines += [f"- {disk['model']} – {disk['size'] / 1e9:.0f} GB" + (f" – S/N {disk['serial']}" if disk.get("serial")
|
||||||
|
else "") for disk in client["disks"]]
|
||||||
|
if client.get("memory_modules"):
|
||||||
|
lines += ["", "### Arbeitsspeicher"]
|
||||||
|
lines += [f"- {item['bank'] or 'RAM'}: {item['capacity'] / 1024 ** 3:.0f} GB"
|
||||||
|
+ (f" {item['manufacturer']}" if item.get("manufacturer") else "")
|
||||||
|
+ (f" {item['part_number']}" if item.get("part_number") else "") for item in client["memory_modules"]]
|
||||||
|
software = client.get("software") or []
|
||||||
|
if software:
|
||||||
|
lines += ["", f"### Installierte Software ({len(software)})", "", "| Programm | Version | Hersteller |",
|
||||||
|
"|---|---|---|"]
|
||||||
|
lines += [f"| {_cell(item['name'])} | {_cell(item['version'])} | {_cell(item['publisher'])} |"
|
||||||
|
for item in software]
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _cell(text):
|
||||||
|
return str(text or "").replace("|", "/").replace("\n", " ").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def merge_report(comments, report):
|
||||||
|
"""Replace the managed report block in ``comments`` and keep everything written by hand."""
|
||||||
|
comments = comments or ""
|
||||||
|
block = f"{REPORT_START}\n{report}\n{REPORT_END}"
|
||||||
|
if REPORT_START in comments and REPORT_END in comments:
|
||||||
|
before, rest = comments.split(REPORT_START, 1)
|
||||||
|
after = rest.split(REPORT_END, 1)[1]
|
||||||
|
return f"{before}{block}{after}"
|
||||||
|
return f"{comments.rstrip()}\n\n{block}" if comments.strip() else block
|
||||||
|
|
||||||
|
|
||||||
|
def _without_timestamp(text):
|
||||||
|
"""The scan time changes every scan – it alone is no reason to update the report."""
|
||||||
|
return re.sub(r"^- \*\*Erfasst:\*\*.*$", "", text or "", flags=re.MULTILINE)
|
||||||
|
|
||||||
|
|
||||||
|
def _report_body(comments):
|
||||||
|
if REPORT_START in (comments or "") and REPORT_END in comments:
|
||||||
|
return comments.split(REPORT_START, 1)[1].split(REPORT_END, 1)[0].strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_UNKNOWN = object()
|
||||||
|
|
||||||
|
|
||||||
def _noop(*_args, **_kwargs):
|
def _noop(*_args, **_kwargs):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -66,6 +135,7 @@ class ClientSyncEngine:
|
|||||||
self._device_types = {}
|
self._device_types = {}
|
||||||
self._platforms = {}
|
self._platforms = {}
|
||||||
self._planned = set()
|
self._planned = set()
|
||||||
|
self._asset_endpoint = _UNKNOWN
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Lookups
|
# Lookups
|
||||||
@@ -156,7 +226,80 @@ class ClientSyncEngine:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def new_report():
|
def new_report():
|
||||||
return {"devices_created": 0, "devices_updated": 0, "devices_unchanged": 0, "objects_created": 0,
|
return {"devices_created": 0, "devices_updated": 0, "devices_unchanged": 0, "objects_created": 0,
|
||||||
"interfaces_created": 0, "ips_created": 0, "changes": [], "errors": [], "items": []}
|
"interfaces_created": 0, "ips_created": 0, "assets_created": 0, "assets_updated": 0,
|
||||||
|
"changes": [], "errors": [], "items": []}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# netbox-inventory plugin (asset management)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def asset_endpoint(self):
|
||||||
|
"""``plugins/inventory/assets`` when the netbox-inventory plugin is installed, else ``None``."""
|
||||||
|
if self._asset_endpoint is _UNKNOWN:
|
||||||
|
try:
|
||||||
|
endpoint = self.nb.plugins.inventory.assets
|
||||||
|
list(endpoint.filter(serial="netbox-sync-probe"))
|
||||||
|
self._asset_endpoint = endpoint
|
||||||
|
except Exception as error: # noqa: BLE001 - plugin missing (404), no permission or no plugins API
|
||||||
|
self._asset_endpoint = None
|
||||||
|
if hasattr(self.nb, "plugins"):
|
||||||
|
self.log(f"netbox-inventory nicht verfügbar – Assets werden übersprungen ({error})", "info")
|
||||||
|
return self._asset_endpoint
|
||||||
|
|
||||||
|
def _sync_asset(self, client, device, type_id, dry_run, report, tenant_id=None):
|
||||||
|
"""Create or update the inventory asset of a client (found by serial number).
|
||||||
|
|
||||||
|
The asset gets the tenant of the transfer or of the device – NetBox installations with a
|
||||||
|
validator that requires a tenant on every object reject assets without one.
|
||||||
|
"""
|
||||||
|
tenant_id = tenant_id or (related_id(device, "tenant") if device is not None else None)
|
||||||
|
endpoint = self.asset_endpoint()
|
||||||
|
serial = clean_serial(client.get("serial"))
|
||||||
|
if endpoint is None or not serial:
|
||||||
|
return []
|
||||||
|
assets = list(endpoint.filter(serial=serial))
|
||||||
|
if len(assets) > 1:
|
||||||
|
return [f"Asset übersprungen – {len(assets)} Assets mit der Seriennummer {serial}"]
|
||||||
|
report_text = inventory_report(client)
|
||||||
|
description = f"Windows-Client; UUID {client['uuid']}" if client.get("uuid") else "Windows-Client"
|
||||||
|
if not assets:
|
||||||
|
report["assets_created"] += 1
|
||||||
|
if not dry_run:
|
||||||
|
payload = {"name": client["name"], "serial": serial, "status": "used", "device_type": type_id,
|
||||||
|
"description": description}
|
||||||
|
if device is not None:
|
||||||
|
payload["device"] = device.id
|
||||||
|
if tenant_id:
|
||||||
|
payload["tenant"] = tenant_id
|
||||||
|
if report_text:
|
||||||
|
payload["comments"] = merge_report("", report_text)
|
||||||
|
endpoint.create(payload)
|
||||||
|
return ["Asset im Inventory-Plugin anlegen"]
|
||||||
|
asset = assets[0]
|
||||||
|
updates = {}
|
||||||
|
if (getattr(asset, "name", "") or "") != client["name"]:
|
||||||
|
updates["name"] = client["name"]
|
||||||
|
if str(getattr(getattr(asset, "status", None), "value", getattr(asset, "status", "")) or "") != "used":
|
||||||
|
updates["status"] = "used"
|
||||||
|
if type_id is not None and related_id(asset, "device_type") != type_id:
|
||||||
|
updates["device_type"] = type_id
|
||||||
|
if device is not None and related_id(asset, "device") != device.id:
|
||||||
|
updates["device"] = device.id
|
||||||
|
if tenant_id and related_id(asset, "tenant") is None:
|
||||||
|
updates["tenant"] = tenant_id
|
||||||
|
if client.get("uuid") and (getattr(asset, "description", "") or "") != description:
|
||||||
|
updates["description"] = description
|
||||||
|
current = getattr(asset, "comments", "") or ""
|
||||||
|
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
|
||||||
|
updates["comments"] = merge_report(current, report_text)
|
||||||
|
if not updates:
|
||||||
|
return []
|
||||||
|
report["assets_updated"] += 1
|
||||||
|
if not dry_run:
|
||||||
|
asset.update(updates)
|
||||||
|
labels = {"name": "Name", "status": "Status", "device_type": "Gerätetyp", "device": "Gerät", "tenant": "Mandant",
|
||||||
|
"description": "UUID", "comments": "Inventarbericht"}
|
||||||
|
return ["Asset aktualisieren: " + ", ".join(labels[key] for key in updates)]
|
||||||
|
|
||||||
def sync(self, clients, site_id, role_id, tenant_id=None, interfaces=True, update_existing=True, dry_run=True,
|
def sync(self, clients, site_id, role_id, tenant_id=None, interfaces=True, update_existing=True, dry_run=True,
|
||||||
progress=_noop, cancelled=lambda: False):
|
progress=_noop, cancelled=lambda: False):
|
||||||
@@ -191,8 +334,11 @@ class ClientSyncEngine:
|
|||||||
if device is None:
|
if device is None:
|
||||||
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
|
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform else "")
|
||||||
+ (f" · S/N {serial}" if serial else ""))
|
+ (f" · S/N {serial}" if serial else ""))
|
||||||
|
if client.get("source") == "agent":
|
||||||
|
changes.append(f"Inventarbericht in den Kommentaren ({len(client.get('software') or [])} Programme)")
|
||||||
report["devices_created"] += 1
|
report["devices_created"] += 1
|
||||||
if dry_run:
|
if dry_run:
|
||||||
|
changes.extend(self._sync_asset(client, None, type_id, dry_run, report, tenant_id))
|
||||||
if interfaces:
|
if interfaces:
|
||||||
for interface in client.get("interfaces", []):
|
for interface in client.get("interfaces", []):
|
||||||
changes.append(f"Schnittstelle {interface['name']} anlegen"
|
changes.append(f"Schnittstelle {interface['name']} anlegen"
|
||||||
@@ -207,6 +353,9 @@ class ClientSyncEngine:
|
|||||||
payload["serial"] = serial
|
payload["serial"] = serial
|
||||||
if tenant_id:
|
if tenant_id:
|
||||||
payload["tenant"] = tenant_id
|
payload["tenant"] = tenant_id
|
||||||
|
report_text = inventory_report(client)
|
||||||
|
if report_text:
|
||||||
|
payload["comments"] = merge_report("", report_text)
|
||||||
device = self.nb.dcim.devices.create(payload)
|
device = self.nb.dcim.devices.create(payload)
|
||||||
self.existing[name.casefold()] = device.id
|
self.existing[name.casefold()] = device.id
|
||||||
elif not update_existing:
|
elif not update_existing:
|
||||||
@@ -226,12 +375,22 @@ class ClientSyncEngine:
|
|||||||
if tenant_id and related_id(device, "tenant") is None:
|
if tenant_id and related_id(device, "tenant") is None:
|
||||||
updates["tenant"] = tenant_id
|
updates["tenant"] = tenant_id
|
||||||
changes.append("Mandant setzen")
|
changes.append("Mandant setzen")
|
||||||
|
report_text = inventory_report(client)
|
||||||
|
current = getattr(device, "comments", "") or ""
|
||||||
|
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
|
||||||
|
updates["comments"] = merge_report(current, report_text)
|
||||||
|
changes.append(f"Inventarbericht aktualisieren ({len(client.get('software') or [])} Programme)")
|
||||||
if updates:
|
if updates:
|
||||||
report["devices_updated"] += 1
|
report["devices_updated"] += 1
|
||||||
if not dry_run:
|
if not dry_run:
|
||||||
device.update(updates)
|
device.update(updates)
|
||||||
if interfaces:
|
if interfaces:
|
||||||
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
|
changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
|
||||||
|
try:
|
||||||
|
changes.extend(self._sync_asset(client, device, type_id, dry_run, report, tenant_id))
|
||||||
|
except Exception as error: # noqa: BLE001 - the device itself is fine; report the asset problem
|
||||||
|
report["errors"].append(f"{name}: Asset – {error}")
|
||||||
|
changes.append(f"Asset fehlgeschlagen: {error}")
|
||||||
if not changes:
|
if not changes:
|
||||||
report["devices_unchanged"] += 1
|
report["devices_unchanged"] += 1
|
||||||
return changes
|
return changes
|
||||||
|
|||||||
@@ -274,10 +274,16 @@ def apply_scan(row, raw, now=None):
|
|||||||
"installed": raw.get("installed", ""),
|
"installed": raw.get("installed", ""),
|
||||||
"last_boot": raw.get("last_boot", ""),
|
"last_boot": raw.get("last_boot", ""),
|
||||||
"source": raw.get("source", "winrm"),
|
"source": raw.get("source", "winrm"),
|
||||||
|
"uuid": raw.get("uuid", ""),
|
||||||
"agent_version": raw.get("agent_version", ""),
|
"agent_version": raw.get("agent_version", ""),
|
||||||
"software_count": len(raw.get("software") or []),
|
"software_count": len(raw.get("software") or []),
|
||||||
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
|
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
|
||||||
for disk in raw.get("disks") or []],
|
"publisher": item.get("publisher", "")} for item in raw.get("software") or []],
|
||||||
|
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0),
|
||||||
|
"serial": disk.get("serial", "")} for disk in raw.get("disks") or []],
|
||||||
|
"memory_modules": [{"bank": item.get("bank", ""), "manufacturer": item.get("manufacturer", ""),
|
||||||
|
"part_number": item.get("part_number", ""), "capacity": int(item.get("capacity") or 0)}
|
||||||
|
for item in raw.get("memory_modules") or []],
|
||||||
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
|
# Only real adapters: VPN/TAP drivers report no MAC or are not physical.
|
||||||
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
|
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -217,6 +217,7 @@ def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
|
|||||||
"model": system.get("Model") or "",
|
"model": system.get("Model") or "",
|
||||||
"product_name": product.get("Name") or "",
|
"product_name": product.get("Name") or "",
|
||||||
"product_version": product.get("Version") or "",
|
"product_version": product.get("Version") or "",
|
||||||
|
"uuid": product.get("UUID") or "",
|
||||||
"serial": bios.get("SerialNumber") or "",
|
"serial": bios.get("SerialNumber") or "",
|
||||||
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
|
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
|
||||||
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
|
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
|
||||||
|
|||||||
@@ -810,7 +810,9 @@ class Actions:
|
|||||||
self.state.client_engine = engine
|
self.state.client_engine = engine
|
||||||
self.state.clients_changed.emit()
|
self.state.clients_changed.emit()
|
||||||
text = (f"{report['devices_created']} Geräte angelegt, {report['devices_updated']} aktualisiert, "
|
text = (f"{report['devices_created']} Geräte angelegt, {report['devices_updated']} aktualisiert, "
|
||||||
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen")
|
f"{report['interfaces_created']} Schnittstellen, {report['ips_created']} IP-Adressen"
|
||||||
|
+ (f", {report['assets_created']} Assets angelegt, {report['assets_updated']} aktualisiert"
|
||||||
|
if report.get("assets_created") or report.get("assets_updated") else ""))
|
||||||
area_log("client")(f"Client-Übertragung: {text}", "success")
|
area_log("client")(f"Client-Übertragung: {text}", "success")
|
||||||
if report["errors"]:
|
if report["errors"]:
|
||||||
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning",
|
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning",
|
||||||
|
|||||||
@@ -1,15 +1,83 @@
|
|||||||
"""Dialogs for transferring scanned Windows clients to NetBox."""
|
"""Dialogs for transferring scanned Windows clients to NetBox."""
|
||||||
|
|
||||||
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
|
import csv
|
||||||
|
|
||||||
|
from PySide6.QtCore import Qt
|
||||||
|
from PySide6.QtGui import QGuiApplication
|
||||||
|
from PySide6.QtWidgets import QFileDialog, QFormLayout, QHBoxLayout, QTreeWidget, QTreeWidgetItem
|
||||||
|
|
||||||
from netbox_sync.ui.dialogs import _Dialog, _mark_invalid
|
from netbox_sync.ui.dialogs import _Dialog, _mark_invalid
|
||||||
from netbox_sync.ui.icons import icon
|
from netbox_sync.ui.icons import icon
|
||||||
from netbox_sync.ui.theme import theme
|
from netbox_sync.ui.theme import theme
|
||||||
from netbox_sync.ui.widgets import Badge, Banner, SearchableComboBox, checkbox, form_dialog_buttons, label
|
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
||||||
|
from netbox_sync.ui.widgets import (
|
||||||
|
Badge,
|
||||||
|
Banner,
|
||||||
|
SearchableComboBox,
|
||||||
|
SearchField,
|
||||||
|
Table,
|
||||||
|
button,
|
||||||
|
checkbox,
|
||||||
|
error,
|
||||||
|
form_dialog_buttons,
|
||||||
|
label,
|
||||||
|
)
|
||||||
|
|
||||||
ROLE_HINTS = ("client", "arbeitsplatz", "workstation", "pc", "notebook")
|
ROLE_HINTS = ("client", "arbeitsplatz", "workstation", "pc", "notebook")
|
||||||
|
|
||||||
|
|
||||||
|
class ClientSoftwareDialog(_Dialog):
|
||||||
|
"""Installed software of one client (from the NetBox Windows Agent), searchable and exportable."""
|
||||||
|
|
||||||
|
def __init__(self, parent, row):
|
||||||
|
software = row.get("software") or []
|
||||||
|
super().__init__(parent, f"Software – {row['name']}",
|
||||||
|
f"{len(software)} Programme laut NetBox-Agent (maschinenweit installierte Software)"
|
||||||
|
+ (f" · erfasst {row['scanned_text']}" if row.get("scanned_text") else ""), width=760)
|
||||||
|
self.resize(900, 640)
|
||||||
|
self.row = row
|
||||||
|
self.search = SearchField("Programm, Version, Hersteller …")
|
||||||
|
self.root.addWidget(self.search)
|
||||||
|
columns = [Column("name", "Programm", 420), Column("version", "Version", 150),
|
||||||
|
Column("publisher", "Hersteller", 260)]
|
||||||
|
self.model = RowTableModel(columns, row_id=lambda item: (item["name"], item["version"]))
|
||||||
|
self.model.set_rows(software)
|
||||||
|
self.proxy = FilterProxy(self.model)
|
||||||
|
self.search.textChanged.connect(self.proxy.set_text)
|
||||||
|
table = Table()
|
||||||
|
table.setModel(self.proxy)
|
||||||
|
table.sortByColumn(0, Qt.AscendingOrder)
|
||||||
|
for index, column in enumerate(columns):
|
||||||
|
table.setColumnWidth(index, column.width)
|
||||||
|
self.root.addWidget(table, 1)
|
||||||
|
buttons = QHBoxLayout()
|
||||||
|
buttons.addWidget(button("Als CSV speichern …", "download", on_click=self.save_csv))
|
||||||
|
buttons.addWidget(button("Kopieren", "copy", on_click=self.copy))
|
||||||
|
buttons.addStretch(1)
|
||||||
|
buttons.addWidget(button("Schließen", variant="primary", on_click=self.accept))
|
||||||
|
self.root.addLayout(buttons)
|
||||||
|
|
||||||
|
def _lines(self):
|
||||||
|
return [(item["name"], item["version"], item["publisher"]) for item in self.row.get("software") or []]
|
||||||
|
|
||||||
|
def copy(self):
|
||||||
|
QGuiApplication.clipboard().setText("\n".join("\t".join(line) for line in self._lines()))
|
||||||
|
|
||||||
|
def save_csv(self):
|
||||||
|
path, _filter = QFileDialog.getSaveFileName(self, "Software speichern", f"{self.row['name']}-software.csv",
|
||||||
|
"CSV (*.csv)")
|
||||||
|
if not path:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
# utf-8-sig and semicolons so that Excel opens it directly
|
||||||
|
with open(path, "w", encoding="utf-8-sig", newline="") as stream:
|
||||||
|
writer = csv.writer(stream, delimiter=";")
|
||||||
|
writer.writerow(("Programm", "Version", "Hersteller"))
|
||||||
|
writer.writerows(self._lines())
|
||||||
|
except OSError as problem:
|
||||||
|
error(self, "Speichern fehlgeschlagen", str(problem))
|
||||||
|
|
||||||
|
|
||||||
class ClientTargetDialog(_Dialog):
|
class ClientTargetDialog(_Dialog):
|
||||||
"""Choose site, role and tenant for the new devices."""
|
"""Choose site, role and tenant for the new devices."""
|
||||||
|
|
||||||
@@ -95,6 +163,9 @@ class ClientPreviewDialog(_Dialog):
|
|||||||
(f"{report['interfaces_created']} Schnittstellen", "info"),
|
(f"{report['interfaces_created']} Schnittstellen", "info"),
|
||||||
(f"{report['ips_created']} IP-Adressen", "info"),
|
(f"{report['ips_created']} IP-Adressen", "info"),
|
||||||
]
|
]
|
||||||
|
assets = report.get("assets_created", 0) + report.get("assets_updated", 0)
|
||||||
|
if assets:
|
||||||
|
items.append((f"{assets} Assets", "info"))
|
||||||
if report["errors"]:
|
if report["errors"]:
|
||||||
items.append((f"{len(report['errors'])} Probleme", "error"))
|
items.append((f"{len(report['errors'])} Probleme", "error"))
|
||||||
for text, kind in items:
|
for text, kind in items:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from PySide6.QtWidgets import (
|
|||||||
QGridLayout,
|
QGridLayout,
|
||||||
QHBoxLayout,
|
QHBoxLayout,
|
||||||
QLineEdit,
|
QLineEdit,
|
||||||
|
QMenu,
|
||||||
QPlainTextEdit,
|
QPlainTextEdit,
|
||||||
QRadioButton,
|
QRadioButton,
|
||||||
QSpinBox,
|
QSpinBox,
|
||||||
@@ -23,7 +24,10 @@ from netbox_sync.core import agent_client
|
|||||||
from netbox_sync.core.client_sync import clean_manufacturer
|
from netbox_sync.core.client_sync import clean_manufacturer
|
||||||
from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label
|
from netbox_sync.core.clients import WINRM_HTTP_PORT, WINRM_HTTPS_PORT, os_label, os_version_label
|
||||||
from netbox_sync.ui import widgets
|
from netbox_sync.ui import widgets
|
||||||
|
from netbox_sync.ui.client_dialogs import ClientSoftwareDialog
|
||||||
from netbox_sync.ui.client_help import ClientHelpDialog
|
from netbox_sync.ui.client_help import ClientHelpDialog
|
||||||
|
from netbox_sync.ui.icons import icon
|
||||||
|
from netbox_sync.ui.theme import theme
|
||||||
from netbox_sync.ui.credentials import ask_credentials
|
from netbox_sync.ui.credentials import ask_credentials
|
||||||
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
|
||||||
from netbox_sync.ui.pages import Page
|
from netbox_sync.ui.pages import Page
|
||||||
@@ -235,6 +239,10 @@ class ClientsPage(Page):
|
|||||||
Column("chassis", "Bauform", 95),
|
Column("chassis", "Bauform", 95),
|
||||||
Column("user", "Angemeldet", 140),
|
Column("user", "Angemeldet", 140),
|
||||||
Column("ips", "IP-Adressen", 160, value=_ips),
|
Column("ips", "IP-Adressen", 160, value=_ips),
|
||||||
|
Column("software", "Software", 90,
|
||||||
|
value=lambda row: f"{len(row['software'])} Programme" if row.get("software") else "",
|
||||||
|
sort=lambda row: len(row.get("software") or []), color=lambda row: "accent",
|
||||||
|
tooltip=lambda row: "Doppelklick: vollständige Liste" if row.get("software") else ""),
|
||||||
Column("last_logon", "AD-Anmeldung", 105, value=lambda row: _date((row.get("ad") or {}).get("last_logon")),
|
Column("last_logon", "AD-Anmeldung", 105, value=lambda row: _date((row.get("ad") or {}).get("last_logon")),
|
||||||
sort=lambda row: (row.get("ad") or {}).get("last_logon") or 0),
|
sort=lambda row: (row.get("ad") or {}).get("last_logon") or 0),
|
||||||
]
|
]
|
||||||
@@ -246,6 +254,8 @@ class ClientsPage(Page):
|
|||||||
for index, column in enumerate(columns):
|
for index, column in enumerate(columns):
|
||||||
self.table.setColumnWidth(index, column.width)
|
self.table.setColumnWidth(index, column.width)
|
||||||
self.table.doubleClicked.connect(self._toggle)
|
self.table.doubleClicked.connect(self._toggle)
|
||||||
|
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||||
|
self.table.customContextMenuRequested.connect(self._context_menu)
|
||||||
card.add(self.table, 1)
|
card.add(self.table, 1)
|
||||||
|
|
||||||
footer = QHBoxLayout()
|
footer = QHBoxLayout()
|
||||||
@@ -506,8 +516,28 @@ class ClientsPage(Page):
|
|||||||
|
|
||||||
def _toggle(self, index):
|
def _toggle(self, index):
|
||||||
row = self.proxy.row_at(index)
|
row = self.proxy.row_at(index)
|
||||||
|
if self.model.columns[index.column()].key == "software" and row.get("software"):
|
||||||
|
self.show_software(row)
|
||||||
|
return
|
||||||
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
|
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
|
||||||
|
|
||||||
|
def show_software(self, row):
|
||||||
|
ClientSoftwareDialog(self.window, dict(row, scanned_text=time.strftime(
|
||||||
|
"%d.%m.%Y %H:%M", time.localtime(row["scanned_at"])) if row.get("scanned_at") else "")).exec()
|
||||||
|
|
||||||
|
def _context_menu(self, position):
|
||||||
|
index = self.table.indexAt(position)
|
||||||
|
if not index.isValid():
|
||||||
|
return
|
||||||
|
row = self.proxy.row_at(index)
|
||||||
|
menu = QMenu(self)
|
||||||
|
action = menu.addAction(icon("list", theme.color("text_muted")), "Software anzeigen …",
|
||||||
|
lambda: self.show_software(row))
|
||||||
|
action.setEnabled(bool(row.get("software")))
|
||||||
|
if not row.get("software"):
|
||||||
|
action.setText("Software anzeigen … (nur mit NetBox-Agent)")
|
||||||
|
menu.exec(self.table.viewport().mapToGlobal(position))
|
||||||
|
|
||||||
def select_visible(self):
|
def select_visible(self):
|
||||||
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
|
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
|
||||||
|
|
||||||
|
|||||||
@@ -222,3 +222,119 @@ def test_scan_runs_in_process(monkeypatch):
|
|||||||
status = {row["host"]: row["status"] for row in results}
|
status = {row["host"]: row["status"] for row in results}
|
||||||
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
|
||||||
assert len(seen) == 3
|
assert len(seen) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_software_goes_into_a_managed_comment_block():
|
||||||
|
nb, client = _setup()
|
||||||
|
raw = dict(RAW, source="agent", agent_version="0.2.0",
|
||||||
|
software=[{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"},
|
||||||
|
{"name": "A | B", "version": "", "publisher": ""}],
|
||||||
|
disks=[{"model": "Micron SSD", "size": 512105932800, "serial": "M1"}],
|
||||||
|
memory_modules=[{"bank": "DIMM 0", "manufacturer": "Samsung", "part_number": "M425", "capacity": 2 ** 34}])
|
||||||
|
agent_client = apply_scan(new_row("pc01.firma.local"), raw)
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
preview = engine.sync([agent_client], 1, 2, dry_run=True)
|
||||||
|
assert "Inventarbericht in den Kommentaren (2 Programme)" in preview["items"][0][1]
|
||||||
|
engine.sync([agent_client], 1, 2, dry_run=False)
|
||||||
|
device = nb.dcim.devices.records[0]
|
||||||
|
assert "| 7-Zip | 24.08 | Igor Pavlov |" in device.comments and "| A / B |" in device.comments
|
||||||
|
assert "Micron SSD – 512 GB – S/N M1" in device.comments and "DIMM 0: 16 GB Samsung M425" in device.comments
|
||||||
|
|
||||||
|
# Hand-written notes survive, an unchanged inventory (only a new scan time) is no update.
|
||||||
|
device.comments = "Notiz vom Admin\n\n" + device.comments
|
||||||
|
again = ClientSyncEngine(nb)
|
||||||
|
again.load_targets()
|
||||||
|
rescanned = dict(agent_client, scanned_at=agent_client["scanned_at"] + 3600)
|
||||||
|
assert again.sync([rescanned], 1, 2, dry_run=True)["devices_updated"] == 0
|
||||||
|
changed = dict(rescanned, software=rescanned["software"] + [{"name": "Firefox", "version": "140", "publisher": ""}])
|
||||||
|
report = again.sync([changed], 1, 2, dry_run=False)
|
||||||
|
assert "Inventarbericht aktualisieren (3 Programme)" in report["items"][0][1]
|
||||||
|
assert device.comments.startswith("Notiz vom Admin") and device.comments.count("<!-- netbox-sync:inventory -->") == 1
|
||||||
|
assert "| Firefox | 140 | |" in device.comments
|
||||||
|
|
||||||
|
|
||||||
|
def test_winrm_scan_leaves_comments_alone():
|
||||||
|
nb, client = _setup()
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
engine.sync([client], 1, 2, dry_run=False)
|
||||||
|
assert "comments" not in nb.dcim.devices.created[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _with_inventory_plugin(nb):
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from fake_netbox import Endpoint
|
||||||
|
nb.plugins = SimpleNamespace(inventory=SimpleNamespace(assets=Endpoint()))
|
||||||
|
return nb.plugins.inventory.assets
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_client_gets_an_asset_linked_to_the_device():
|
||||||
|
nb, client = _setup()
|
||||||
|
assets = _with_inventory_plugin(nb)
|
||||||
|
agent_row = apply_scan(new_row("pc01.firma.local"), dict(RAW, source="agent", uuid="4C4C-1234",
|
||||||
|
software=[{"name": "7-Zip", "version": "24", "publisher": ""}]))
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
preview = engine.sync([agent_row], 1, 2, dry_run=True)
|
||||||
|
assert preview["assets_created"] == 1 and "Asset im Inventory-Plugin anlegen" in preview["items"][0][1]
|
||||||
|
assert assets.created == []
|
||||||
|
|
||||||
|
engine.sync([agent_row], 1, 2, dry_run=False)
|
||||||
|
device = nb.dcim.devices.records[0]
|
||||||
|
asset = assets.created[0]
|
||||||
|
assert asset["serial"] == "PW0K84A9" and asset["device"] == device.id and asset["status"] == "used"
|
||||||
|
assert asset["device_type"] == device.device_type and asset["description"] == "Windows-Client; UUID 4C4C-1234"
|
||||||
|
assert "| 7-Zip | 24 | |" in asset["comments"]
|
||||||
|
|
||||||
|
again = ClientSyncEngine(nb)
|
||||||
|
again.load_targets()
|
||||||
|
report = again.sync([agent_row], 1, 2, dry_run=True)
|
||||||
|
assert report["assets_created"] == 0 and report["assets_updated"] == 0 and report["items"][0][1] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_existing_asset_is_linked_and_updated_by_serial():
|
||||||
|
nb, client = _setup()
|
||||||
|
assets = _with_inventory_plugin(nb)
|
||||||
|
assets.records.append(Record(assets, id=500, name="Lager-Notebook", serial="PW0K84A9", status="stored",
|
||||||
|
device=None, device_type=None, description="", comments="Kaufbeleg 4711"))
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
report = engine.sync([client], 1, 2, dry_run=False)
|
||||||
|
asset = assets.records[0]
|
||||||
|
device = nb.dcim.devices.records[0]
|
||||||
|
assert report["assets_updated"] == 1 and report["assets_created"] == 0
|
||||||
|
assert asset.device == device.id and asset.status == "used" and asset.name == "PC01"
|
||||||
|
assert asset.comments == "Kaufbeleg 4711" # WinRM scan: no inventory report, comments untouched
|
||||||
|
assert any(change.startswith("Asset aktualisieren: Name, Status, Gerätetyp, Gerät") for change in report["items"][0][1])
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_inventory_plugin_no_asset_is_touched():
|
||||||
|
nb, client = _setup()
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
report = engine.sync([client], 1, 2, dry_run=False)
|
||||||
|
assert report["errors"] == [] and report["assets_created"] == 0 and engine.asset_endpoint() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_gets_the_tenant_of_the_transfer_or_the_device():
|
||||||
|
from types import SimpleNamespace
|
||||||
|
nb, client = _setup()
|
||||||
|
assets = _with_inventory_plugin(nb)
|
||||||
|
engine = ClientSyncEngine(nb)
|
||||||
|
engine.load_targets()
|
||||||
|
engine.sync([client], 1, 2, tenant_id=7, dry_run=False)
|
||||||
|
assert assets.created[0]["tenant"] == 7
|
||||||
|
|
||||||
|
# an existing device keeps its tenant; an asset without tenant gets the device's one
|
||||||
|
nb2, client2 = _setup()
|
||||||
|
assets2 = _with_inventory_plugin(nb2)
|
||||||
|
nb2.dcim.devices.records.append(Record(nb2.dcim.devices, id=300, name="PC01", tenant=SimpleNamespace(id=9),
|
||||||
|
device_type=None, platform=None, serial="", primary_ip4=None))
|
||||||
|
assets2.records.append(Record(assets2, id=501, name="PC01", serial="PW0K84A9", status="used", device=None,
|
||||||
|
device_type=None, tenant=None, description="", comments=""))
|
||||||
|
again = ClientSyncEngine(nb2)
|
||||||
|
again.load_targets()
|
||||||
|
report = again.sync([client2], 1, 2, dry_run=False)
|
||||||
|
assert report["errors"] == [] and assets2.records[0].tenant == 9 and assets2.records[0].device == 300
|
||||||
Reference in new issue
Block a user