Compare commits

...
21 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 ef12531c8e chore: release 4.20.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:29:59 +01:00
MrBlakeandClaude Opus 5.5 98c8647501 feat: maintain netbox-inventory assets for clients and show the agent's software list
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:29:58 +01:00
MrBlakeandClaude Opus 5.5 d6622cf48f chore: release 4.20.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:13:24 +01:00
MrBlakeandClaude Opus 5.5 1f338902a7 feat: write the agent's hardware and software inventory into the device comments
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:13:23 +01:00
MrBlakeandClaude Opus 5.5 76f12069b5 chore: release 4.20.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:16:12 +01:00
MrBlakeandClaude Opus 5.5 76662dd378 docs: link the agent release and list the GPO share files in the setup guide
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:16:12 +01:00
MrBlakeandClaude Opus 5.5 9603add434 chore: release 4.20.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:05:32 +01:00
MrBlakeandClaude Opus 5.5 a67b0d3e5c feat: scan Windows clients with the NetBox Windows Agent in listen mode
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 11:05:32 +01:00
MrBlakeandClaude Opus 5.5 43c5e5e85a chore: release 4.19.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:15:56 +01:00
MrBlakeandClaude Opus 5.5 b1cfdf7a5c feat: map missing printer models to device types and ignore printers or models
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:15:55 +01:00
MrBlakeandClaude Opus 5.5 2db5e1f251 chore: release 4.18.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:07:44 +01:00
MrBlakeandClaude Opus 5.5 4d77528266 fix: start the printer comparison after the scan has ended and allow a site per printer
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:07:43 +01:00
MrBlakeandClaude Opus 5.5 596bbabb54 chore: release 4.18.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:39:50 +01:00
MrBlakeandClaude Opus 5.5 235fb8e26a feat: printer import via SNMP v2c/v3 scan with page counter and supplies
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:39:50 +01:00
MrBlakeandClaude Opus 5.5 05d34e4823 chore: release 4.17.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:46 +01:00
MrBlakeandClaude Opus 5.5 f134db0c16 fix: put access point IPs into the VRF of the matching tenant prefix instead of always global
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:45 +01:00
MrBlakeandClaude Opus 5.5 1352514577 chore: release 4.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:50:33 +01:00
MrBlakeandClaude Opus 5.5 fc503bd7d3 feat: choose the far-end interface of a cable in the review dialog
The neighbor tab gets a "Nachbar-Schnittstelle" column with the cable targets
of the neighbor device (no wireless interfaces) and the automatic choice;
the selection is stored per switch as neighbor_interfaces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:50:33 +01:00
MrBlakeandClaude Opus 5.5 144e5f9eb8 fix: ignore wireless interfaces when looking for the far end of a cable
NetBox does not allow cables on wireless interfaces; wlan1 made "LAN1" on a
LANCOM LW-600 (eth1, wlan0, wlan1) ambiguous and prevented the single-port rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:46:24 +01:00
MrBlakeandClaude Opus 5.5 823d968b33 chore: release 4.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:39:23 +01:00
MrBlakeandClaude Opus 5.5 0241509845 fix: LANCOM LLDP fields with empty values, indented lines after paging and prompt as port description; explain skipped cables
Every skipped cable is reported as a note with its reason (local port,
neighbor device or far-end interface not found, far end already cabled).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:38:23 +01:00
30 changed files with 3462 additions and 119 deletions

No files matched your search

+49 -1
View File
@@ -106,7 +106,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
assignments) are supported; without the plugin the step is skipped with a note
- Cables from LLDP/CDP, also with FQDN system names or via the management IP.
Neighbors that report their MAC address as port ID (e.g. access points) are
matched by MAC, and a device with a single physical port is cabled there
matched by MAC, and a device with a single physical port is cabled there.
Wireless interfaces (Wi-Fi, LTE …) are never cable targets. In the review
dialog the far-end interface can be chosen per neighbor ("automatisch" shows
the interface that would be used); the choice is stored in the profile.
Every skipped cable is listed as a note with its reason
- Existing cables are checked against LLDP/CDP: a different far end is reported
as a note. Only with the optional "Bestehende Kabel anpassen" (confirmed with
a warning, NetBox is the source of truth) the cable is moved to the reported
@@ -148,6 +152,36 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
firmware, interface with MAC and IP address (primary IPv4); existing ones get
missing serial numbers and tenants, optionally the Sophos name. Preview before
writing
- IP addresses go into the VRF of the most specific matching prefix of the
tenant (group), otherwise global
### Printers (SNMP scan)
- Scans IP ranges for printers of any manufacturer via the standard Host
Resources and Printer MIBs (RFC 3805); hosts that do not answer ping are
still probed on the printer ports 9100/631/515
- SNMPv2c communities and SNMPv3 users (MD5, SHA-1, SHA-224/256/384/512; DES,
AES-128/192/256) are stored per profile (secrets encrypted with DPAPI) and
tried in order; the credential that worked is remembered per address and
tried first next time. Rejected SNMPv3 logins are explained (unknown user,
wrong password, wrong privacy settings)
- Reads name, location, contact, manufacturer (from sysObjectID), model,
serial number, firmware, MAC address, netmask, page counter, colour
capability, supplies (toner, drum, waste toner, fuser … with fill level),
paper trays, status, error flags, display text and alerts
- Devices with open printer ports but no SNMP answer are listed as
"without SNMP"
- Printers can be ignored this time or permanently (context menu); models
missing in NetBox as device type can be created, mapped to an existing
device type (with suggestion), skipped this time or ignored permanently
("Modelle …", asked before the transfer)
- The model is taken from prtGeneralPrinterName, hrDeviceDescr or the HP
device ID – not from generic JetDirect descriptions
- Same workflow as the access point import: matching by serial number, MAC
address, name and IP address, site/tenant mapping by SNMP location, default
site, preview before writing
- Optionally stores page counter, supplies, colour capability and scan date in
custom fields of the device (created on first transfer, group "Drucker")
### Network scanner (read only)
@@ -185,6 +219,20 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
permissions, common errors, check commands and a connection test for single
clients
### Windows clients with the NetBox Windows Agent
- Third target mode **NetBox-Agent (Netzwerk-Scan)**: scans IP ranges for the
[NetBox Windows Agent](https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows)
in listen mode – no WinRM, no admin account and no NetBox access needed on the
clients; only hosts with an answering agent are listed
- One shared key per profile (encrypted with DPAPI); requests are signed with
HMAC-SHA256, the inventory comes back encrypted with AES-256-GCM
- "Agent-Konfiguration speichern …" writes the ready `config.json` (port,
key, optional allowed networks) for unattended deployment with Intune or a
Group Policy startup script; the setup guide has a tab with all steps
- The agent data runs through the same table and NetBox transfer as the WinRM
scan, plus disks and the number of installed programs in the tooltip
### Offline mode (without NetBox)
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.16.4"
#define AppVersion "4.20.3"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.16.4"
APP_VERSION = "4.20.3"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+114
View File
@@ -0,0 +1,114 @@
"""Query the NetBox Windows Agent in "listen" mode (protocol v1).
The agent answers ``GET /v1/info`` without authentication. The inventory at
``GET /v1/inventory`` needs a signature (HMAC-SHA256 with a key derived from
the shared scan key) over a fresh nonce and the current time, and comes back
encrypted with AES-256-GCM, so serial numbers and software lists never cross
the network in clear text even without TLS certificates.
The decrypted inventory has the same shape as the WinRM scan
(:func:`netbox_sync.core.wsman.query_client`), so it runs through the same
table and NetBox transfer as the agentless client scan.
"""
import base64
import hashlib
import hmac
import http.client
import json
import secrets
import time
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
DEFAULT_PORT = 8731
PROTOCOL = 1
AGENT_NAME = "netbox-windows-agent"
class AgentError(Exception):
"""The host answered, but not as an agent we can read (wrong key, other service …)."""
def derive_key(secret, purpose):
return hmac.new(secret.encode(), purpose.encode(), hashlib.sha256).digest()
def new_scan_key():
"""Random shared key for the agents of one customer (URL-safe, 43 characters)."""
return secrets.token_urlsafe(32)
def _get(host, port, path, headers=None, timeout=5.0):
connection = http.client.HTTPConnection(host, port, timeout=timeout)
try:
connection.request("GET", path, headers=headers or {})
response = connection.getresponse()
body = response.read(16 * 1024 * 1024)
return response.status, body
finally:
connection.close()
def _json(body):
try:
return json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, ValueError) as error:
raise AgentError("keine gültige Antwort (kein NetBox-Agent?)") from error
def info(host, port=DEFAULT_PORT, timeout=3.0):
status, body = _get(host, port, "/v1/info", timeout=timeout)
data = _json(body)
if status != 200 or data.get("agent") != AGENT_NAME:
raise AgentError("kein NetBox-Agent auf diesem Port")
return data
def inventory(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Decrypted inventory dict of one agent."""
nonce = secrets.token_hex(16)
ts = str(int(time.time()))
signature = hmac.new(derive_key(key, "netbox-agent auth v1"), f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(),
hashlib.sha256).hexdigest()
status, body = _get(host, port, f"/v1/inventory?nonce={nonce}&ts={ts}", {"X-Agent-Signature": signature},
timeout)
data = _json(body)
if status != 200:
reason = data.get("error", f"HTTP {status}")
raise AgentError({
"wrong key": "Agent-Schlüssel stimmt nicht",
"clock skew too large": "Uhrzeit von Client und diesem Rechner weicht mehr als 5 Minuten ab",
"address not allowed": "dieser Rechner ist in allowed_networks des Agenten nicht freigegeben",
}.get(reason, f"Agent meldet: {reason}"))
try:
payload = AESGCM(derive_key(key, "netbox-agent enc v1")).decrypt(
base64.b64decode(data["iv"]), base64.b64decode(data["data"]), nonce.encode())
except Exception as error: # noqa: BLE001 - InvalidTag, KeyError, binascii.Error
raise AgentError("Antwort lässt sich nicht entschlüsseln (falscher Schlüssel?)") from error
return json.loads(payload.decode("utf-8"))
def query(host, key, port=DEFAULT_PORT, timeout=60.0):
"""Raw result for :func:`netbox_sync.core.clients.apply_scan` – never raises."""
try:
result = inventory(host, key, port, timeout)
except AgentError as error:
return {"host": host, "ok": False, "error": str(error)}
except (OSError, http.client.HTTPException) as error:
return {"host": host, "ok": False, "error": f"Agent nicht erreichbar: {error}"}
result.update(host=host, ok=True)
return result
def agent_config(key, port=DEFAULT_PORT, allowed_networks=(), collect_software=True):
"""``config.json`` for agents in listen mode (no NetBox access needed on the clients)."""
return {
"mode": "listen",
"listen_port": port,
"scan_key": key,
"allowed_networks": list(allowed_networks),
"inventory_cache_seconds": 300,
"collect_software": collect_software,
"max_software_entries": 250,
}
+64 -19
View File
@@ -13,6 +13,7 @@ import ipaddress
import re
from netbox_sync.core.client_sync import ClientSyncEngine
from netbox_sync.core.switches import candidate_vrfs
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id, uses_mac_objects
MANUFACTURER = "Sophos"
@@ -140,9 +141,7 @@ class APSyncEngine(ClientSyncEngine):
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
"tenant": tenants.get(related_id(site, "tenant"), "")}
for site in self.nb.dcim.sites.all()), key=lambda row: row["name"].casefold())
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id)) if manufacturer else []
self.netbox_aps = self._known_devices({})
return self.ap_sites
tenant = self.nb.tenancy.tenants.get(tenant_id)
if tenant is None:
@@ -160,11 +159,30 @@ class APSyncEngine(ClientSyncEngine):
for site in self.nb.dcim.sites.filter(**scope)), key=lambda row: row["name"].casefold())
self.roles = sorted(((item.name, item.id) for item in self.nb.dcim.device_roles.all()),
key=lambda pair: pair[0].casefold())
self.netbox_aps = self._known_devices(scope)
return self.ap_sites
def _known_devices(self, scope):
"""Devices of this kind in NetBox (``scope`` limits them to the tenant group)."""
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) \
if manufacturer else []
return self.ap_sites
return list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) if manufacturer else []
def _identity(self, ap):
"""``(manufacturer, model, platform or None)`` of a new device."""
return MANUFACTURER, ap["model"] or "Access Point", PLATFORM
def _mapped_type(self, ap):
"""Device type ID chosen by the user instead of creating one, or ``None``."""
return None
def _extra_payload(self, ap):
"""Additional fields for a new device."""
return {}
def _extra_updates(self, device, ap):
"""Additional field changes for an existing device: ``(updates, change texts)``."""
return {}, []
def suggest_site(self, hint):
"""NetBox site for a Sophos site name, or ``None`` when unclear."""
@@ -260,6 +278,7 @@ class APSyncEngine(ClientSyncEngine):
"""
report = self.new_report()
self._planned = set()
self._vrf_cache = {}
for ap in aps:
try:
changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report,
@@ -290,11 +309,13 @@ class APSyncEngine(ClientSyncEngine):
if description and (getattr(device, "description", "") or "").startswith("Firmware") \
and device.description != description:
updates["description"] = description
extra, extra_texts = self._extra_updates(device, ap)
updates.update(extra)
if updates:
report["devices_updated"] += 1
changes.append("Aktualisieren: " + ", ".join(
f"{key} → {value}" for key, value in updates.items() if key != "tenant")
+ (" (Mandant ergänzt)" if "tenant" in updates else ""))
[f"{key} → {value}" for key, value in updates.items() if key not in ("tenant", *extra)]
+ extra_texts) + (" (Mandant ergänzt)" if "tenant" in updates else ""))
if not dry_run:
device.update(updates)
else:
@@ -307,19 +328,24 @@ class APSyncEngine(ClientSyncEngine):
"Standard-Standort wählen")
if not role_id:
raise APImportError("keine Geräterolle gewählt")
manufacturer_id = self._manufacturer(MANUFACTURER, report, dry_run)
type_id = self._device_type(MANUFACTURER, manufacturer_id, ap["model"] or "Access Point", report, dry_run)
platform_id = self._platform(PLATFORM, report, dry_run)
manufacturer, model, platform = self._identity(ap)
manufacturer_id = self._manufacturer(manufacturer, report, dry_run)
type_id = self._mapped_type(ap) or self._device_type(manufacturer, manufacturer_id, model, report,
dry_run)
platform_id = self._platform(platform, report, dry_run) if platform else None
# An explicitly chosen tenant wins, otherwise the one of the site.
tenant_id = placement.get("tenant") or self._site_tenant(site_id)
payload = {"name": ap["name"], "device_type": type_id, "role": role_id, "site": site_id,
"tenant": tenant_id, "status": "active", "platform": platform_id}
"tenant": tenant_id, "status": "active"}
if platform:
payload["platform"] = platform_id
if ap["serial"]:
payload["serial"] = ap["serial"]
if description:
payload["description"] = description
payload.update(self._extra_payload(ap))
report["devices_created"] += 1
changes.append(f"Gerät anlegen ({ap['model'] or 'Access Point'})")
changes.append(f"Gerät anlegen ({model})")
if dry_run:
if ap["mac"] or ap["ip"]:
report["interfaces_created"] += 1
@@ -327,7 +353,9 @@ class APSyncEngine(ClientSyncEngine):
else ""))
if ap["ip"]:
report["ips_created"] += 1
changes.append(f"IP-Adresse {ap['ip']} anlegen")
prefix = self._prefix_for(ap["ip"], tenant_id)
vrf = getattr(prefix, "vrf", None) if prefix else None
changes.append(f"IP-Adresse {ap['ip']} anlegen" + (f" (VRF {vrf.name})" if vrf else ""))
return changes
device = self.nb.dcim.devices.create(payload)
if dry_run and device is None:
@@ -350,6 +378,21 @@ class APSyncEngine(ClientSyncEngine):
interface = self.nb.dcim.interfaces.create({"device": device.id, "name": INTERFACE_NAME, "type": "1000base-t"})
return interface, [f"Schnittstelle {INTERFACE_NAME} anlegen"]
def _prefix_for(self, ip, tenant_id):
"""Most specific prefix containing ``ip``, globally or in a VRF of the tenant (group).
With the same length a VRF prefix wins over a global one.
"""
if tenant_id not in self._vrf_cache:
# VRFs of the device's tenant and of the tenant chosen for the import (and their groups).
owners = {owner for owner in (tenant_id, self.tenant_id) if owner}
self._vrf_cache[tenant_id] = {vrf.id for owner in owners for vrf in candidate_vrfs(self.nb, owner)}
allowed = self._vrf_cache[tenant_id]
prefixes = [prefix for prefix in self.nb.ipam.prefixes.filter(contains=ip)
if related_id(prefix, "vrf") is None or related_id(prefix, "vrf") in allowed]
return max(prefixes, default=None, key=lambda prefix: (
ipaddress.ip_network(str(prefix.prefix), strict=False).prefixlen, related_id(prefix, "vrf") is not None))
def _sync_network(self, device, ap, tenant_id, dry_run, report):
if not ap["mac"] and not ap["ip"]:
return []
@@ -359,10 +402,12 @@ class APSyncEngine(ClientSyncEngine):
changes.append(f"MAC {ap['mac']} zugeordnet")
if not ap["ip"]:
return changes
prefix = next(iter(self.nb.ipam.prefixes.filter(contains=ap["ip"], vrf_id="null")), None)
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32"
prefix = self._prefix_for(ap["ip"], tenant_id)
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else str(ap.get("prefix_length") or 32)
vrf_id = related_id(prefix, "vrf") if prefix else None
address = f"{ap['ip']}/{length}"
existing = list(self.nb.ipam.ip_addresses.filter(address=ap["ip"], vrf_id="null"))
where = f" (VRF {getattr(getattr(prefix, 'vrf', None), 'name', vrf_id)})" if vrf_id else ""
existing = list(self.nb.ipam.ip_addresses.filter(address=ap["ip"], vrf_id=vrf_id or "null"))
if existing:
ip = existing[0]
assigned = getattr(ip, "assigned_object_id", None)
@@ -378,11 +423,11 @@ class APSyncEngine(ClientSyncEngine):
"tenant": related_id(ip, "tenant") or tenant_id})
else:
report["ips_created"] += 1
changes.append(f"IP-Adresse {address} anlegen")
changes.append(f"IP-Adresse {address} anlegen{where}")
if dry_run or interface is None:
return changes
ip = self.nb.ipam.ip_addresses.create({
"address": address, "status": "active", "tenant": tenant_id,
"address": address, "status": "active", "tenant": tenant_id, "vrf": vrf_id,
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
})
if not dry_run and related_id(device, "primary_ip4") != ip.id:
+151 -1
View File
@@ -7,11 +7,80 @@ written; the report lists what would change.
"""
import re
import time
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
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):
pass
@@ -66,6 +135,7 @@ class ClientSyncEngine:
self._device_types = {}
self._platforms = {}
self._planned = set()
self._asset_endpoint = _UNKNOWN
# ------------------------------------------------------------------
# Lookups
@@ -156,7 +226,71 @@ class ClientSyncEngine:
@staticmethod
def new_report():
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):
"""Create or update the inventory asset of a client (found by serial number)."""
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 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 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",
"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,
progress=_noop, cancelled=lambda: False):
@@ -191,8 +325,11 @@ class ClientSyncEngine:
if device is None:
changes.append(f"Gerät anlegen · {manufacturer} {model}" + (f" · {platform}" if platform 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
if dry_run:
changes.extend(self._sync_asset(client, None, type_id, dry_run, report))
if interfaces:
for interface in client.get("interfaces", []):
changes.append(f"Schnittstelle {interface['name']} anlegen"
@@ -207,6 +344,9 @@ class ClientSyncEngine:
payload["serial"] = serial
if 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)
self.existing[name.casefold()] = device.id
elif not update_existing:
@@ -226,12 +366,22 @@ class ClientSyncEngine:
if tenant_id and related_id(device, "tenant") is None:
updates["tenant"] = tenant_id
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:
report["devices_updated"] += 1
if not dry_run:
device.update(updates)
if interfaces:
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))
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:
report["devices_unchanged"] += 1
return changes
+24 -6
View File
@@ -21,7 +21,7 @@ WINRM_HTTPS_PORT = 5986
MAX_RANGE = 4096
DEFAULT_CLIENT_OPTIONS = {
"mode": "ad", # ad | hosts
"mode": "ad", # ad | hosts | agent
"ad_server": "", # domain or domain controller, empty = own domain
"ad_base": "", # search base (OU DN), empty = whole domain
"include_servers": False,
@@ -31,6 +31,10 @@ DEFAULT_CLIENT_OPTIONS = {
"use_current_user": False,
"username": "", # remembered for the logon prompt, never the password
"use_ssl": False,
# NetBox Windows Agent in listen mode (the key itself is a profile secret).
"agent_targets": "",
"agent_port": 8731,
"agent_networks": "", # allowed_networks written into the agent configuration
# Last choices in the NetBox transfer dialog.
"netbox_site": None,
"netbox_role": "Client",
@@ -269,6 +273,17 @@ def apply_scan(row, raw, now=None):
"os_architecture": raw.get("os_architecture", ""),
"installed": raw.get("installed", ""),
"last_boot": raw.get("last_boot", ""),
"source": raw.get("source", "winrm"),
"uuid": raw.get("uuid", ""),
"agent_version": raw.get("agent_version", ""),
"software_count": len(raw.get("software") or []),
"software": [{"name": item.get("name", ""), "version": item.get("version", ""),
"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.
"interfaces": [_interface(nic) for nic in raw.get("nics") or [] if nic.get("physical") and nic.get("mac")],
})
@@ -358,11 +373,14 @@ def friendly_error(text):
# --------------------------------------------------------------------------
def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, log=lambda *_args: None,
on_result=lambda _row: None, cancelled=lambda: False, query=None):
"""Query every row's host. ``on_result`` is called for each finished row (any thread)."""
on_result=lambda _row: None, cancelled=lambda: False, query=None, port=None, service="WinRM"):
"""Query every row's host. ``on_result`` is called for each finished row (any thread).
``query``/``port``/``service`` replace the WinRM query, e.g. by the NetBox Windows Agent.
"""
if sys.platform != "win32" and query is None:
raise ClientScanError("Die Abfrage von Windows-Clients ist nur unter Windows verfügbar.")
port = WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT
port = port or (WINRM_HTTPS_PORT if use_ssl else WINRM_HTTP_PORT)
results = []
def scan(row):
@@ -374,7 +392,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
scanned_at=time.time())
if not port_open(host, port):
return dict(row, status="offline", scanned_at=time.time(),
message=f"Nicht erreichbar – ausgeschaltet oder WinRM-Port {port} geschlossen.")
message=f"Nicht erreichbar – ausgeschaltet oder {service}-Port {port} geschlossen.")
if cancelled():
return None
if query is not None:
@@ -386,7 +404,7 @@ def scan_clients(rows, credential=None, use_ssl=False, parallel=8, timeout=30, l
raw = wsman.query_client(host, credential, use_ssl, port, timeout)
return apply_scan(row, raw)
log(f"Frage {len(rows)} Client(s) über WinRM (Port {port}) ab …")
log(f"Frage {len(rows)} Client(s) über {service} (Port {port}) ab …")
with ThreadPoolExecutor(max_workers=max(1, min(parallel, len(rows) or 1))) as pool:
futures = [pool.submit(scan, row) for row in rows]
for future in as_completed(futures):
+15 -1
View File
@@ -11,7 +11,7 @@ from pathlib import Path
from netbox_sync import CONFIG_DIR_NAME
from netbox_sync.core.clients import DEFAULT_CLIENT_OPTIONS
SECRET_KEYS = ("password", "token_secret")
SECRET_KEYS = ("password", "token_secret", "community", "auth_password", "priv_password")
CONFIG_VERSION = 5
DEFAULT_SETTINGS = {
@@ -115,6 +115,8 @@ def empty_profile(name):
"netbox_url": "",
"netbox_token": "",
"netbox_ignore_ssl": False,
# Shared key of the NetBox Windows Agents of this customer (listen mode).
"agent_key": "",
"sources": [],
"switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
@@ -127,6 +129,10 @@ def empty_profile(name):
# Sophos AP import: tenant, role, rename option and site choices
# ("site_map": Sophos site -> NetBox site ID, "ap_sites": AP key -> NetBox site ID).
"access_points": {},
# SNMP printer scan: targets, role, site choices and remembered credential per address.
"printers": {},
# SNMP credentials (v2c communities and v3 users) – secrets encrypted.
"snmp_credentials": [],
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -172,17 +178,22 @@ class ProfileStore:
profile.update({
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"agent_key": self._decrypt(record.get("agent_key_encrypted", ""), f"{name}: Agent-Schlüssel")
if record.get("agent_key_encrypted") else "",
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"vlan_map": dict(record.get("vlan_map", {})),
"network_map": dict(record.get("network_map", {})),
"access_points": dict(record.get("access_points", {})),
"printers": dict(record.get("printers", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for credential in record.get("snmp_credentials", []):
profile["snmp_credentials"].append(self._decrypt_record(credential, f"{name}: SNMP"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5/4.6: VLAN and network decisions were stored per switch.
@@ -246,6 +257,7 @@ class ProfileStore:
"name": name,
"netbox_url": profile.get("netbox_url", ""),
"netbox_token_encrypted": protect(profile.get("netbox_token", "")),
"agent_key_encrypted": protect(profile.get("agent_key", "")) if profile.get("agent_key") else "",
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
@@ -254,6 +266,8 @@ class ProfileStore:
"vlan_map": dict(profile.get("vlan_map", {})),
"network_map": dict(profile.get("network_map", {})),
"access_points": dict(profile.get("access_points", {})),
"printers": dict(profile.get("printers", {})),
"snmp_credentials": [self._encrypt_record(item) for item in profile.get("snmp_credentials", [])],
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+15 -8
View File
@@ -12,6 +12,7 @@ import time
from netbox_sync.core.switches import (
CLI_ERROR,
CLI_PROMPT,
MAC_PATTERN,
_compress_vlans,
_interface,
_membership,
@@ -120,7 +121,9 @@ def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, w
def _field(text, label):
match = re.search(rf"(?im)^{re.escape(label)}\s*:\s*(.*?)\s*$", text or "")
# Only spaces/tabs around the colon: an empty value must not swallow the next line. Lines after a
# paging prompt are indented, hence the optional leading blanks.
match = re.search(rf"(?im)^[ \t]*{re.escape(label)}[ \t]*:[ \t]*(.*?)[ \t]*$", text or "")
return match.group(1) if match else ""
@@ -148,17 +151,17 @@ def parse_status(output):
def parse_port_config(output):
"""``show configuration``: a port line followed by its description line."""
"""``show configuration``: a port line, directly followed by its (possibly empty) description line."""
ports, current = {}, None
for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)\s+(Enabled|Disabled)\s", line, re.I)
if match:
current = int(match.group(1))
ports[current] = {"enabled": match.group(2).lower() == "enabled", "description": ""}
elif current is not None and line.strip() and not set(line.strip()) <= {"-"}:
ports[current]["description"] = line.strip()
current = None
elif current is not None and set(line.strip()) <= {"-"} and line.strip():
elif current is not None:
text = line.strip()
if text and not set(text) <= {"-"} and not CLI_PROMPT.search(text):
ports[current]["description"] = text
current = None
return ports
@@ -240,14 +243,18 @@ def parse_neighbors(output):
if not local:
continue
port = re.search(r"(\d+)", local) # "Port 2" → "2", the name of the switch port
chassis = _field(block, "Chassis ID")
name = _field(block, "System Name")
if not name and chassis and not MAC_PATTERN.fullmatch(chassis) and not re.fullmatch(r"[\d.]+", chassis):
name = chassis # e.g. Windows hosts send their name only as chassis ID
neighbors.append({
"local_port": port.group(1) if port else local,
"system_name": _field(block, "System Name"),
"system_name": name,
"remote_port": _field(block, "Port ID") or _field(block, "Port Description"),
"port_description": _field(block, "Port Description"),
"management_ip": (re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", _field(block, "Management Address"))
or [""])[0],
"chassis_id": _field(block, "Chassis ID"),
"chassis_id": chassis,
"protocol": "LLDP",
})
return neighbors
+500
View File
@@ -0,0 +1,500 @@
"""Printers found by an SNMP network scan, documented in NetBox.
Every address is pinged (or probed on the printer ports 9100/515/631), then
queried via SNMP. The credentials of the profile are tried in order – SNMPv2c
communities and SNMPv3 users – and the one that works is remembered per
address. Printers are recognised by the Host Resources MIB (hrDeviceType
printer) or the Printer MIB (RFC 3805), so this works for every manufacturer.
Devices that only answer on printer ports are listed as "printer without SNMP".
The sync reuses the access point import: devices are matched by serial number,
MAC address, name and IP address. Page counter, supplies, colour capability and
the date of the scan are optionally stored in custom fields.
"""
import datetime
import ipaddress
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from netbox_sync.core import netscan, snmp
from netbox_sync.core.ap_sync import CHUNK, APSyncEngine
from netbox_sync.core.netbox import normalize_mac, related_id, version_tuple
PRINTER_PORTS = (9100, 631, 515)
SYS = "1.3.6.1.2.1.1"
SYS_DESCR, SYS_OBJECT_ID, SYS_UPTIME = f"{SYS}.1.0", f"{SYS}.2.0", f"{SYS}.3.0"
SYS_CONTACT, SYS_NAME, SYS_LOCATION = f"{SYS}.4.0", f"{SYS}.5.0", f"{SYS}.6.0"
HR_DEVICE_TYPE = "1.3.6.1.2.1.25.3.2.1.2"
HR_DEVICE_DESCR = "1.3.6.1.2.1.25.3.2.1.3"
HR_PRINTER = "1.3.6.1.2.1.25.3.1.5"
HR_PRINTER_STATUS = "1.3.6.1.2.1.25.3.5.1.1"
HR_PRINTER_ERRORS = "1.3.6.1.2.1.25.3.5.1.2"
PRT_SERIAL = "1.3.6.1.2.1.43.5.1.1.17"
PRT_PRINTER_NAME = "1.3.6.1.2.1.43.5.1.1.16"
HP_DEVICE_ID = "1.3.6.1.4.1.11.2.3.9.1.1.7.0" # IEEE 1284 device ID "MFG:HP;MDL:HP LaserJet …;"
GENERIC_DESCR = re.compile(r"ETHERNET MULTI-ENVIRONMENT|JETDIRECT|^\s*$", re.IGNORECASE)
PRT_INPUT = "1.3.6.1.2.1.43.8.2.1"
PRT_LIFE_COUNT = "1.3.6.1.2.1.43.10.2.1.4"
PRT_SUPPLIES = "1.3.6.1.2.1.43.11.1.1"
PRT_COLORANT = "1.3.6.1.2.1.43.12.1.1.4"
PRT_DISPLAY = "1.3.6.1.2.1.43.16.5.1.2"
PRT_ALERT_DESCR = "1.3.6.1.2.1.43.18.1.1.8"
IF_TABLE = "1.3.6.1.2.1.2.2.1"
IP_ADDR_IFINDEX = "1.3.6.1.2.1.4.20.1.2"
IP_ADDR_MASK = "1.3.6.1.2.1.4.20.1.3"
ENT_SOFTWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.10"
ENT_FIRMWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.9"
# IANA enterprise numbers of printer manufacturers (from sysObjectID).
ENTERPRISES = {
11: "HP", 1347: "Kyocera", 2435: "Brother", 367: "Ricoh", 1602: "Canon", 18334: "Konica Minolta",
641: "Lexmark", 253: "Xerox", 1248: "Epson", 2001: "OKI", 674: "Dell", 236: "Samsung", 297: "Fujifilm",
1129: "Toshiba", 2385: "Sharp", 26696: "HP", 2699: "Printer Working Group", 1552: "Utax", 3369: "Sharp",
10642: "Zebra", 683: "Zebra", 5530: "Develop", 4322: "Develop", 15315: "Muratec", 3793: "Panasonic",
}
MANUFACTURER_NAMES = (
"Hewlett-Packard", "HP", "Kyocera", "Brother", "Ricoh", "Canon", "Konica Minolta", "Lexmark", "Xerox", "Epson",
"OKI", "Dell", "Samsung", "Fujifilm", "Fuji Xerox", "Toshiba", "Sharp", "Utax", "TA Triumph-Adler", "Develop",
"Zebra", "Muratec", "Panasonic", "Olivetti", "Kyocera Mita", "Konica", "Minolta", "Nashuatec", "Gestetner",
)
PRINTER_STATUS = {1: "sonstiges", 2: "unbekannt", 3: "bereit", 4: "druckt", 5: "wärmt auf"}
ERROR_BITS = ("wenig Papier", "kein Papier", "wenig Toner", "kein Toner", "Klappe offen", "Papierstau", "offline",
"Service angefordert", "Papierfach fehlt", "Ausgabefach fehlt", "Verbrauchsmaterial fehlt",
"Ausgabefach fast voll", "Ausgabefach voll", "Papierfach leer", "Wartung überfällig")
SUPPLY_TYPES = {3: "Toner", 4: "Resttoner", 5: "Tinte", 6: "Tintenpatrone", 7: "Tintenbehälter", 9: "Trommel",
10: "Entwickler", 15: "Fixiereinheit", 20: "Transfereinheit", 21: "Tonerkassette",
22: "Fixieröl", 32: "Heftklammern"}
CUSTOM_FIELDS = (
("printer_page_count", "Seitenzähler", "integer"),
("printer_supplies", "Verbrauchsmaterial", "longtext"),
("printer_color", "Farbdrucker", "boolean"),
("printer_last_scan", "Letzter Drucker-Scan", "date"),
)
ROLE_HINTS = ("drucker", "printer", "multifunktion", "mfp", "mfd", "multifunction")
class PrinterError(ValueError):
pass
# ----------------------------------------------------------------------
# Reading a printer
# ----------------------------------------------------------------------
def _first(values):
return next((value for _key, value in sorted(values.items(), key=lambda item: snmp.oid_key(item[0]))
if snmp.text(value)), None)
def manufacturer_from(object_id, *texts):
for text in texts:
for name in MANUFACTURER_NAMES:
if re.search(rf"\b{re.escape(name)}\b", text or "", re.IGNORECASE):
return {"Hewlett-Packard": "HP", "Kyocera Mita": "Kyocera", "Fuji Xerox": "Fujifilm",
"Konica": "Konica Minolta", "Minolta": "Konica Minolta"}.get(name, name)
parts = snmp.oid_key(object_id) if object_id else ()
if parts[:6] == (1, 3, 6, 1, 4, 1) and len(parts) > 6:
return ENTERPRISES.get(parts[6], "")
return ""
def clean_model(text, manufacturer):
model = re.sub(r"\s+", " ", snmp.text(text)).strip(" ;,")
model = re.split(r";|,| - |\bFW\b|\bFirmware\b|\bS/N\b", model)[0].strip()
for prefix in (manufacturer, "Hewlett-Packard", "HP", "Kyocera Mita", "Konica Minolta", "KONICA MINOLTA"):
if prefix and model.casefold().startswith(prefix.casefold() + " "):
model = model[len(prefix) + 1:].strip()
return model[:100]
def mac_text(value):
if isinstance(value, bytes) and len(value) == 6 and any(value):
return normalize_mac(value.hex()) or ""
return normalize_mac(snmp.text(value)) or "" if value else ""
def error_flags(value):
if not isinstance(value, bytes):
return []
flags = []
for index, name in enumerate(ERROR_BITS):
byte, bit = divmod(index, 8)
if byte < len(value) and value[byte] & (0x80 >> bit):
flags.append(name)
return flags
def supplies_from(walked, colorants):
"""List of ``{"name", "type", "level", "max", "percent"}`` from prtMarkerSuppliesTable."""
supplies = []
for _index, row in sorted(snmp.table(walked, PRT_SUPPLIES).items()):
name = snmp.text(row.get(6))
kind = SUPPLY_TYPES.get(row.get(5), "")
level, maximum = row.get(9), row.get(8)
if not name and not kind:
continue
colour = colorants.get(row.get(3)) if row.get(3) else ""
percent = None
if isinstance(level, int) and isinstance(maximum, int) and level >= 0 and maximum > 0:
percent = max(0, min(100, round(level * 100 / maximum)))
state = {-3: "vorhanden", -2: "unbekannt", -1: "sonstiges"}.get(level, "") if isinstance(level, int) else ""
if isinstance(level, int) and level >= 0 and maximum in (-1, -2, None):
state = f"{level}"
supplies.append({"name": name or " ".join(filter(None, (kind, colour))), "type": kind, "colour": colour,
"level": level, "max": maximum, "percent": percent, "state": state})
return supplies
def supplies_text(supplies):
lines = []
for item in supplies:
value = f"{item['percent']} %" if item["percent"] is not None else (item["state"] or "–")
lines.append(f"{item['name']}: {value}")
return "\n".join(lines)
def trays_from(walked):
trays = []
for _index, row in sorted(snmp.table(walked, PRT_INPUT).items()):
name = snmp.text(row.get(13)) or snmp.text(row.get(18)) or f"Fach {len(trays) + 1}"
media = snmp.text(row.get(12))
capacity, current = row.get(9), row.get(10)
level = ""
if isinstance(current, int) and isinstance(capacity, int) and capacity > 0 and current >= 0:
level = f"{current}/{capacity} Blatt"
elif current == -3:
level = "Papier vorhanden"
elif current == 0:
level = "leer"
trays.append({"name": name, "media": media, "capacity": capacity if isinstance(capacity, int) else None,
"level": level})
return trays
def read_printer(client, ip):
"""Printer data via SNMP, or ``None`` when the device is no printer."""
base = client.get([SYS_DESCR, SYS_OBJECT_ID, SYS_NAME, SYS_LOCATION, SYS_CONTACT, SYS_UPTIME])
types = client.walk(HR_DEVICE_TYPE, limit=200)
printer_indexes = [snmp.oid_key(oid)[-1] for oid, value in types.items() if value == HR_PRINTER]
serials = client.walk(PRT_SERIAL, limit=20)
counters = client.walk(PRT_LIFE_COUNT, limit=20)
if not printer_indexes and not serials and not counters:
return None
descr = client.get([f"{HR_DEVICE_DESCR}.{index}" for index in printer_indexes]) if printer_indexes else {}
printer_name = snmp.text(_first(client.walk(PRT_PRINTER_NAME, limit=20)))
device_id = snmp.text(client.get([HP_DEVICE_ID]).get(HP_DEVICE_ID))
device_model = next((part.split(":", 1)[1].strip() for part in device_id.split(";")
if part.strip().upper().startswith(("MDL:", "MODEL:"))), "")
status = client.get([f"{oid}.{index}" for index in printer_indexes[:1]
for oid in (HR_PRINTER_STATUS, HR_PRINTER_ERRORS)]) if printer_indexes else {}
colorants_raw = client.walk(PRT_COLORANT, limit=50)
colorants = {snmp.oid_key(oid)[-1]: snmp.text(value) for oid, value in colorants_raw.items()}
supplies = supplies_from(client.walk(PRT_SUPPLIES, limit=600), colorants)
trays = trays_from(client.walk(PRT_INPUT, limit=600))
display = [snmp.text(value) for value in client.walk(PRT_DISPLAY, limit=20).values() if snmp.text(value)]
alerts = list(dict.fromkeys(snmp.text(value) for value in client.walk(PRT_ALERT_DESCR, limit=100).values()
if snmp.text(value)))
interfaces = snmp.table(client.walk(IF_TABLE, limit=800), IF_TABLE)
addressing = client.get([f"{IP_ADDR_IFINDEX}.{ip}", f"{IP_ADDR_MASK}.{ip}"])
firmware = snmp.text(_first(client.walk(ENT_SOFTWARE_REV, limit=50)) or _first(
client.walk(ENT_FIRMWARE_REV, limit=50)))
sys_descr = snmp.text(base.get(SYS_DESCR))
object_id = base.get(SYS_OBJECT_ID) or ""
candidates = [printer_name, snmp.text(next(iter(descr.values()), "")) if descr else "", device_model, sys_descr]
model_text = next((text for text in candidates if text and not GENERIC_DESCR.search(text)), "")
manufacturer = manufacturer_from(object_id, model_text, sys_descr)
model = clean_model(model_text, manufacturer)
if not firmware:
match = re.search(r"(?:firmware|fw|version|ver\.?)\s*[:=]?\s*([\w.\-]+)", sys_descr, re.IGNORECASE)
firmware = match.group(1) if match else ""
if_index = addressing.get(f"{IP_ADDR_IFINDEX}.{ip}")
mac = mac_text(interfaces.get((if_index,), {}).get(6)) if isinstance(if_index, int) else ""
if not mac:
for _index, row in sorted(interfaces.items()):
if row.get(3) in (6, 71, 117) and mac_text(row.get(6)):
mac = mac_text(row.get(6))
break
prefix_length = None
mask = addressing.get(f"{IP_ADDR_MASK}.{ip}")
if isinstance(mask, str):
try:
prefix_length = ipaddress.ip_network(f"0.0.0.0/{mask}").prefixlen
except ValueError:
prefix_length = None
colours = [name for name in colorants.values() if name]
colour = any(name.casefold() not in ("black", "schwarz", "unknown", "other") for name in colours) or any(
item["colour"] and item["colour"].casefold() not in ("black", "schwarz") for item in supplies)
page_count = max((value for value in counters.values() if isinstance(value, int)), default=None)
status_value = status.get(f"{HR_PRINTER_STATUS}.{printer_indexes[0]}") if printer_indexes else None
errors = error_flags(status.get(f"{HR_PRINTER_ERRORS}.{printer_indexes[0]}")) if printer_indexes else []
serial = snmp.text(_first(serials)).upper()
return {
"name": snmp.text(base.get(SYS_NAME)), "sys_descr": sys_descr, "object_id": object_id,
"manufacturer": manufacturer, "model": model, "serial": serial, "firmware": firmware,
"site_hint": snmp.text(base.get(SYS_LOCATION)), "contact": snmp.text(base.get(SYS_CONTACT)),
"uptime": base.get(SYS_UPTIME), "mac": mac, "prefix_length": prefix_length,
"page_count": page_count, "color": bool(colour), "supplies": supplies, "trays": trays,
"status": PRINTER_STATUS.get(status_value, ""), "errors": errors, "display": display, "alerts": alerts,
}
# ----------------------------------------------------------------------
# Scan
# ----------------------------------------------------------------------
def credential_label(record):
try:
return snmp.Credential(record).label
except snmp.SnmpError:
return "ungültig"
def _ordered(credentials, preferred_id):
if not preferred_id:
return list(credentials)
return sorted(credentials, key=lambda record: record.get("id") != preferred_id)
def scan_host(ip, credentials, preferred=None, timeout=1.0):
"""``{"ip", "alive", "printer": bool, ...}`` for one address."""
alive = netscan.ping(ip) is not None
ports = []
if not alive:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if not ports:
return {"ip": ip, "alive": False, "printer": False}
result = {"ip": ip, "alive": True, "printer": False, "snmp": "", "credential_id": None, "notes": []}
try:
client, notes = snmp.connect(ip, _ordered(credentials, (preferred or {}).get(ip)), timeout=timeout)
result["notes"] += notes
info = read_printer(client, ip)
result["snmp"] = client.credential.label
result["credential_id"] = client.credential.record.get("id")
if info:
result.update(info, printer=True)
if not result["mac"]:
result["mac"] = netscan.arp_mac(ip) or ""
return result
except snmp.SnmpAuthError as error:
result["notes"].append(str(error))
except snmp.SnmpError as error:
if not isinstance(error, snmp.SnmpTimeout):
result["notes"].append(f"SNMP-Fehler: {error}")
except OSError as error:
result["notes"].append(f"SNMP-Fehler: {error}")
if result["snmp"]:
return result # answers SNMP but is no printer
if not ports:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if 9100 in ports or (631 in ports and 515 in ports):
result.update(printer=True, name=netscan.reverse_dns(ip) or "", mac=netscan.arp_mac(ip) or "",
manufacturer="", model="", serial="", firmware="", site_hint="", supplies=[], trays=[],
page_count=None, color=None, errors=[], display=[], alerts=[], status="",
prefix_length=None)
result["notes"].append("Druckerports offen (" + ", ".join(map(str, ports)) + "), aber keine SNMP-Antwort"
" – Zugangsdaten prüfen")
return result
def scan(ips, credentials, on_result, cancelled=lambda: False, preferred=None, workers=48, timeout=1.0):
if not credentials:
raise PrinterError("Bitte mindestens eine SNMP-Community oder einen SNMPv3-Benutzer hinterlegen.")
for record in credentials:
snmp.Credential(record) # validates protocols early
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(scan_host, ip, credentials, preferred, timeout): ip for ip in ips}
for future in as_completed(futures):
if cancelled():
for pending in futures:
pending.cancel()
break
try:
on_result(future.result())
except Exception as error: # noqa: BLE001 - one host must not stop the scan
on_result({"ip": futures[future], "alive": True, "printer": False, "notes": [str(error)]})
def to_import(host):
"""Scan result → record for the sync (same keys as an access point)."""
name = host.get("name") or netscan.reverse_dns(host["ip"]) or f"Drucker {host['ip']}"
issues = list(host.get("notes", []))
if host.get("errors"):
issues.append("Gerät meldet: " + ", ".join(host["errors"]))
defaults = {"manufacturer": "", "model": "", "firmware": "", "supplies": [], "trays": [], "page_count": None,
"color": None, "errors": [], "display": [], "alerts": [], "status": "", "prefix_length": None,
"snmp": ""}
return dict({**defaults, **host}, name=re.sub(r"\s+", " ", name).strip()[:64], serial=(host.get("serial") or "").upper(),
mac=normalize_mac(host.get("mac")) or "", issues=issues, site_hint=host.get("site_hint") or "")
def mark_duplicates(printers):
for key, text in (("serial", "Seriennummer"), ("mac", "MAC-Adresse")):
groups = {}
for printer in printers:
if printer.get(key):
groups.setdefault(printer[key], []).append(printer)
for value, members in groups.items():
if len(members) > 1:
for printer in members:
others = ", ".join(other["ip"] for other in members if other is not printer)
printer["issues"].append(f"{text} {value} doppelt (auch {others})")
def model_key(printer):
"""Key of the NetBox device type a new printer needs (``manufacturer|model``, case-insensitive)."""
return f"{printer.get('manufacturer') or 'Unbekannt'}|{printer.get('model') or 'Drucker'}".casefold()
def printer_key(printer):
return printer.get("serial") or printer.get("mac") or printer["ip"]
# ----------------------------------------------------------------------
# NetBox
# ----------------------------------------------------------------------
class PrinterSyncEngine(APSyncEngine):
"""Access point import with printer identity, IP matching and custom fields."""
def __init__(self, nb, log=None, role_id=None, counters=True):
super().__init__(nb, log)
self.role_id = role_id
self.counters = counters
self.today = datetime.date.today().isoformat()
self.device_types = []
self.type_map = {} # model_key -> device type ID chosen by the user
def load_context(self, tenant_id=None):
result = super().load_context(tenant_id)
self.device_types = sorted(({"id": item.id, "model": item.model,
"manufacturer": getattr(getattr(item, "manufacturer", None), "name", "") or ""}
for item in self.nb.dcim.device_types.all()),
key=lambda row: (row["manufacturer"].casefold(), row["model"].casefold()))
return result
def type_exists(self, printer):
"""Is the device type of ``printer`` already in NetBox (same manufacturer and model)?"""
manufacturer, model, _platform = self._identity(printer)
return any(row["model"].casefold() == model.casefold() and row["manufacturer"].casefold() in (
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")
for row in self.device_types)
def suggest_type(self, printer):
"""Device type with a similar model name, or ``None``."""
model = re.sub(r"[^0-9a-z]", "", (printer.get("model") or "").casefold())
if len(model) < 4:
return None
matches = [row["id"] for row in self.device_types
if model in re.sub(r"[^0-9a-z]", "", row["model"].casefold())
or re.sub(r"[^0-9a-z]", "", row["model"].casefold()) in model]
return matches[0] if len(matches) == 1 else None
def _mapped_type(self, printer):
return self.type_map.get(model_key(printer))
def _known_devices(self, scope):
if not self.role_id:
return []
return list(self.nb.dcim.devices.filter(role_id=self.role_id, **scope))
def _identity(self, printer):
return printer.get("manufacturer") or "Unbekannt", printer.get("model") or "Drucker", None
def _custom_values(self, printer):
if not self.counters or not printer.get("snmp"):
return {}
values = {"printer_last_scan": self.today}
if printer.get("page_count") is not None:
values["printer_page_count"] = printer["page_count"]
if printer.get("supplies"):
values["printer_supplies"] = supplies_text(printer["supplies"])
if printer.get("color") is not None:
values["printer_color"] = bool(printer["color"])
return values
def _extra_payload(self, printer):
values = self._custom_values(printer)
return {"custom_fields": values} if values else {}
def _extra_updates(self, device, printer):
values = self._custom_values(printer)
current = dict(getattr(device, "custom_fields", None) or {})
changed = {key: value for key, value in values.items() if current.get(key) != value}
if not changed or set(changed) == {"printer_last_scan"} and len(values) > 1:
return {}, []
texts = []
if "printer_page_count" in changed:
texts.append(f"Seitenzähler {current.get('printer_page_count') or '–'} → {changed['printer_page_count']}")
if "printer_supplies" in changed:
texts.append("Verbrauchsmaterial")
if "printer_color" in changed:
texts.append("Farbdrucker" if changed["printer_color"] else "Schwarzweiß")
return {"custom_fields": dict(current, **values)}, texts or ["Scan-Datum"]
def match(self, printers):
"""Base matching plus the IP address assigned to a device interface."""
only_netbox = super().match(printers)
open_items = [printer for printer in printers if printer.get("device") is None and printer.get("ip")]
if not open_items:
return only_netbox
by_ip = {}
ips = sorted({printer["ip"] for printer in open_items})
for start in range(0, len(ips), CHUNK):
for record in self.nb.ipam.ip_addresses.filter(address=ips[start:start + CHUNK]):
if getattr(record, "assigned_object_type", None) != "dcim.interface":
continue
device_id = related_id(getattr(record, "assigned_object", None), "device")
if device_id:
by_ip.setdefault(str(record.address).split("/")[0], set()).add(device_id)
matched = set()
for printer in open_items:
devices = by_ip.get(printer["ip"], set())
if len(devices) == 1:
device = self.nb.dcim.devices.get(next(iter(devices)))
if device is not None:
printer["device"], printer["method"] = device, "IP-Adresse"
matched.add(device.id)
if related_id(device, "tenant") not in self.tenant_ids:
printer["issues"].append("NetBox-Gerät gehört " + (
f"Mandant „{getattr(device.tenant, 'name', '')}“ außerhalb der Mandantengruppe"
if related_id(device, "tenant") else "keinem Mandanten"))
return [device for device in only_netbox if device.id not in matched]
def ensure_custom_fields(self, dry_run, report):
"""Create the printer custom fields that are missing."""
if not self.counters:
return
existing = {field.name for field in self.nb.extras.custom_fields.filter(
name=[name for name, _label, _type in CUSTOM_FIELDS])}
key = "object_types" if version_tuple(self.nb) >= (4, 0) else "content_types"
for name, label, kind in CUSTOM_FIELDS:
if name in existing:
continue
report["changes"].append(f"Benutzerdefiniertes Feld {label} ({name}) anlegen")
report["objects_created"] += 1
if not dry_run:
self.nb.extras.custom_fields.create({
"name": name, "label": label, "type": kind, key: ["dcim.device"], "group_name": "Drucker",
"required": False, "description": "Aus dem SNMP-Drucker-Scan",
})
def sync(self, printers, placements, role_id, rename=True, dry_run=True, default_site=None):
report = self.new_report()
try:
self.ensure_custom_fields(dry_run, report)
except Exception as error: # noqa: BLE001 - devices can still be documented
report["errors"].append(f"Benutzerdefinierte Felder: {error}")
self.counters = False
result = super().sync(printers, placements, role_id, rename, dry_run, default_site)
for key, value in result.items():
if isinstance(value, list):
report[key] = report.get(key, []) + value
else:
report[key] = report.get(key, 0) + value
return report
+540
View File
@@ -0,0 +1,540 @@
"""Small SNMP client (v2c and v3 USM) for reading devices – no external SNMP library.
Supports GET and GETBULK walks. SNMPv3 handles engine discovery, time
synchronisation, authentication (MD5, SHA-1, SHA-224/256/384/512) and privacy
(DES, AES-128 and AES-192/256 with Blumenthal key extension) using the
``cryptography`` package that paramiko already brings along.
"""
import hashlib
import hmac
import itertools
import random
import socket
import struct
import time
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
try: # cryptography >= 43 moved TripleDES (used for single DES with K1=K2=K3)
from cryptography.hazmat.decrepit.ciphers.algorithms import TripleDES
except ImportError: # pragma: no cover - older cryptography
TripleDES = algorithms.TripleDES
PORT = 161
# ASN.1 / SNMP tags
INTEGER, OCTET_STRING, NULL, OID, SEQUENCE = 0x02, 0x04, 0x05, 0x06, 0x30
IP_ADDRESS, COUNTER32, GAUGE32, TIMETICKS, OPAQUE, COUNTER64 = 0x40, 0x41, 0x42, 0x43, 0x44, 0x46
NO_SUCH_OBJECT, NO_SUCH_INSTANCE, END_OF_MIB_VIEW = 0x80, 0x81, 0x82
GET, GET_NEXT, RESPONSE, GET_BULK, REPORT = 0xA0, 0xA1, 0xA2, 0xA5, 0xA8
AUTH_PROTOCOLS = { # name -> (hash, length of the truncated HMAC)
"MD5": (hashlib.md5, 12), "SHA": (hashlib.sha1, 12), "SHA-224": (hashlib.sha224, 16),
"SHA-256": (hashlib.sha256, 24), "SHA-384": (hashlib.sha384, 32), "SHA-512": (hashlib.sha512, 48),
}
PRIV_PROTOCOLS = {"DES": 8, "AES": 16, "AES-192": 24, "AES-256": 32} # name -> key length
REPORT_TEXT = {
"1.3.6.1.6.3.15.1.1.1.0": "Sicherheitsstufe wird nicht unterstützt",
"1.3.6.1.6.3.15.1.1.2.0": "nicht im Zeitfenster",
"1.3.6.1.6.3.15.1.1.3.0": "unbekannter Benutzer",
"1.3.6.1.6.3.15.1.1.4.0": "unbekannte Engine-ID",
"1.3.6.1.6.3.15.1.1.5.0": "falsches Authentifizierungs-Passwort oder -Protokoll",
"1.3.6.1.6.3.15.1.1.6.0": "Entschlüsselung fehlgeschlagen (Privacy-Passwort oder -Protokoll falsch)",
}
class SnmpError(Exception):
"""Base error."""
class SnmpTimeout(SnmpError):
"""No answer – host down, SNMP off or (for v2c) wrong community."""
class SnmpAuthError(SnmpError):
"""The agent answered but rejected the credentials (SNMPv3 report)."""
# ----------------------------------------------------------------------
# BER encoding
# ----------------------------------------------------------------------
def _length(size):
if size < 0x80:
return bytes([size])
raw = size.to_bytes((size.bit_length() + 7) // 8, "big")
return bytes([0x80 | len(raw)]) + raw
def tlv(tag, content):
return bytes([tag]) + _length(len(content)) + content
def enc_int(value, tag=INTEGER):
size = max(1, (value.bit_length() + 8) // 8)
return tlv(tag, value.to_bytes(size, "big", signed=True))
def enc_str(value):
return tlv(OCTET_STRING, value if isinstance(value, bytes) else str(value).encode())
def enc_oid(oid):
parts = [int(part) for part in str(oid).strip(".").split(".")]
body = bytearray([parts[0] * 40 + parts[1]])
for part in parts[2:]:
chunk = [part & 0x7F]
part >>= 7
while part:
chunk.append(0x80 | (part & 0x7F))
part >>= 7
body += bytes(reversed(chunk))
return tlv(OID, bytes(body))
def seq(*items):
return tlv(SEQUENCE, b"".join(items))
def decode(data, pos=0):
"""``(tag, content, next position)`` of the TLV at ``pos``."""
if pos + 2 > len(data):
raise SnmpError("Antwort unvollständig")
tag, size = data[pos], data[pos + 1]
pos += 2
if size & 0x80:
count = size & 0x7F
size = int.from_bytes(data[pos:pos + count], "big")
pos += count
if pos + size > len(data):
raise SnmpError("Antwort unvollständig")
return tag, data[pos:pos + size], pos + size
def children(content):
items, pos = [], 0
while pos < len(content):
tag, value, pos = decode(content, pos)
items.append((tag, value))
return items
def dec_oid(content):
first = content[0]
parts = [first // 40 if first < 80 else 2, first % 40 if first < 80 else first - 80]
value = 0
for byte in content[1:]:
value = (value << 7) | (byte & 0x7F)
if not byte & 0x80:
parts.append(value)
value = 0
return ".".join(map(str, parts))
def dec_value(tag, content):
if tag == INTEGER:
return int.from_bytes(content, "big", signed=True)
if tag in (COUNTER32, GAUGE32, TIMETICKS, COUNTER64):
return int.from_bytes(content, "big")
if tag == OID:
return dec_oid(content)
if tag == IP_ADDRESS:
return ".".join(str(byte) for byte in content)
if tag in (OCTET_STRING, OPAQUE):
return bytes(content)
return None # NULL, noSuchObject, noSuchInstance, endOfMibView
def oid_key(oid):
return tuple(int(part) for part in oid.strip(".").split("."))
def in_subtree(oid, root):
return oid_key(oid)[:len(oid_key(root))] == oid_key(root)
def text(value):
"""OCTET STRING as readable text (trailing NULs and control characters removed)."""
if value is None:
return ""
if isinstance(value, bytes):
for encoding in ("utf-8", "cp1252"):
try:
value = value.decode(encoding)
break
except UnicodeDecodeError:
continue
return "".join(char for char in str(value) if char.isprintable()).strip()
# ----------------------------------------------------------------------
# PDUs
# ----------------------------------------------------------------------
def _pdu(kind, request_id, oids, non_repeaters=0, max_repetitions=0):
varbinds = seq(*(seq(enc_oid(oid), tlv(NULL, b"")) for oid in oids))
return tlv(kind, enc_int(request_id) + enc_int(non_repeaters) + enc_int(max_repetitions) + varbinds)
def _parse_pdu(tag, content):
request_id, status, index, varbinds = children(content)
bindings = []
for _tag, binding in children(varbinds[1]):
(_oid_tag, oid_raw), (value_tag, value_raw) = children(binding)
bindings.append((dec_oid(oid_raw), value_tag, dec_value(value_tag, value_raw)))
return {"type": tag, "request_id": dec_value(INTEGER, request_id[1]), "error_status": dec_value(INTEGER, status[1]),
"error_index": dec_value(INTEGER, index[1]), "varbinds": bindings}
# ----------------------------------------------------------------------
# SNMPv3 keys and crypto
# ----------------------------------------------------------------------
_KEY_CACHE = {}
def aes_cfb(key, iv, data, decrypt=False):
"""AES-CFB128 (RFC 3826) built on ECB – the CFB mode of ``cryptography`` is being deprecated."""
encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
out, register = bytearray(), iv
for start in range(0, len(data), 16):
block = data[start:start + 16]
stream = encryptor.update(register)
chunk = bytes(a ^ b for a, b in zip(block, stream))
out += chunk
register = (block if decrypt else chunk).ljust(16, b"\0")
return bytes(out)
def password_to_key(password, hash_func):
"""RFC 3414 A.2: hash of the password repeated to 1 MB."""
key = (password, hash_func().name)
if key not in _KEY_CACHE:
data = password.encode()
if not data:
raise SnmpError("leeres SNMPv3-Passwort")
digest = hash_func()
repeated = (data * (64 // len(data) + 2))
chunk = (repeated * (1048576 // len(repeated) + 1))[:1048576]
digest.update(chunk)
_KEY_CACHE[key] = digest.digest()
return _KEY_CACHE[key]
def localize(key, engine_id, hash_func):
return hash_func(key + engine_id + key).digest()
def priv_key(password, engine_id, hash_func, size):
key = localize(password_to_key(password, hash_func), engine_id, hash_func)
while len(key) < size: # Blumenthal key extension for AES-192/256
key += hash_func(key).digest()
return key[:size] if size > 8 else key[:16] # DES needs key + pre-IV
class Credential:
"""One set of credentials: ``{"version": "2c", "community": …}`` or a v3 user."""
def __init__(self, record):
self.record = record
self.version = str(record.get("version") or "2c")
self.community = record.get("community") or "public"
self.username = record.get("username") or ""
self.auth_protocol = record.get("auth_protocol") or ""
self.auth_password = record.get("auth_password") or ""
self.priv_protocol = record.get("priv_protocol") or ""
self.priv_password = record.get("priv_password") or ""
self.context = record.get("context") or ""
if self.version == "3":
if self.auth_protocol and self.auth_protocol not in AUTH_PROTOCOLS:
raise SnmpError(f"unbekanntes Authentifizierungs-Protokoll {self.auth_protocol}")
if self.priv_protocol and self.priv_protocol not in PRIV_PROTOCOLS:
raise SnmpError(f"unbekanntes Privacy-Protokoll {self.priv_protocol}")
if self.priv_protocol and not self.auth_protocol:
raise SnmpError("Privacy ohne Authentifizierung ist bei SNMPv3 nicht möglich")
@property
def label(self):
if self.version != "3":
return "SNMPv2c"
level = ("authPriv" if self.priv_protocol else "authNoPriv") if self.auth_protocol else "noAuthNoPriv"
return f"SNMPv3 {self.username} ({level})"
# ----------------------------------------------------------------------
# Client
# ----------------------------------------------------------------------
_ids = itertools.count(random.randint(1, 1 << 30))
class SnmpClient:
def __init__(self, host, credential, timeout=1.0, retries=1, port=PORT):
self.host, self.port = host, port
self.credential = credential if isinstance(credential, Credential) else Credential(credential)
self.timeout, self.retries = timeout, retries
self.engine_id = b""
self.boots = self.engine_time = 0
self._time_base = 0.0
self._salt = random.getrandbits(64)
self.bulk = True
# transport ----------------------------------------------------------
def _exchange(self, packet, accept):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(self.timeout)
for _attempt in range(self.retries + 1):
try:
sock.sendto(packet, (self.host, self.port))
except OSError as error:
raise SnmpTimeout(str(error)) from error
deadline = time.monotonic() + self.timeout
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
sock.settimeout(remaining)
try:
data, _addr = sock.recvfrom(65535)
except (socket.timeout, ConnectionResetError):
break
except OSError:
break
try:
result = accept(data)
except SnmpAuthError:
raise
except (SnmpError, ValueError, IndexError):
continue
if result is not None:
return result
raise SnmpTimeout(f"{self.host}: keine SNMP-Antwort")
# v2c ----------------------------------------------------------------
def _request_v2(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
request_id = next(_ids) & 0x7FFFFFFF
community = self.credential.community.encode()
packet = seq(enc_int(1), enc_str(community), _pdu(pdu_type, request_id, oids, non_repeaters, max_repetitions))
def accept(data):
_tag, content, _pos = decode(data)
version, community_raw, (pdu_tag, pdu_content) = children(content)
if community_raw[1] != community:
return None
pdu = _parse_pdu(pdu_tag, pdu_content)
return pdu if pdu["request_id"] == request_id else None
return self._exchange(packet, accept)
# v3 -----------------------------------------------------------------
def _hash(self):
return AUTH_PROTOCOLS[self.credential.auth_protocol][0] if self.credential.auth_protocol else None
def _discover(self):
msg_id = next(_ids) & 0x7FFFFFFF
usm = seq(enc_str(b""), enc_int(0), enc_int(0), enc_str(b""), enc_str(b""), enc_str(b""))
scoped = seq(enc_str(b""), enc_str(b""), _pdu(GET, msg_id, []))
packet = seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x04"), enc_int(3)),
enc_str(usm), scoped)
message = self._exchange(packet, lambda data: self._parse_v3(data, msg_id, verify=False))
if not message["engine_id"]:
raise SnmpError(f"{self.host}: keine SNMPv3-Engine-ID erhalten")
self._set_engine(message)
def _set_engine(self, message):
self.engine_id = message["engine_id"]
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
hash_func = self._hash()
cred = self.credential
self._auth_key = localize(password_to_key(cred.auth_password, hash_func), self.engine_id, hash_func) \
if hash_func else None
self._priv_key = priv_key(cred.priv_password, self.engine_id, hash_func, PRIV_PROTOCOLS[cred.priv_protocol]) \
if cred.priv_protocol else None
def _now(self):
return self.engine_time + int(time.monotonic() - self._time_base)
def _encrypt(self, plain, now):
cred = self.credential
self._salt = (self._salt + 1) & 0xFFFFFFFFFFFFFFFF
if cred.priv_protocol == "DES":
salt = struct.pack(">II", self.boots & 0xFFFFFFFF, self._salt & 0xFFFFFFFF)
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
plain += b"\x00" * (-len(plain) % 8)
encryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).encryptor()
else:
salt = struct.pack(">Q", self._salt)
iv = struct.pack(">II", self.boots, now) + salt
return aes_cfb(self._priv_key, iv, plain), salt
return encryptor.update(plain) + encryptor.finalize(), salt
def _decrypt(self, data, salt, boots, engine_time):
if self.credential.priv_protocol == "DES":
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
decryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).decryptor()
else:
iv = struct.pack(">II", boots, engine_time) + salt
return aes_cfb(self._priv_key, iv, data, decrypt=True)
return decryptor.update(data) + decryptor.finalize()
def _parse_v3(self, data, msg_id, verify=True):
_tag, content, _pos = decode(data)
version, header, (_usm_tag, usm_raw), (data_tag, data_raw) = children(content)
if dec_value(INTEGER, version[1]) != 3:
raise SnmpError("keine SNMPv3-Antwort")
header_items = children(header[1])
if dec_value(INTEGER, header_items[0][1]) != msg_id:
return None
flags = header_items[2][1][0] if header_items[2][1] else 0
_t, usm_content, _p = decode(usm_raw)
engine_id, boots, engine_time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
message = {"engine_id": bytes(engine_id), "boots": dec_value(INTEGER, boots),
"time": dec_value(INTEGER, engine_time)}
if verify and flags & 0x01 and self._auth_key:
hash_func, size = AUTH_PROTOCOLS[self.credential.auth_protocol]
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if hmac.new(self._auth_key, zeroed, hash_func).digest()[:size] != auth_params:
raise SnmpError("Antwort mit ungültiger Signatur")
if data_tag == OCTET_STRING:
if not self._priv_key:
raise SnmpError("verschlüsselte Antwort ohne Privacy-Schlüssel")
plain = self._decrypt(bytes(data_raw), bytes(priv_params), message["boots"], message["time"])
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_context_engine, _context_name, (pdu_tag, pdu_content) = children(scoped)
message["pdu"] = _parse_pdu(pdu_tag, pdu_content)
return message
def _request_v3(self, pdu_type, oids, non_repeaters=0, max_repetitions=0, resync=True):
if not self.engine_id:
self._discover()
cred = self.credential
msg_id = next(_ids) & 0x7FFFFFFF
pdu = _pdu(pdu_type, msg_id, oids, non_repeaters, max_repetitions)
scoped = seq(enc_str(self.engine_id), enc_str(cred.context), pdu)
flags = 0x04 | (0x01 if cred.auth_protocol else 0) | (0x02 if cred.priv_protocol else 0)
salt, now = b"", self._now()
if cred.priv_protocol:
encrypted, salt = self._encrypt(scoped, now)
body = enc_str(encrypted)
else:
body = scoped
auth_size = AUTH_PROTOCOLS[cred.auth_protocol][1] if cred.auth_protocol else 0
def build(auth_params):
usm = seq(enc_str(self.engine_id), enc_int(self.boots), enc_int(now), enc_str(cred.username),
enc_str(auth_params), enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * auth_size)
if cred.auth_protocol:
hash_func, size = AUTH_PROTOCOLS[cred.auth_protocol]
packet = build(hmac.new(self._auth_key, packet, hash_func).digest()[:size])
def accept(data):
return self._parse_v3(data, msg_id)
message = self._exchange(packet, accept)
pdu = message["pdu"]
if pdu["type"] == REPORT:
oid = pdu["varbinds"][0][0] if pdu["varbinds"] else ""
if oid == "1.3.6.1.6.3.15.1.1.2.0" and resync: # not in time window: resynchronise once
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions, resync=False)
raise SnmpAuthError(f"SNMPv3 {cred.username}: {REPORT_TEXT.get(oid, 'abgelehnt (' + oid + ')')}")
return pdu
# public API ---------------------------------------------------------
def request(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
if self.credential.version == "3":
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions)
return self._request_v2(pdu_type, oids, non_repeaters, max_repetitions)
def get(self, oids):
"""``{oid: value}``; missing objects are left out."""
result = {}
oids = list(oids)
for start in range(0, len(oids), 20):
pdu = self.request(GET, oids[start:start + 20])
if pdu["error_status"]:
# v1-style error for one bad OID: fall back to single requests
for oid in oids[start:start + 20]:
single = self.request(GET, [oid])
if not single["error_status"]:
result.update({o: v for o, tag, v in single["varbinds"] if tag < NO_SUCH_OBJECT})
continue
result.update({oid: value for oid, tag, value in pdu["varbinds"] if tag < NO_SUCH_OBJECT})
return result
def walk(self, root, limit=2000):
"""``{oid: value}`` of the subtree below ``root``."""
result, current = {}, root
while len(result) < limit:
if self.bulk:
pdu = self.request(GET_BULK, [current], 0, 25)
if pdu["error_status"]:
self.bulk = False
continue
else:
pdu = self.request(GET_NEXT, [current])
if pdu["error_status"]:
break
if not pdu["varbinds"]:
break
done = False
for oid, tag, value in pdu["varbinds"]:
if tag == END_OF_MIB_VIEW or not in_subtree(oid, root) or oid_key(oid) <= oid_key(current):
done = True
break
result[oid] = value
current = oid
if done:
break
return result
def connect(host, credentials, timeout=1.0, retries=1, check_oid="1.3.6.1.2.1.1.2.0", port=PORT):
"""First credential that works for ``host``: ``(client, notes)``.
``notes`` collects why other credentials failed (e.g. a wrong v3 password),
which helps to spot misconfigured devices. Raises ``SnmpTimeout`` when no
credential got an answer.
"""
notes = []
for record in credentials:
try:
client = SnmpClient(host, record, timeout, retries, port)
if client.get([check_oid]):
return client, notes
notes.append(f"{client.credential.label}: keine Daten")
except SnmpAuthError as error:
notes.append(str(error))
except SnmpTimeout:
continue
except SnmpError as error:
notes.append(str(error))
if notes:
raise SnmpAuthError("; ".join(notes))
raise SnmpTimeout(f"{host}: keine SNMP-Antwort")
def table(walked, root):
"""Group a walked table by row index: ``{index tuple: {column: value}}``."""
rows = {}
base = len(oid_key(root))
for oid, value in walked.items():
key = oid_key(oid)
if len(key) <= base + 1:
continue
rows.setdefault(key[base + 1:], {})[key[base]] = value
return rows
+64 -13
View File
@@ -1095,6 +1095,14 @@ def _physical_record(record):
and not re.match(r"^(?:vlan|lo|mgmt|oobm)", interface_key(record.name)))
# NetBox does not allow cables on wireless interfaces (Wi-Fi, LTE/5G, Bluetooth …).
_WIRELESS_TYPE = re.compile(r"^(?:ieee802\.1[15]|other-wireless|gsm|cdma|lte|4g|5g)")
def _cableable_record(record):
return _physical_record(record) and not _WIRELESS_TYPE.match(_record_type(record))
def _physical_interface(interface):
return netbox_interface_type(interface) not in ("virtual", "lag")
@@ -1420,7 +1428,15 @@ def plan_switch_sync(nb, config, snapshot):
if remote and remote.id not in known and remote.id != device.id:
devices.append({"id": remote.id, "name": remote.name})
known.add(remote.id)
neighbors.append(dict(neighbor, device_id=device_id, method=method))
interfaces, suggested, chosen = [], None, None
if remote:
interfaces = cable_targets(nb, remote.id, lookup)
found = lookup.interface(remote, neighbor)
suggested = found.name if found else None
stored = (config.get("neighbor_interfaces") or {}).get(local)
chosen = stored if any(item["id"] == stored for item in interfaces) else None
neighbors.append(dict(neighbor, device_id=device_id, method=method, interfaces=interfaces,
suggested_interface=suggested, interface_id=chosen))
# Stack members may be chosen from the same list (including the switch itself).
for member_device in ([device, *filter(None, members.values())] if members else []):
if member_device.id not in known:
@@ -1523,10 +1539,13 @@ class _RemoteLookup:
self.devices[cache_key] = found
return found
def records(self, device_id):
if device_id not in self.interfaces:
self.interfaces[device_id] = _device_interfaces(self.nb, device_id)
return self.interfaces[device_id]
def interface(self, device, neighbor):
if device.id not in self.interfaces:
self.interfaces[device.id] = _device_interfaces(self.nb, device.id)
records = self.interfaces[device.id]
records = self.records(device.id)
candidates = [neighbor.get("remote_port"), neighbor.get("port_description")]
if neighbor.get("port_description"):
candidates.append(neighbor["port_description"].split()[0])
@@ -1538,7 +1557,7 @@ class _RemoteLookup:
number = _port_number(neighbor.get("remote_port"))
if number is not None:
found = [record for record in records.values()
if _physical_record(record) and _port_number(record.name) == number]
if _cableable_record(record) and _port_number(record.name) == number]
if len(found) == 1:
return found[0]
# Access points and phones often report their MAC address as port ID.
@@ -1550,10 +1569,18 @@ class _RemoteLookup:
return found[0]
# An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there.
physical = [record for record in records.values()
if _physical_record(record) and not getattr(record, "mgmt_only", False)]
if _cableable_record(record) and not getattr(record, "mgmt_only", False)]
return physical[0] if len(physical) == 1 else None
def cable_targets(nb, device_id, lookup=None):
"""Interfaces of a device a cable can end on, as ``[{"id", "name", "cabled"}]`` in natural order."""
records = (lookup or _RemoteLookup(nb)).records(device_id)
return [{"id": record.id, "name": record.name, "cabled": bool(getattr(record, "cable", None))}
for record in sorted(records.values(), key=lambda item: _natural_key(item.name))
if _cableable_record(record)]
_NEW = "new" # placeholder ID of objects a dry run would create
@@ -2030,34 +2057,58 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if create_cables:
lookup = _RemoteLookup(nb)
manual_devices = config.get("neighbor_devices") or {}
manual_interfaces = config.get("neighbor_interfaces") or {}
for neighbor in snapshot["neighbors"]:
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
name = neighbor.get("system_name") or neighbor.get("management_ip") or neighbor.get("chassis_id") or "?"
label = f"{neighbor.get('local_port')} → {name} {neighbor.get('remote_port') or ''}".strip()
def skip(reason):
report["cables_skipped"] += 1
report["notes"].append(f"Kabel {device.name} {label} übersprungen: {reason}")
try:
key = interface_key(neighbor["local_port"])
if key not in records:
skip(f"lokaler Port „{neighbor['local_port']}“ gehört zu keiner Schnittstelle")
continue
local = records[key]
if local is None: # interface only created by this (dry) run
if not dry_run:
skip("lokale Schnittstelle wurde nicht angelegt")
continue
existing = getattr(local, "cable", None) if local is not None else None
if neighbor["local_port"] in manual_devices:
# 0 means "no device" was chosen in the review dialog.
chosen = int(manual_devices[neighbor["local_port"]] or 0)
remote_device = nb.dcim.devices.get(chosen) if chosen else None
if not chosen:
report["cables_skipped"] += 1 # deliberately "no cable"
continue
remote_device = nb.dcim.devices.get(chosen)
else:
remote_device = lookup.device(neighbor)
if not remote_device:
report["cables_skipped"] += 1
skip("Nachbargerät nicht in NetBox gefunden – bei Bedarf im Reiter „Nachbarn“ zuordnen")
continue
if remote_device.id in own_devices:
continue
remote = lookup.interface(remote_device, neighbor)
# A far-end interface chosen in the review dialog wins – as long as it belongs to the device.
chosen_interface = manual_interfaces.get(neighbor["local_port"])
remote = next((record for record in lookup.records(remote_device.id).values()
if chosen_interface and record.id == chosen_interface), None)
remote = remote or lookup.interface(remote_device, neighbor)
if existing:
if remote:
_check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report)
else:
report["cables_skipped"] += 1
skip(f"lokaler Port hat bereits ein Kabel, Schnittstelle „{neighbor.get('remote_port')}“ "
f"auf {remote_device.name} nicht gefunden")
continue
if not remote or getattr(remote, "cable", None):
report["cables_skipped"] += 1
if not remote:
skip(f"keine passende Schnittstelle „{neighbor.get('remote_port')}“ auf {remote_device.name} "
"(Name, Portnummer, MAC oder einziger physischer Port)")
continue
if getattr(remote, "cable", None):
skip(f"{remote_device.name} {remote.name} hat bereits ein Kabel")
continue
report["cables_created"] += 1
report["changes"].append(f"Kabel {device.name} {label}")
+1
View File
@@ -217,6 +217,7 @@ def query_client(host, credential=None, use_ssl=False, port=None, timeout=30):
"model": system.get("Model") or "",
"product_name": product.get("Name") or "",
"product_version": product.get("Version") or "",
"uuid": product.get("UUID") or "",
"serial": bios.get("SerialNumber") or "",
"bios_version": bios.get("SMBIOSBIOSVersion") or "",
"chassis": [as_int(value) for value in as_list(enclosure.get("ChassisTypes"))],
+27 -7
View File
@@ -9,13 +9,14 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QFileDialog
from netbox_sync.core import backups, exchange, lancom, netbox
from netbox_sync.core import agent_client, backups, exchange, lancom, netbox
from netbox_sync.core.client_sync import ClientSyncEngine
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.netbox import NetBoxError, related_id, related_name
from netbox_sync.core.switches import (
PLATFORMS,
cable_targets,
describe_snapshot,
discover_switch,
plan_switch_sync,
@@ -525,7 +526,8 @@ class Actions:
# Started after the planning task has finished, so the next
# task is not rejected as "still busy".
if needs_review:
dialog = SwitchMappingDialog(self.window, reviewable, create_cables)
dialog = SwitchMappingDialog(self.window, reviewable, create_cables,
interface_loader=lambda device_id: cable_targets(nb, device_id))
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
@@ -643,9 +645,19 @@ class Actions:
parallel = max(1, int(self.state.settings.get("parallel_wmi", 8)))
mode = options.get("mode", "ad")
hosts = []
if rows is None and mode == "hosts":
agent = mode == "agent"
agent_key = (self.state.profile or {}).get("agent_key", "")
agent_port = int(options.get("agent_port") or agent_client.DEFAULT_PORT)
if agent and not agent_key:
widgets.message(self.window, "Agent-Schlüssel fehlt",
"Bitte zuerst einen Agent-Schlüssel erzeugen und mit der Agent-Konfiguration verteilen.",
"info")
return
if agent:
parallel = max(parallel, 32)
if rows is None and mode in ("hosts", "agent"):
try:
hosts = expand_targets(options.get("hosts", ""))
hosts = expand_targets(options.get("agent_targets" if agent else "hosts", ""))
except ClientScanError as error:
widgets.error(self.window, "Ungültige Eingabe", str(error))
return
@@ -682,11 +694,17 @@ class Actions:
ctx.progress(done[0], len(targets), row["name"])
ctx.progress(0, len(targets), "")
extra = ({"query": lambda host: agent_client.query(host, agent_key, agent_port), "port": agent_port,
"service": "Agent"} if agent else {})
results = scan_clients(targets, credential, bool(options.get("use_ssl")), parallel, log=ctx.log,
on_result=on_result, cancelled=lambda: ctx.cancelled)
on_result=on_result, cancelled=lambda: ctx.cancelled, **extra)
ctx.check_cancelled()
by_host = {row["host"]: row for row in results}
return nb, engine, [by_host.get(row["host"], row) for row in targets]
scanned = [by_host.get(row["host"], row) for row in targets]
if agent and targets_given is None:
# A range scan: only hosts where an agent answered (or rejected us) are of interest.
scanned = [row for row in scanned if row["status"] != "offline"]
return nb, engine, scanned
def success(result):
nb, engine, scanned = result
@@ -792,7 +810,9 @@ class Actions:
self.state.client_engine = engine
self.state.clients_changed.emit()
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")
if report["errors"]:
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning",
+73 -2
View File
@@ -1,15 +1,83 @@
"""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.icons import icon
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")
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):
"""Choose site, role and tenant for the new devices."""
@@ -95,6 +163,9 @@ class ClientPreviewDialog(_Dialog):
(f"{report['interfaces_created']} Schnittstellen", "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"]:
items.append((f"{len(report['errors'])} Probleme", "error"))
for text, kind in items:
+79
View File
@@ -119,6 +119,80 @@ winrm/config/listener</span>.</td></tr>
"""
AGENT_REPO = "https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows"
def _agent_html():
accent = theme.color("accent")
code_bg = theme.color("log_bg")
return f"""
<style>
h2 {{ font-size: 13pt; margin: 14px 0 6px 0; }}
h3 {{ font-size: 10.5pt; margin: 12px 0 4px 0; color: {accent}; }}
p, li {{ line-height: 140%; }}
.path {{ font-family: 'Cascadia Mono', Consolas, monospace; background: {code_bg}; }}
td {{ padding: 3px 10px 3px 0; vertical-align: top; }}
</style>
<h2>NetBox-Agent statt WinRM</h2>
<p>Der <b>NetBox Windows Agent</b> läuft unsichtbar als SYSTEM-Aufgabe auf den Clients und stellt sein
Inventar auf einem TCP-Port (Standard 8731) bereit. Dieser Rechner scannt IP-Bereiche und liest die Agenten
aus – <b>ohne WinRM, ohne Administratorkonto und ohne NetBox-Zugang auf den Clients</b>. Die Abfrage ist mit
dem Agent-Schlüssel signiert, die Antwort mit AES-256 verschlüsselt. Benutzer bemerken nichts: kein Fenster,
keine Firewall-Abfrage.</p>
<h3>1. Schlüssel und Konfiguration</h3>
<ol>
<li>Modus <b>NetBox-Agent (Netzwerk-Scan)</b> wählen und <b>Schlüssel erzeugen</b> (einer pro Kunde,
verschlüsselt im Profil gespeichert).</li>
<li>Optional unter <b>Freigegebene Netze</b> das Admin-Netz eintragen – dann nehmen die Agenten nur von dort
Verbindungen an.</li>
<li><b>Agent-Konfiguration speichern …</b> erzeugt die fertige <span class="path">config.json</span>.</li>
</ol>
<h3>2. Agent herunterladen</h3>
<p>Auf der <a href="{AGENT_REPO}/releases/latest">Release-Seite des Agenten</a> das ZIP-Paket laden –
<span class="path">win-x64</span> für Intel/AMD, <span class="path">win-arm64</span> für ARM-Geräte. Es enthält
<span class="path">agent.exe</span>, <span class="path">install.ps1</span>, <span class="path">uninstall.ps1</span>
und <span class="path">gpo-startup.ps1</span>. Dazu kommt die eben gespeicherte
<span class="path">config.json</span>.</p>
<h3>3a. Verteilung per Intune</h3>
<table>
<tr><td>Paket</td><td>agent.exe, config.json, install.ps1, uninstall.ps1 als Win32-App (.intunewin)</td></tr>
<tr><td>Installation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\install.ps1
-SourceDirectory .</span></td></tr>
<tr><td>Deinstallation</td><td><span class="path">powershell.exe -NoProfile -ExecutionPolicy Bypass -File
.\\uninstall.ps1</span></td></tr>
<tr><td>Verhalten</td><td>System · als <b>Erforderlich</b> einer Gerätegruppe zuweisen</td></tr>
<tr><td>Erkennung</td><td>Datei <span class="path">C:\\Program Files\\NetBox Windows Agent</span> /
<span class="path">agent.exe</span>, Methode „Zeichenfolge (Version)“, „Größer als oder gleich“, z. B. 0.2.0</td></tr>
</table>
<h3>3b. Verteilung per Gruppenrichtlinie</h3>
<ol>
<li>Diese fünf Dateien in eine Freigabe legen, die „Domänencomputer“ lesen dürfen, z. B.
<span class="path">\\\\fileserver\\NetBoxAgent$</span>:
<span class="path">agent.exe</span>, <span class="path">config.json</span>, <span class="path">install.ps1</span>,
<span class="path">uninstall.ps1</span> und <span class="path">gpo-startup.ps1</span>.</li>
<li>GPO für die OU der Clients: <b>Computerkonfiguration › Richtlinien › Windows-Einstellungen › Skripts ›
Starten › PowerShell-Skripts</b> – <span class="path">\\\\fileserver\\NetBoxAgent$\\gpo-startup.ps1</span>
ohne Parameter.</li>
<li><b>Computerkonfiguration › Administrative Vorlagen › System › Anmelden › Beim Neustart des Computers und
bei der Anmeldung immer auf das Netzwerk warten</b> = Aktiviert.</li>
</ol>
<p>Das Skript installiert beim Start nur, wenn sich agent.exe oder config.json auf der Freigabe geändert
haben – neue Versionen oder ein neuer Schlüssel werden so automatisch verteilt.</p>
<h3>4. Scannen</h3>
<p>IP-Bereiche als Ziele eintragen und <b>Abfragen</b>. Es erscheinen nur Rechner, auf denen ein Agent
antwortet; die Übertragung nach NetBox läuft wie beim WinRM-Scan mit Vorschau.</p>
<p>Findet der Scan keinen Agenten: Läuft die Aufgabe „NetBox Windows Agent Listener“? Ist Port 8731
zwischen den Netzen offen (<span class="path">Test-NetConnection PC0815 -Port 8731</span>)? Liegt dieser
Rechner in den freigegebenen Netzen? Die Firewall-Regel gilt für die Profile Domäne und Privat.</p>
"""
class ClientHelpDialog(_Dialog):
def __init__(self, parent, state, tab=0):
super().__init__(parent, "Einrichtungshilfe: Windows-Clients",
@@ -169,6 +243,11 @@ class ClientHelpDialog(_Dialog):
layout.addStretch(1)
self.tabs.addTab(test, "Verbindung testen")
agent = QTextBrowser()
agent.setOpenExternalLinks(True)
agent.setHtml(_agent_html())
self.tabs.addTab(agent, "NetBox-Agent")
self.root.addWidget(self.tabs, 1)
self.root.addWidget(button("Schließen", variant="primary", on_click=self.accept), 0, Qt.AlignRight)
self.tabs.setCurrentIndex(tab)
+57 -9
View File
@@ -619,7 +619,10 @@ class SwitchMappingDialog(_Dialog):
NEW = "\x00new"
def __init__(self, parent, plans, create_cables):
def __init__(self, parent, plans, create_cables, interface_loader=None):
# interface_loader(device_id) → cable targets of another chosen neighbor device.
self.interface_loader = interface_loader
self._far_end_cache = {}
super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
@@ -716,9 +719,9 @@ class SwitchMappingDialog(_Dialog):
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: "
f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
"überspringt den Nachbarn.", muted=True, wrap=True))
self.neighbor_table = QTableWidget(0, 5)
self.neighbor_table = QTableWidget(0, 6)
self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
"Nachbar-Port", "NetBox-Gerät"])
"Nachbar-Port", "NetBox-Gerät", "Nachbar-Schnittstelle"])
for switch, plan in plans:
for neighbor in plan["neighbors"]:
row = self.neighbor_table.rowCount()
@@ -727,14 +730,22 @@ class SwitchMappingDialog(_Dialog):
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
neighbor.get("device_id") or 0)
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or
neighbor.get("management_ip") or "", neighbor.get("remote_port") or "")
neighbor.get("management_ip") or neighbor.get("chassis_id") or "",
neighbor.get("remote_port") or "")
for column, text in enumerate(texts):
self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
self.neighbor_table.setCellWidget(row, 4, combo)
self.neighbor_rows.append((switch, neighbor, combo))
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260))
port_combo = SearchableComboBox("Schnittstelle suchen …")
self._fill_far_ends(port_combo, neighbor.get("interfaces") or [],
neighbor.get("suggested_interface"), neighbor.get("interface_id"))
self.neighbor_table.setCellWidget(row, 5, port_combo)
combo.currentIndexChanged.connect(
lambda _index, device_combo=combo, target=port_combo, item=neighbor:
self._device_changed(device_combo, target, item))
self.neighbor_rows.append((switch, neighbor, combo, port_combo))
self._prepare_table(self.neighbor_table, (130, 95, 200, 140, 220, 220))
neighbor_layout.addWidget(self.neighbor_table, 1)
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
found = sum(1 for _switch, neighbor, *_combos in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks --------------------------------------------------------------
@@ -959,13 +970,43 @@ class SwitchMappingDialog(_Dialog):
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
@staticmethod
def _fill_far_ends(combo, interfaces, suggested=None, current=None, evaluated=True):
""""automatic" (with the interface it would pick) plus the cable targets of the device.
``evaluated`` is False for a device chosen in the dialog: its automatic match is only known at sync time.
"""
automatic = f"automatisch ({suggested})" if suggested else (
"automatisch – keine passende gefunden" if interfaces and evaluated else "automatisch")
items = [(automatic, 0)] + [(item["name"] + (" (hat Kabel)" if item.get("cabled") else ""), item["id"])
for item in interfaces]
combo.set_items(items, current or 0)
combo.setEnabled(bool(interfaces) or bool(suggested))
def _device_changed(self, device_combo, target, neighbor):
device_id = int(device_combo.valid_data() or 0)
if not device_id:
self._fill_far_ends(target, [])
return
if device_id == (neighbor.get("device_id") or 0):
self._fill_far_ends(target, neighbor.get("interfaces") or [], neighbor.get("suggested_interface"),
neighbor.get("interface_id"))
return
if device_id not in self._far_end_cache:
try:
self._far_end_cache[device_id] = self.interface_loader(device_id) if self.interface_loader else []
except Exception: # noqa: BLE001 – the choice stays "automatic"
self._far_end_cache[device_id] = []
self._fill_far_ends(target, self._far_end_cache[device_id], evaluated=False)
def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
def accept(self):
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
"neighbor_devices": dict(switch.get("neighbor_devices") or {}),
"neighbor_interfaces": dict(switch.get("neighbor_interfaces") or {})}
for switch, _plan in self.plans}
# Members moved to another device: their port choices refer to the old
# device and are dropped, so the ports are matched again automatically.
@@ -996,7 +1037,7 @@ class SwitchMappingDialog(_Dialog):
mapping.pop(item["name"], None)
else:
mapping[item["name"]] = target
for switch, neighbor, combo in self.neighbor_rows:
for switch, neighbor, combo, port_combo in self.neighbor_rows:
chosen = combo.valid_data()
chosen = int(chosen or 0)
stored = result[switch["id"]]["neighbor_devices"]
@@ -1004,6 +1045,13 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None)
else:
stored[neighbor["local_port"]] = chosen
# 0 = automatic (name, port number, MAC or single port); otherwise the chosen NetBox interface.
interface_id = int(port_combo.valid_data() or 0) if chosen else 0
interfaces = result[switch["id"]]["neighbor_interfaces"]
if interface_id:
interfaces[neighbor["local_port"]] = interface_id
else:
interfaces.pop(neighbor["local_port"], None)
network_map = dict(self.previous_network_map)
for item, combo, status in self.network_rows:
chosen = combo.currentData()
+2
View File
@@ -30,6 +30,8 @@ _PATHS = {
'<path d="M8.5 16.43a5 5 0 0 1 7 0"/>',
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>'
'<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
"printer": '<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/>'
'<path d="M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6"/><rect x="6" y="14" width="12" height="8" rx="1"/>',
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
"check": '<path d="M20 6 9 17l-5-5"/>',
+4 -1
View File
@@ -29,6 +29,7 @@ from netbox_sync.ui.pages.connections import ConnectionsPage
from netbox_sync.ui.pages.ipam import IpamPage
from netbox_sync.ui.pages.log import LogPage
from netbox_sync.ui.pages.overview import OverviewPage
from netbox_sync.ui.pages.printers import PrintersPage
from netbox_sync.ui.pages.scanner import ScannerPage
from netbox_sync.ui.pages.settings import SettingsPage
from netbox_sync.ui.pages.switches import SwitchesPage
@@ -47,6 +48,7 @@ NAVIGATION = (
("switches", "Switche", "network"),
("clients", "Windows-Clients", "monitor"),
("aps", "Access Points", "wifi"),
("printers", "Drucker", "printer"),
("ipam", "VRFs && Netze", "globe"),
("scanner", "Netzwerk-Scanner", "search"),
("log", "Protokoll", "list"),
@@ -109,6 +111,7 @@ class MainWindow(QMainWindow):
for key, page_class in (("overview", OverviewPage), ("connections", ConnectionsPage), ("vms", VMsPage),
("switches", SwitchesPage), ("clients", ClientsPage), ("aps", AccessPointsPage),
("printers", PrintersPage),
("ipam", IpamPage), ("scanner", ScannerPage),
("log", LogPage),
("settings", SettingsPage)):
@@ -371,7 +374,7 @@ class MainWindow(QMainWindow):
has_profile = self.state.profile is not None
for key in ("duplicate", "rename", "delete"):
self.profile_actions[key].setEnabled(has_profile)
for key in ("connections", "vms", "switches", "clients", "aps", "ipam"):
for key in ("connections", "vms", "switches", "clients", "aps", "printers", "ipam"):
self.nav_buttons[key].setEnabled(has_profile)
self.setWindowTitle(f"{self.state.active} – {APP_NAME}" if has_profile else APP_NAME)
self._refresh_netbox_pill()
+64 -36
View File
@@ -48,9 +48,9 @@ class SiteMappingDialog(_Dialog):
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
and to APs without a Sophos site."""
def __init__(self, parent, rows, sites, tenants):
def __init__(self, parent, rows, sites, tenants, header="Sophos-Standort / Access Point", noun="APs"):
super().__init__(parent, "Standorte & Mandanten zuordnen",
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
f"Der Standort ist optional – {noun} ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. Zeilen ohne "
"Standort und ohne Mandant werden ignoriert.",
width=860)
@@ -59,7 +59,7 @@ class SiteMappingDialog(_Dialog):
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
self.table.setHorizontalHeaderLabels([header, noun, "NetBox-Standort (optional)",
"Mandant *"])
self.rows = []
for text, count, key, current in rows:
@@ -101,6 +101,14 @@ class SiteMappingDialog(_Dialog):
class AccessPointsPage(Page):
title = "Access Points"
# Overridden by pages that reuse this workflow (printers).
settings_key = "access_points"
noun = "Access Points"
source_name = "Sophos"
role_hints = ROLE_HINTS
key_func = staticmethod(ap_key)
mapping_header = "Sophos-Standort / Access Point"
mapping_noun = "APs"
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
"Seriennummer, MAC und Name) und fehlende anlegen.")
@@ -194,7 +202,7 @@ class AccessPointsPage(Page):
# ------------------------------------------------------------------
def _settings(self):
return self.state.profile.setdefault("access_points", {}) if self.state.profile else {}
return self.state.profile.setdefault(self.settings_key, {}) if self.state.profile else {}
def _store(self, **values):
if self.state.profile is None:
@@ -255,9 +263,7 @@ class AccessPointsPage(Page):
def done(roles):
self.roles = roles
settings = self._settings()
role_id = settings.get("role_id") or next(
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
or "access point" in name.casefold()), None)
role_id = settings.get("role_id") or self._suggest_role(roles)
self.role.set_items(roles, role_id)
if then_compare:
QTimer.singleShot(0, self.compare)
@@ -265,6 +271,13 @@ class AccessPointsPage(Page):
self.tasks.run(work, title="Geräterollen laden", area="app", on_success=done,
on_error=self.actions._netbox_failed)
def _suggest_role(self, roles):
return next((role_id for name, role_id in roles if name.casefold() in self.role_hints
or "access point" in name.casefold()), None)
def _make_engine(self, nb, log):
return APSyncEngine(nb, log)
def compare(self):
if not self.aps or self.tasks.busy:
return
@@ -274,10 +287,10 @@ class AccessPointsPage(Page):
for ap in self.aps]
def work(ctx):
engine = APSyncEngine(connect(ctx), ctx.log)
ctx.log("Lade Standorte, Mandanten und vorhandene Sophos-Geräte …")
engine = self._make_engine(connect(ctx), ctx.log)
ctx.log("Lade Standorte, Mandanten und vorhandene Geräte …")
engine.load_context()
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
ctx.log(f"Suche {len(aps)} {self.noun} in NetBox …")
only_netbox = engine.match(aps)
return engine, aps, only_netbox
@@ -287,11 +300,11 @@ class AccessPointsPage(Page):
site["id"]) for site in self.engine.ap_sites],
self._settings().get("default_site"))
found = sum(1 for ap in self.aps if ap.get("device"))
logger("app").log(25, "Abgleich: %s von %s APs in NetBox, %s nur in NetBox", found, len(self.aps),
len(self.only_netbox))
logger("app").log(25, "Abgleich: %s von %s %s in NetBox, %s nur in NetBox", found, len(self.aps),
self.noun, len(self.only_netbox))
self._refresh()
self.tasks.run(work, title="Access Points abgleichen", area="app", on_success=done,
self.tasks.run(work, title=f"{self.noun} abgleichen", area="app", on_success=done,
on_error=self.actions._netbox_failed)
# ------------------------------------------------------------------
@@ -301,7 +314,7 @@ class AccessPointsPage(Page):
def _placement(self, ap):
"""Site (optional) and tenant for a new AP: stored choice, else the suggestion."""
settings = self._settings()
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
stored = (settings.get("ap_sites") or {}).get(self.key_func(ap)) or (settings.get("site_map") or {}).get(
ap["site_hint"])
if stored:
value = placement_value(stored)
@@ -342,8 +355,9 @@ class AccessPointsPage(Page):
tenant_name = self._tenant_name(self._tenant_for(placement))
else:
site_name = ""
state = ("ignored" if self.engine and self._placement(ap)["ignored"] else "new") if not device else ("check" if ap["issues"] else "known")
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
state = "ignored" if self._excluded(ap) else ("ignored" if self.engine and self._placement(ap)["ignored"]
else "new") if not device else ("check" if ap["issues"] else "known")
rows.append(dict(ap, key=self.key_func(ap), state=state if self.engine else "", site_id=site_id,
netbox_site=site_name, tenant=tenant_name or "",
netbox_device=device.name if device else "", method=ap.get("method", "")))
# NetBox APs missing in the export – only for tenants this export is about
@@ -359,11 +373,11 @@ class AccessPointsPage(Page):
or self._site_name(related_id(device, "site")),
"tenant": self._tenant_name(related_id(device, "tenant")),
"netbox_device": device.name, "method": "",
"issues": ["In NetBox, aber nicht im Sophos-Export"]})
"issues": [f"In NetBox, aber nicht im {self.source_name}-Ergebnis"]})
self.model.set_rows(rows)
self.stack.setCurrentIndex(1 if rows else 0)
counts = {key: sum(1 for row in rows if row["state"] == key) for key in STATE_TEXT}
parts = [f"{len(self.aps)} Access Points" + (f" aus {self.file_name}" if self.file_name else "")]
parts = [f"{len(self.aps)} {self.noun}" + (f" aus {self.file_name}" if self.file_name else "")]
if self.engine:
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
f"{counts['netbox_only']} nur in NetBox"]
@@ -389,25 +403,38 @@ class AccessPointsPage(Page):
# Sites and transfer
# ------------------------------------------------------------------
def _new_aps(self):
return [ap for ap in self.aps if not ap.get("device")]
def _excluded(self, ap):
"""Left out deliberately (overridden by the printer page)."""
return False
def map_sites(self):
if not self.engine:
return False
new = self._new_aps()
def _new_aps(self):
return [ap for ap in self.aps if not ap.get("device") and not self._excluded(ap)]
def _prepare_sync(self):
return self.engine
def _mapping_rows(self, new):
"""``(text, count, (kind, key), placement)`` per Sophos site, plus APs without one."""
groups = {}
for ap in new:
if ap["site_hint"]:
groups.setdefault(ap["site_hint"], []).append(ap)
rows = [(hint, len(members), ("site", hint), self._placement(members[0]))
for hint, members in sorted(groups.items(), key=lambda pair: pair[0].casefold())]
rows += [(f"{ap['name']} (ohne Sophos-Standort)", 1, ("ap", ap_key(ap)), self._placement(ap))
rows += [(f"{ap['name']} (ohne {self.source_name}-Standort)", 1, ("ap", self.key_func(ap)),
self._placement(ap))
for ap in new if not ap["site_hint"]]
if not rows:
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
return rows
def map_sites(self):
if not self.engine:
return False
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants)
rows = self._mapping_rows(self._new_aps())
if not rows:
self.window.toast(f"Alle {self.noun} sind bereits in NetBox.", "info")
return False
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
self.mapping_header, self.mapping_noun)
if not dialog.exec():
return False
settings = self._settings()
@@ -424,7 +451,7 @@ class AccessPointsPage(Page):
new = [ap for ap in self._new_aps() if not self._placement(ap)["ignored"]]
role_id = self.role.valid_data()
if new and not role_id:
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
widgets.message(self.window, "Geräterolle fehlt", f"Für neue {self.noun} bitte eine Geräterolle wählen.",
"info")
return
if any(not self._placement(ap)["stored"] for ap in new):
@@ -435,16 +462,17 @@ class AccessPointsPage(Page):
placements = {}
for ap in new:
placement = self._placement(ap)
placements[ap_key(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
homeless = [ap["name"] for ap in new if not placements[ap_key(ap)]["site"]]
placements[self.key_func(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
homeless = [ap["name"] for ap in new if not placements[self.key_func(ap)]["site"]]
if homeless and not default_site:
widgets.message(self.window, "Standard-Standort fehlt",
f"{len(homeless)} neue Access Points haben keinen Standort. NetBox verlangt für jedes "
f"{len(homeless)} neue {self.noun} haben keinen Standort. NetBox verlangt für jedes "
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
"\n".join(homeless))
return
engine, rename = self.engine, self.rename.isChecked()
aps = [ap for ap in self.aps if ap.get("device") or ap_key(ap) in placements]
engine, rename = self._prepare_sync(), self.rename.isChecked()
aps = [ap for ap in self.aps if (ap.get("device") and not self._excluded(ap))
or self.key_func(ap) in placements]
def run(dry_run):
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
@@ -452,14 +480,14 @@ class AccessPointsPage(Page):
def show(report):
def ask():
if ClientPreviewDialog(self.window, report).exec():
self.tasks.run(run(False), title="Access Points übertragen", area="app", on_success=applied,
self.tasks.run(run(False), title=f"{self.noun} übertragen", area="app", on_success=applied,
on_error=self.actions._netbox_failed)
QTimer.singleShot(0, ask)
def applied(report):
for error in report["errors"]:
logger("app").error("%s", error)
text = (f"{report['devices_created']} Access Points angelegt, {report['devices_updated']} aktualisiert"
text = (f"{report['devices_created']} {self.noun} angelegt, {report['devices_updated']} aktualisiert"
+ (f", {len(report['errors'])} Fehler" if report["errors"] else ""))
logger("app").log(25, "%s", text)
self.window.toast(text, "warning" if report["errors"] else "success")
+185 -13
View File
@@ -1,13 +1,18 @@
import ipaddress
import json
import os
import time
from PySide6.QtCore import Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QFileDialog,
QComboBox,
QGridLayout,
QHBoxLayout,
QLineEdit,
QMenu,
QPlainTextEdit,
QRadioButton,
QSpinBox,
@@ -15,14 +20,29 @@ from PySide6.QtWidgets import (
QWidget,
)
from netbox_sync.core import agent_client
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.ui import widgets
from netbox_sync.ui.client_dialogs import ClientSoftwareDialog
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.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Badge, Banner, Card, EmptyState, SearchField, Table, button, checkbox, label
from netbox_sync.ui.widgets import (
Badge,
Banner,
Card,
EmptyState,
PasswordField,
SearchField,
Table,
button,
checkbox,
label,
)
STATUS = {
"ok": ("OK", "success"),
@@ -55,6 +75,9 @@ def _tooltip(row):
("RAM", f"{row['memory'] / 1024 ** 3:.0f} GB" if row.get("memory") else ""),
("Angemeldet", row.get("user")),
("Letzter Start", (row.get("last_boot") or "").replace("T", " ")),
("Quelle", f"NetBox-Agent {row.get('agent_version', '')}".strip() if row.get("source") == "agent" else ""),
("Software", f"{row['software_count']} Programme (laut Agent)" if row.get("software_count") else ""),
("Datenträger", ", ".join(f"{disk['model']} ({disk['size'] / 1e9:.0f} GB)" for disk in row.get("disks") or [])),
("AD", (row.get("ad") or {}).get("dn")),
):
if value:
@@ -87,7 +110,8 @@ class ClientsPage(Page):
mode_row.addWidget(label("Ziele", object_name="CardTitle"))
self.mode_group = QButtonGroup(self)
self.mode_buttons = {}
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche")):
for key, text in (("ad", "Active Directory"), ("hosts", "Hostnamen / IP-Bereiche"),
("agent", "NetBox-Agent (Netzwerk-Scan)")):
radio = QRadioButton(text)
radio.setCursor(Qt.PointingHandCursor)
self.mode_group.addButton(radio)
@@ -136,12 +160,17 @@ class ClientsPage(Page):
"PC0815.firma.local 10.0.10.0/24 10.0.20.10-50")
self.hosts.setFixedHeight(76)
self.mode_stack.addWidget(self.hosts)
self.mode_stack.addWidget(self._build_agent_panel())
# QPlainTextEdit reports a tall size hint even with a fixed height.
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height()))
self.mode_stack.setFixedHeight(max(ad_panel.sizeHint().height(), self.hosts.height(),
self.agent_panel.sizeHint().height()))
targets.add(self.mode_stack)
targets.add(widgets.hline())
self.separator = widgets.hline()
targets.add(self.separator)
logon = QHBoxLayout()
self.logon_widget = QWidget()
logon = QHBoxLayout(self.logon_widget)
logon.setContentsMargins(0, 0, 0, 0)
logon.setSpacing(10)
logon.addWidget(label("Anmeldung", object_name="CardTitle"))
self.account_badge = Badge("", "neutral")
@@ -161,7 +190,7 @@ class ClientsPage(Page):
"verschlüsselt. HTTPS erfordert einen Zertifikats-Listener auf den Clients.")
logon.addWidget(self.current_user)
logon.addWidget(self.use_ssl)
targets.add(logon)
targets.add(self.logon_widget)
self.body.addWidget(targets)
self.help_banner = Banner("Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, "
@@ -210,6 +239,10 @@ class ClientsPage(Page):
Column("chassis", "Bauform", 95),
Column("user", "Angemeldet", 140),
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")),
sort=lambda row: (row.get("ad") or {}).get("last_logon") or 0),
]
@@ -221,6 +254,8 @@ class ClientsPage(Page):
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
card.add(self.table, 1)
footer = QHBoxLayout()
@@ -250,6 +285,10 @@ class ClientsPage(Page):
self.hosts.textChanged.connect(lambda: self._save(hosts=self.hosts.toPlainText()))
self.current_user.toggled.connect(self._current_user_toggled)
self.use_ssl.toggled.connect(lambda value: self._save(use_ssl=value))
self.agent_targets.textChanged.connect(lambda: self._save(agent_targets=self.agent_targets.toPlainText()))
self.agent_port.valueChanged.connect(lambda value: self._save(agent_port=value))
self.agent_networks.editingFinished.connect(
lambda: self._save(agent_networks=self.agent_networks.text().strip()))
self.search.textChanged.connect(self.proxy.set_text)
self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.netbox_filter.currentIndexChanged.connect(self._apply_filters)
@@ -272,7 +311,8 @@ class ClientsPage(Page):
def load_options(self):
options = self.state.client_options
controls = (self.ad_server, self.ad_base, self.only_enabled, self.include_servers, self.max_age, self.hosts,
self.current_user, self.use_ssl, *self.mode_buttons.values())
self.current_user, self.use_ssl, self.agent_targets, self.agent_port, self.agent_networks,
*self.mode_buttons.values())
for widget in controls:
widget.blockSignals(True)
self.ad_server.setText(options.get("ad_server", ""))
@@ -284,17 +324,125 @@ class ClientsPage(Page):
self.hosts.setPlainText(options.get("hosts", ""))
self.current_user.setChecked(bool(options.get("use_current_user")))
self.use_ssl.setChecked(bool(options.get("use_ssl")))
if self.agent_targets.toPlainText() != options.get("agent_targets", ""):
self.agent_targets.setPlainText(options.get("agent_targets", ""))
self.agent_port.setValue(int(options.get("agent_port") or agent_client.DEFAULT_PORT))
self.agent_networks.setText(options.get("agent_networks", ""))
mode = options.get("mode", "ad")
self.mode_buttons.get(mode, self.mode_buttons["ad"]).setChecked(True)
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
for widget in controls:
widget.blockSignals(False)
self._show_mode(mode)
self._update_account()
self._update_agent_key()
def _set_mode(self, mode):
self.mode_stack.setCurrentIndex(0 if mode == "ad" else 1)
self._show_mode(mode)
self._save(mode=mode)
def _show_mode(self, mode):
self.mode_stack.setCurrentIndex({"ad": 0, "hosts": 1, "agent": 2}.get(mode, 0))
agent = mode == "agent"
# The agent needs no Windows logon – its shared key replaces it.
self.logon_widget.setVisible(not agent)
self.separator.setVisible(not agent)
self.help_banner.set(
"Der NetBox-Agent wird per Intune oder GPO verteilt und stellt sein Inventar verschlüsselt bereit – "
"ohne WinRM und ohne NetBox-Zugang auf den Clients. Die Einrichtungshilfe zeigt die Verteilung."
if agent else
"Die Clients müssen einmalig für WinRM vorbereitet werden (Gruppenrichtlinie, Firewall). Die "
"Einrichtungshilfe zeigt alle Schritte.")
# ------------------------------------------------------------------
# NetBox Windows Agent
# ------------------------------------------------------------------
def _build_agent_panel(self):
self.agent_panel = QWidget()
grid = QGridLayout(self.agent_panel)
grid.setContentsMargins(0, 0, 0, 0)
grid.setHorizontalSpacing(12)
grid.setVerticalSpacing(8)
self.agent_targets = QPlainTextEdit()
self.agent_targets.setPlaceholderText("IP-Bereiche oder Hostnamen, z. B. 10.0.10.0/24, 10.0.20.10-50")
self.agent_targets.setFixedHeight(52)
grid.addWidget(label("Ziele"), 0, 0)
grid.addWidget(self.agent_targets, 0, 1, 1, 5)
self.agent_key = PasswordField("noch kein Schlüssel")
self.agent_key.setReadOnly(True)
grid.addWidget(label("Agent-Schlüssel"), 1, 0)
grid.addWidget(self.agent_key, 1, 1)
self.agent_key_new = button("Neu erzeugen", "refresh", on_click=self.new_agent_key,
tooltip="Neuen Schlüssel für die Agenten dieses Kunden erzeugen")
self.agent_key_copy = button("Kopieren", "copy", variant="ghost", on_click=self.copy_agent_key)
self.agent_config = button("Agent-Konfiguration speichern …", "download", on_click=self.save_agent_config,
tooltip="config.json für die Verteilung per Intune oder GPO erzeugen")
grid.addWidget(self.agent_key_new, 1, 2)
grid.addWidget(self.agent_key_copy, 1, 3)
grid.addWidget(self.agent_config, 1, 4, 1, 2)
self.agent_port = QSpinBox()
self.agent_port.setRange(1, 65535)
self.agent_port.setFixedWidth(100)
self.agent_networks = QLineEdit()
self.agent_networks.setPlaceholderText("leer = jede Adresse, z. B. 10.0.0.0/24 (Netz dieses Rechners)")
grid.addWidget(label("Port"), 2, 0)
grid.addWidget(self.agent_port, 2, 1, Qt.AlignLeft)
grid.addWidget(label("Freigegebene Netze"), 2, 2)
grid.addWidget(self.agent_networks, 2, 3, 1, 3)
grid.setColumnStretch(1, 1)
grid.setColumnStretch(3, 1)
return self.agent_panel
def _update_agent_key(self):
key = (self.state.profile or {}).get("agent_key", "")
self.agent_key.setText(key)
self.agent_key_copy.setEnabled(bool(key))
self.agent_config.setEnabled(bool(key))
self.agent_key_new.setText("Neu erzeugen" if key else "Schlüssel erzeugen")
def new_agent_key(self):
if self.state.profile is None:
return
if self.state.profile.get("agent_key") and not widgets.confirm(
self.window, "Neuen Schlüssel erzeugen?",
"Bereits verteilte Agenten lassen sich danach erst wieder abfragen, wenn sie die neue "
"Konfiguration erhalten haben.", "Neu erzeugen", destructive=True):
return
self.state.edit_profile(agent_key=agent_client.new_scan_key())
self._update_agent_key()
self.window.toast("Neuer Agent-Schlüssel erzeugt – Konfiguration neu verteilen.", "info")
def copy_agent_key(self):
QGuiApplication.clipboard().setText(self.agent_key.text())
self.window.toast("Agent-Schlüssel kopiert.", "info")
def save_agent_config(self):
key = (self.state.profile or {}).get("agent_key", "")
if not key:
return
networks = [part.strip() for part in self.agent_networks.text().replace(";", ",").split(",") if part.strip()]
for network in networks:
try:
ipaddress.ip_network(network, strict=False)
except ValueError:
widgets.message(self.window, "Freigegebene Netze prüfen",
f"„{network}“ ist kein Netz in CIDR-Schreibweise (z. B. 10.0.0.0/24).", "warning")
return
path, _filter = QFileDialog.getSaveFileName(self.window, "Agent-Konfiguration speichern", "config.json",
"JSON (*.json)")
if not path:
return
data = agent_client.agent_config(key, self.agent_port.value(),
[str(ipaddress.ip_network(n, strict=False)) for n in networks])
try:
with open(path, "w", encoding="utf-8") as stream:
json.dump(data, stream, indent=2)
except OSError as error:
widgets.error(self.window, "Speichern fehlgeschlagen", str(error))
return
self.window.toast("config.json gespeichert – zusammen mit agent.exe per Intune oder GPO verteilen.",
"success")
def _current_user_toggled(self, value):
self._save(use_current_user=value)
self._update_account()
@@ -368,8 +516,28 @@ class ClientsPage(Page):
def _toggle(self, 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)
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):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
@@ -416,12 +584,14 @@ class ClientsPage(Page):
return
self.ad_server.editingFinished.emit()
self.ad_base.editingFinished.emit()
if self._ensure_logon():
if self.state.client_options.get("mode") == "agent":
self.actions.scan_clients()
elif self._ensure_logon():
self.actions.scan_clients()
def rescan(self):
rows = self.model.checked_rows()
if rows and self._ensure_logon():
if rows and (self.state.client_options.get("mode") == "agent" or self._ensure_logon()):
self.actions.scan_clients(rows)
def load_file(self):
@@ -436,5 +606,7 @@ class ClientsPage(Page):
else:
self.actions.sync_clients(rows)
def show_help(self, tab=0):
ClientHelpDialog(self.window, self.state, tab if isinstance(tab, int) else 0).exec()
def show_help(self, tab=None):
if tab is None or isinstance(tab, bool): # button signals pass "checked"
tab = 3 if self.state.client_options.get("mode") == "agent" else 0
ClientHelpDialog(self.window, self.state, tab).exec()
+698
View File
@@ -0,0 +1,698 @@
"""Printers: SNMP network scan, comparison with NetBox and transfer (reuses the access point workflow)."""
import uuid
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (
QComboBox,
QFormLayout,
QHBoxLayout,
QLineEdit,
QMenu,
QStackedWidget,
QTableWidget,
QTableWidgetItem,
)
from netbox_sync.core import netscan, printers, snmp
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import _Dialog
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.pages.access_points import STATE_DOT, STATE_TEXT, AccessPointsPage
from netbox_sync.ui.tasks import logger
from netbox_sync.ui.widgets import (
Card,
EmptyState,
PasswordField,
SearchableComboBox,
SearchField,
Table,
button,
checkbox,
form_dialog_buttons,
label,
)
MODEL_ACTIONS = (("create", "Gerätetyp neu anlegen"), ("map", "Vorhandenen Gerätetyp verwenden"),
("skip", "Diesmal überspringen"), ("ignore", "Dauerhaft ignorieren"))
AUTH_CHOICES = ["", *snmp.AUTH_PROTOCOLS]
PRIV_CHOICES = ["", *snmp.PRIV_PROTOCOLS]
def _supplies_short(row):
parts = []
for item in row.get("supplies") or []:
if item["percent"] is None:
continue
name = item.get("colour") or item.get("type") or item["name"]
parts.append(f"{name} {item['percent']} %")
return " · ".join(parts)
def _supplies_low(row):
return any(item["percent"] is not None and item["percent"] <= 10 for item in row.get("supplies") or [])
def _supplies_tooltip(row):
lines = [printers.supplies_text(row.get("supplies") or [])]
trays = row.get("trays") or []
if trays:
lines.append("\nPapierfächer:")
lines += [f"{tray['name']}: {tray['level'] or '–'}" + (f" ({tray['media']})" if tray["media"] else "")
for tray in trays]
return "\n".join(line for line in lines if line)
def _status(row):
return ", ".join(filter(None, [row.get("status", ""), *(row.get("errors") or [])]))
def _status_tooltip(row):
lines = []
if row.get("display"):
lines.append("Display: " + " | ".join(row["display"]))
if row.get("alerts"):
lines += ["Meldungen:"] + [f"• {alert}" for alert in row["alerts"]]
if row.get("sys_descr"):
lines.append(f"\n{row['sys_descr']}")
return "\n".join(lines)
class SnmpCredentialsDialog(_Dialog):
"""SNMPv2c communities and SNMPv3 users of a profile, tried in this order."""
COLUMNS = ("Version", "Community", "Benutzer (v3)", "Auth", "Auth-Passwort", "Privacy", "Privacy-Passwort")
def __init__(self, parent, credentials):
super().__init__(parent, "SNMP-Zugangsdaten",
"Jede Adresse wird mit diesen Zugangsdaten in dieser Reihenfolge abgefragt – erst die "
"funktionierenden des letzten Scans. SNMPv2c-Communities und SNMPv3-Benutzer lassen sich "
"mischen. Passwörter werden mit Windows DPAPI verschlüsselt im Profil gespeichert.",
width=980)
self.resize(1080, 460)
self.table = QTableWidget(0, len(self.COLUMNS))
self.table.setHorizontalHeaderLabels(self.COLUMNS)
self.table.verticalHeader().hide()
self.table.verticalHeader().setDefaultSectionSize(42)
self.table.setSelectionBehavior(QTableWidget.SelectRows)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
for column, width in enumerate((80, 160, 150, 100, 170, 100, 170)):
self.table.setColumnWidth(column, width)
self.table.horizontalHeader().setStretchLastSection(True)
self.rows = []
for record in credentials:
self._add(record)
actions = QHBoxLayout()
actions.addWidget(button("SNMPv2c-Community", "plus", on_click=lambda: self._add({"version": "2c"})))
actions.addWidget(button("SNMPv3-Benutzer", "plus", on_click=lambda: self._add(
{"version": "3", "auth_protocol": "SHA", "priv_protocol": "AES"})))
actions.addWidget(button("Entfernen", "trash", on_click=self._remove))
actions.addStretch(1)
self.root.addWidget(self.table, 1)
self.root.addLayout(actions)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
self.root.addWidget(buttons)
self.result = []
def _add(self, record):
row = self.table.rowCount()
self.table.insertRow(row)
version = QComboBox()
version.addItems(["2c", "3"])
version.setCurrentText(str(record.get("version") or "2c"))
community = PasswordField("public")
community.setText(record.get("community", "public" if not self.rows else ""))
username = QLineEdit(record.get("username", ""))
auth = QComboBox()
auth.addItems(AUTH_CHOICES)
auth.setCurrentText(record.get("auth_protocol", ""))
auth_password = PasswordField()
auth_password.setText(record.get("auth_password", ""))
priv = QComboBox()
priv.addItems(PRIV_CHOICES)
priv.setCurrentText(record.get("priv_protocol", ""))
priv_password = PasswordField()
priv_password.setText(record.get("priv_password", ""))
cells = (version, community, username, auth, auth_password, priv, priv_password)
for column, widget in enumerate(cells):
self.table.setCellWidget(row, column, widget)
entry = {"id": record.get("id") or uuid.uuid4().hex[:8], "cells": cells}
self.rows.append(entry)
def update(*_args):
v3 = version.currentText() == "3"
community.setEnabled(not v3)
for widget in (username, auth, priv):
widget.setEnabled(v3)
auth_password.setEnabled(v3 and bool(auth.currentText()))
priv_password.setEnabled(v3 and bool(priv.currentText()))
for widget in (version, auth, priv):
widget.currentIndexChanged.connect(update)
update()
def _remove(self):
row = self.table.currentRow()
if row < 0:
return
self.table.removeRow(row)
del self.rows[row]
def accept(self):
result = []
for number, entry in enumerate(self.rows, 1):
version, community, username, auth, auth_password, priv, priv_password = entry["cells"]
if version.currentText() == "3":
record = {"id": entry["id"], "version": "3", "username": username.text().strip(),
"auth_protocol": auth.currentText(), "auth_password": auth_password.text(),
"priv_protocol": priv.currentText(), "priv_password": priv_password.text()}
problem = ("Benutzername fehlt" if not record["username"] else
"Privacy braucht Authentifizierung" if record["priv_protocol"] and not record["auth_protocol"]
else "Auth-Passwort mit mindestens 8 Zeichen nötig"
if record["auth_protocol"] and len(record["auth_password"]) < 8
else "Privacy-Passwort mit mindestens 8 Zeichen nötig"
if record["priv_protocol"] and len(record["priv_password"]) < 8 else "")
if not record["auth_protocol"]:
record["auth_password"] = ""
if not record["priv_protocol"]:
record["priv_password"] = ""
else:
record = {"id": entry["id"], "version": "2c", "community": community.text()}
problem = "Community fehlt" if not record["community"] else ""
if problem:
self.show_error(f"Zeile {number}: {problem}.")
return
result.append(record)
if not result:
self.show_error("Bitte mindestens eine Community oder einen SNMPv3-Benutzer anlegen.")
return
self.result = result
super().accept()
class ModelMappingDialog(_Dialog):
"""Decide per printer model that is missing in NetBox: create, map to an existing type, skip or ignore."""
def __init__(self, parent, rows, device_types):
super().__init__(parent, "Modelle zuordnen",
"Diese Modelle gibt es in NetBox noch nicht als Gerätetyp. Pro Modell: neu anlegen, einen "
"vorhandenen Gerätetyp verwenden, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
"ignorieren (gespeichert im Profil).", width=900)
self.resize(1040, 520)
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Hersteller / Modell (SNMP)", "Drucker", "Aktion", "Gerätetyp in NetBox"])
self.rows = []
for text, count, key, decision, suggestion in rows:
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(text))
self.table.setItem(row, 1, QTableWidgetItem(str(count)))
action = QComboBox()
for value, caption in MODEL_ACTIONS:
action.addItem(caption, value)
device_type = SearchableComboBox("Gerätetyp suchen …")
device_type.set_items(type_items, decision.get("device_type") or suggestion)
chosen = decision.get("action") or ("map" if suggestion else "create")
action.setCurrentIndex(next(index for index, (value, _c) in enumerate(MODEL_ACTIONS) if value == chosen))
action.currentIndexChanged.connect(lambda _i, a=action, d=device_type: d.setEnabled(a.currentData() == "map"))
device_type.setEnabled(chosen == "map")
self.table.setCellWidget(row, 2, action)
self.table.setCellWidget(row, 3, device_type)
self.rows.append((key, text, action, device_type))
self.table.verticalHeader().hide()
self.table.verticalHeader().setDefaultSectionSize(42)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
self.table.setSelectionMode(QTableWidget.NoSelection)
self.table.horizontalHeader().setStretchLastSection(True)
for column, width in enumerate((330, 60, 250, 300)):
self.table.setColumnWidth(column, width)
self.root.addWidget(self.table, 1)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
self.root.addWidget(buttons)
self.result = {}
def accept(self):
result = {}
for key, text, action, device_type in self.rows:
value = action.currentData()
if value == "map" and device_type.valid_data() is None:
self.show_error(f"Bitte für „{text}“ einen vorhandenen Gerätetyp wählen.")
return
result[key] = {"action": value, "device_type": device_type.valid_data() if value == "map" else None}
self.result = result
super().accept()
class PrintersPage(AccessPointsPage):
title = "Drucker"
subtitle = ("Drucker per SNMP (v2c und v3) im Netzwerk finden – herstellerübergreifend über die Printer-MIB – "
"mit NetBox abgleichen und mit Seitenzähler und Verbrauchsmaterial dokumentieren.")
settings_key = "printers"
noun = "Drucker"
source_name = "Scan"
role_hints = printers.ROLE_HINTS
key_func = staticmethod(printers.printer_key)
mapping_header = "Drucker (IP, Modell, SNMP-Standort)"
mapping_noun = "Drucker"
def __init__(self, window): # noqa: PLR0915 - builds the page
Page.__init__(self, window)
self.aps = []
self.only_netbox = []
self.engine = None
self.roles = []
self.file_name = ""
self.scan_task = None
self.others = []
self._engine_args = {}
self._compare_after_scan = False
self._skipped = set() # printer keys left out for this session
self._skipped_models = set() # model keys left out for this session
source = Card("Scan", "Erreichbare Adressen werden per SNMP abgefragt; Geräte nur mit offenem Druckerport "
"(9100/IPP/LPD) erscheinen als „ohne SNMP“.")
self.credentials_button = source.add_action(button("SNMP-Zugangsdaten …", "shield",
on_click=self.edit_credentials))
self.load_button = source.add_action(button("Scannen", "play", "primary", on_click=self.scan))
self.sync_button = source.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync))
form = QFormLayout()
form.setHorizontalSpacing(18)
targets = QHBoxLayout()
self.targets = QLineEdit()
self.targets.setPlaceholderText("z. B. 192.168.1.1-254, 10.0.0.0/24")
targets.addWidget(self.targets, 1)
self.own_network = button("Eigenes Netz", "network", tooltip="Netze dieses Rechners übernehmen",
on_click=self._own_network_menu)
targets.addWidget(self.own_network)
form.addRow("IP-Bereiche", targets)
self.credentials_label = label("", muted=True)
form.addRow("SNMP", self.credentials_label)
self.role = SearchableComboBox("Geräterolle wählen …")
self.role.setMinimumWidth(320)
form.addRow("Geräterolle", self.role)
site_row = QHBoxLayout()
self.default_site = SearchableComboBox("Standort wählen …")
self.default_site.setMinimumWidth(320)
site_row.addWidget(self.default_site)
site_row.addWidget(label("Für neue Drucker ohne zugeordneten Standort – NetBox verlangt für jedes Gerät "
"einen.", muted=True), 1)
form.addRow("Standard-Standort", site_row)
options = QHBoxLayout()
self.counters = checkbox("Seitenzähler && Verbrauchsmaterial in NetBox speichern", True,
tooltip="Benutzerdefinierte Felder am Gerät (werden bei Bedarf angelegt): "
"Seitenzähler, Verbrauchsmaterial, Farbdrucker, letzter Scan")
self.rename = checkbox("Namen vorhandener Geräte aus SNMP übernehmen", False,
tooltip="sysName des Druckers – oft ein Werksname wie NPI1A2B3C")
options.addWidget(self.counters)
options.addWidget(self.rename)
options.addStretch(1)
form.addRow("", options)
source.add(form)
self.body.addWidget(source)
result = Card("Abgleich")
self.models_button = result.add_action(button("Modelle …", "server", on_click=self.edit_models))
self.sites_button = result.add_action(button("Standorte && Mandanten …", "globe", on_click=self.map_sites))
self.refresh_button = result.add_action(button("Neu abgleichen", "refresh", on_click=self.compare))
filters = QHBoxLayout()
self.search = SearchField("Name, Modell, S/N, MAC, IP, Standort …")
self.only_open = checkbox("Nur neue und zu prüfende")
filters.addWidget(self.search, 2)
filters.addWidget(self.only_open)
filters.addStretch(1)
result.add(filters)
columns = [
Column("state", "Status", 110, value=lambda row: STATE_TEXT.get(row["state"], ""),
dot=lambda row: "warning" if row.get("issues") and row["state"] == "new"
else STATE_DOT.get(row["state"]), tooltip=lambda row: "\n".join(row.get("issues", []))),
Column("name", "Name", 190),
Column("ip", "IP-Adresse", 110),
Column("manufacturer", "Hersteller", 100),
Column("model", "Modell", 190),
Column("serial", "Seriennummer", 130),
Column("mac", "MAC-Adresse", 135),
Column("page_count", "Seiten", 80,
value=lambda row: f"{row['page_count']:,}".replace(",", ".") if row.get("page_count") is not None
else "", sort=lambda row: row.get("page_count") or 0),
Column("supplies", "Verbrauchsmaterial", 220, value=_supplies_short, tooltip=_supplies_tooltip,
color=lambda row: "warning" if _supplies_low(row) else None),
Column("printer_status", "Zustand", 150, value=_status, tooltip=_status_tooltip,
color=lambda row: "warning" if row.get("errors") else "text_muted"),
Column("site_hint", "Standort (SNMP)", 150),
Column("netbox_site", "NetBox-Standort", 180,
color=lambda row: "warning" if row["state"] == "new" and not row.get("site_id")
else ("text_muted" if str(row.get("netbox_site", "")).startswith("Standard:") else None)),
Column("tenant", "Mandant", 140),
Column("netbox_device", "NetBox-Gerät", 160),
Column("method", "Gefunden über", 110, color=lambda row: "text_muted"),
Column("snmp", "SNMP", 150, value=lambda row: row.get("snmp") or ("ohne SNMP" if row.get("ip") else ""),
color=lambda row: "text_muted" if row.get("snmp") else "warning"),
Column("issues", "Hinweise", 260, value=lambda row: "; ".join(row.get("issues", [])),
color=lambda row: "warning"),
]
self.model = RowTableModel(columns, row_id=lambda row: row["key"])
self.proxy = FilterProxy(self.model)
self.table = Table()
self.table.setModel(self.proxy)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
self.stack = QStackedWidget()
self.stack.addWidget(EmptyState("search", "Noch nicht gescannt",
"IP-Bereiche eintragen, SNMP-Zugangsdaten prüfen und „Scannen“ wählen. "
"Danach wird automatisch mit NetBox abgeglichen – geschrieben wird erst nach "
"der Vorschau."))
self.stack.addWidget(self.table)
result.add(self.stack, 1)
self.summary = label("", muted=True)
result.add(self.summary)
self.body.addWidget(result, 1)
self.search.textChanged.connect(self.proxy.set_text)
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
self.role.activated.connect(self._role_changed)
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
self._refresh()))
self.rename.toggled.connect(lambda value: self._store(rename=value))
self.counters.toggled.connect(lambda value: self._store(counters=value))
self.targets.editingFinished.connect(lambda: self._store(targets=self.targets.text().strip()))
self.targets.returnPressed.connect(self.scan)
self.state.profile_switched.connect(self._profile_switched)
self._profile_switched()
# ------------------------------------------------------------------
# Profile settings
# ------------------------------------------------------------------
def _credentials(self):
if not self.state.profile:
return []
return self.state.profile.setdefault("snmp_credentials", [])
def _profile_switched(self):
self.aps, self.only_netbox, self.engine, self.roles, self.others = [], [], None, [], []
self._skipped, self._skipped_models = set(), set()
self.role.set_items([])
self.default_site.set_items([])
settings = self._settings()
for box, key, default in ((self.rename, "rename", False), (self.counters, "counters", True)):
box.blockSignals(True)
box.setChecked(settings.get(key, default))
box.blockSignals(False)
self.targets.setText(settings.get("targets", ""))
self._update_credentials_label()
self._refresh()
def _update_credentials_label(self):
credentials = self._credentials()
if not credentials:
self.credentials_label.setText("Keine Zugangsdaten – es wird die Community „public“ (v2c) versucht.")
return
v2 = sum(1 for item in credentials if item.get("version") != "3")
v3 = [item.get("username", "") for item in credentials if item.get("version") == "3"]
parts = [f"{v2} SNMPv2c-Communit{'y' if v2 == 1 else 'ies'}"] if v2 else []
if v3:
parts.append("SNMPv3: " + ", ".join(v3))
self.credentials_label.setText(" · ".join(parts))
def edit_credentials(self):
if self.state.profile is None:
return
dialog = SnmpCredentialsDialog(self.window, self._credentials())
if dialog.exec():
self.state.profile["snmp_credentials"] = dialog.result
self.state.touch()
self._update_credentials_label()
def on_show(self):
if not self.targets.text().strip():
networks = netscan.local_networks()
if networks:
self.targets.setText(networks[0])
super().on_show()
def _own_network_menu(self):
networks = netscan.local_networks()
if not networks:
self.window.toast("Kein eigenes IPv4-Netz gefunden.", "info")
return
menu = QMenu(self)
for network in networks:
menu.addAction(network, lambda n=network: self.targets.setText(n))
if len(networks) > 1:
menu.addSeparator()
menu.addAction("Alle", lambda: self.targets.setText(", ".join(networks)))
menu.exec(self.own_network.mapToGlobal(self.own_network.rect().bottomLeft()))
def set_busy(self, busy):
scanning = busy and self.scan_task is not None and self.tasks.current is self.scan_task
self.load_button.setText("Stopp" if scanning else "Scannen")
widgets.set_enabled(self.load_button, scanning or not busy, "Bitte warten …")
for widget in (self.sites_button, self.refresh_button, self.credentials_button):
widget.setEnabled(not busy)
self._update_buttons()
def _update_buttons(self):
super()._update_buttons()
widgets.set_enabled(self.models_button, bool(self.engine) and not self.tasks.busy, "Erst mit NetBox abgleichen.")
widgets.set_enabled(self.refresh_button, bool(self.aps) and not self.tasks.busy, "Erst scannen.")
widgets.set_enabled(self.sync_button, bool(self.engine) and not self.tasks.busy,
"Erst scannen." if not self.engine else "Bitte warten …")
# ------------------------------------------------------------------
# Scan
# ------------------------------------------------------------------
def scan(self):
if self.scan_task is not None and self.tasks.current is self.scan_task:
self.tasks.cancel()
return
if self.tasks.busy or self.state.profile is None:
return
try:
ips = netscan.expand_ips(self.targets.text())
except netscan.ScanError as error:
widgets.message(self.window, "Eingabe prüfen", str(error), "warning")
return
self._store(targets=self.targets.text().strip())
credentials = [dict(item) for item in self._credentials()] or [{"id": "public", "version": "2c",
"community": "public"}]
preferred = dict(self._settings().get("snmp_hosts") or {})
def work(ctx):
ctx.log(f"Scanne {len(ips)} Adressen per SNMP ({len(credentials)} Zugangsdaten) …")
found, done = [], [0]
def on_result(host):
done[0] += 1
ctx.progress(done[0], len(ips), host["ip"])
if host.get("alive"):
found.append(host)
printers.scan(ips, credentials, on_result, lambda: ctx.cancelled, preferred)
ctx.check_cancelled()
return found
def finished(hosts):
items = [printers.to_import(host) for host in hosts if host.get("printer")]
printers.mark_duplicates(items)
self.others = [host for host in hosts if not host.get("printer") and host.get("notes")]
remembered = dict(self._settings().get("snmp_hosts") or {})
remembered.update({host["ip"]: host["credential_id"] for host in hosts if host.get("credential_id")})
self._store(snmp_hosts=remembered)
for host in self.others:
logger("app").warning("%s: %s", host["ip"], "; ".join(host["notes"]))
self.aps, self.only_netbox, self.engine = items, [], None
self.file_name = ""
without = sum(1 for item in items if not item.get("snmp"))
text = f"{len(items)} Drucker gefunden" + (f", {without} ohne SNMP" if without else "") + (
f", {len(self.others)} Gerät{'e' if len(self.others) != 1 else ''} mit SNMP-Problemen (siehe Protokoll)" if self.others else "")
logger("app").log(25, "Drucker-Scan: %s", text)
self.window.toast(text, "warning" if self.others or without else "success")
self._refresh()
# The scan task is still current here; the comparison starts once it has ended.
self._compare_after_scan = self._netbox_ready() and bool(items)
self.scan_task = self.tasks.run(work, title=f"{len(ips)} Adressen nach Druckern scannen", area="app",
on_success=finished, on_error=lambda error: widgets.error(
self.window, "Scan fehlgeschlagen", str(error)),
on_finished=self._scan_ended)
self.set_busy(True)
def _scan_ended(self):
self.scan_task = None
self.set_busy(self.tasks.busy)
if self._compare_after_scan:
self._compare_after_scan = False
self._load_lists(then_compare=True)
# ------------------------------------------------------------------
# NetBox
# ------------------------------------------------------------------
def _mapping_rows(self, new):
"""One row per printer – preset with the choice for its SNMP location, if any."""
return [(" · ".join(filter(None, (printer["name"], printer["ip"], printer.get("model"))))
+ (f" (SNMP-Standort: {printer['site_hint']})" if printer["site_hint"] else ""), 1,
("ap", self.key_func(printer)), self._placement(printer))
for printer in sorted(new, key=lambda item: tuple(int(part) for part in item["ip"].split(".")))]
def _suggest_role(self, roles):
return next((role_id for name, role_id in roles
if any(hint in name.casefold() for hint in self.role_hints)), None)
def _role_changed(self, _index):
self._store(role_id=self.role.valid_data())
if self.engine and not self.tasks.busy:
QTimer.singleShot(0, self.compare) # "only in NetBox" depends on the role
def compare(self):
self._engine_args = {"role_id": self.role.valid_data() or self._settings().get("role_id"),
"counters": self.counters.isChecked()}
super().compare()
def _make_engine(self, nb, log):
return printers.PrinterSyncEngine(nb, log, **self._engine_args)
def _prepare_sync(self):
self.engine.counters = self.counters.isChecked()
self.engine.type_map = {key: value["device_type"] for key, value in self._model_decisions().items()
if value.get("action") == "map" and value.get("device_type")}
return self.engine
# ------------------------------------------------------------------
# Ignoring printers and models
# ------------------------------------------------------------------
def _ignored(self):
return set(self._settings().get("ignored") or [])
def _model_decisions(self):
return dict(self._settings().get("models") or {})
def _model_action(self, printer):
key = printers.model_key(printer)
if key in self._skipped_models:
return "skip"
return self._model_decisions().get(key, {}).get("action")
def _excluded(self, printer):
key = self.key_func(printer)
if key in self._skipped or key in self._ignored():
return True
# a skipped or ignored model only matters for printers that would be created
return not printer.get("device") and self._model_action(printer) in ("skip", "ignore")
def _missing_models(self):
"""``{model key: [printers]}`` of new printers whose device type is not in NetBox."""
if not self.engine:
return {}
missing = {}
for printer in self.aps:
if printer.get("device") or self.key_func(printer) in self._skipped | self._ignored():
continue
if not self.engine.type_exists(printer):
missing.setdefault(printers.model_key(printer), []).append(printer)
return missing
def edit_models(self):
missing = self._missing_models()
if not missing:
self.window.toast("Alle Modelle der neuen Drucker gibt es bereits in NetBox.", "info")
return True
decisions = self._model_decisions()
rows = []
for key, members in sorted(missing.items()):
first = members[0]
decision = dict(decisions.get(key) or {})
if key in self._skipped_models:
decision["action"] = "skip"
text = f"{first.get('manufacturer') or 'Unbekannt'} · {first.get('model') or '(kein Modell – nur Ports)'}"
rows.append((text, len(members), key, decision, self.engine.suggest_type(first)))
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types)
if not dialog.exec():
return False
for key, value in dialog.result.items():
if value["action"] == "skip":
self._skipped_models.add(key)
decisions.pop(key, None)
else:
self._skipped_models.discard(key)
decisions[key] = value
self._store(models=decisions)
self._refresh()
return True
def _set_ignored(self, rows, mode):
keys = {row["key"] for row in rows if not str(row["key"]).startswith("netbox-")}
ignored = self._ignored()
if mode == "skip":
self._skipped |= keys
elif mode == "ignore":
ignored |= keys
self._skipped -= keys
else:
ignored -= keys
self._skipped -= keys
# also release the model of these printers
models = {printers.model_key(row) for row in rows}
self._skipped_models -= models
decisions = self._model_decisions()
for key in models:
if decisions.get(key, {}).get("action") == "ignore":
decisions.pop(key)
self._store(models=decisions)
self._store(ignored=sorted(ignored))
self._refresh()
def _context_menu(self, position):
rows = [self.proxy.row_at(index) for index in self.table.selectionModel().selectedRows()]
rows = [row for row in rows if row and not str(row["key"]).startswith("netbox-")]
if not rows:
return
count = f" ({len(rows)})" if len(rows) > 1 else ""
menu = QMenu(self)
menu.addAction(f"Diesmal ignorieren{count}", lambda: self._set_ignored(rows, "skip"))
menu.addAction(f"Dauerhaft ignorieren{count}", lambda: self._set_ignored(rows, "ignore"))
if any(row["state"] == "ignored" for row in rows):
menu.addAction(f"Nicht mehr ignorieren{count}", lambda: self._set_ignored(rows, "release"))
if self.engine and any(not row.get("device") for row in rows):
menu.addSeparator()
menu.addAction("Modell zuordnen …", self.edit_models)
menu.exec(self.table.viewport().mapToGlobal(position))
def sync(self):
if not self.engine or self.tasks.busy:
return
undecided = [key for key in self._missing_models()
if key not in self._skipped_models and key not in self._model_decisions()]
if undecided and not self.edit_models():
return
super().sync()
def _refresh(self):
if self.engine:
decisions = self._model_decisions()
for printer in self.aps:
printer["issues"] = [issue for issue in printer.get("issues", [])
if not issue.startswith("Modell nicht in NetBox")]
if printer.get("device") or self._excluded(printer) or self.engine.type_exists(printer):
continue
decision = decisions.get(printers.model_key(printer), {})
if decision.get("action") == "map":
name = next((f"{row['manufacturer']} {row['model']}" for row in self.engine.device_types
if row["id"] == decision.get("device_type")), "?")
printer["issues"].append(f"Modell nicht in NetBox – wird als „{name}“ angelegt")
elif decision.get("action") == "create":
printer["issues"].append("Modell nicht in NetBox – Gerätetyp wird neu angelegt")
else:
printer["issues"].append("Modell nicht in NetBox – bitte unter „Modelle …“ entscheiden")
super()._refresh()
if self.others and self.summary.text():
count = len(self.others)
self.summary.setText(self.summary.text() + f" · {count} Gerät{'e' if count != 1 else ''} mit SNMP-Problemen")
+5
View File
@@ -31,6 +31,10 @@ def _matches(record, key, value):
vrf = getattr(record, "vrf", None)
vrf_id = vrf if isinstance(vrf, int) else getattr(vrf, "id", None)
return (vrf_id is None) if value == "null" else vrf_id == value
if key == "contains":
import ipaddress
prefix = getattr(record, "prefix", None)
return prefix is not None and ipaddress.ip_address(value) in ipaddress.ip_network(str(prefix), strict=False)
if key == "address":
return str(getattr(record, "address", "")).split("/")[0] == str(value).split("/")[0]
if key.endswith("_id") and not hasattr(record, key):
@@ -80,3 +84,4 @@ class FakeNetBox:
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint())
self.extras = SimpleNamespace(custom_fields=Endpoint())
+201
View File
@@ -0,0 +1,201 @@
"""Minimal SNMP agent on localhost for tests (v2c and v3 USM)."""
import hmac
import socket
import struct
import threading
from netbox_sync.core import snmp
from netbox_sync.core.snmp import (
AUTH_PROTOCOLS,
GET,
GET_BULK,
GET_NEXT,
INTEGER,
OCTET_STRING,
PRIV_PROTOCOLS,
REPORT,
RESPONSE,
TripleDES,
children,
dec_oid,
dec_value,
decode,
enc_int,
enc_oid,
enc_str,
localize,
oid_key,
password_to_key,
priv_key,
seq,
tlv,
)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
ENGINE_ID = bytes.fromhex("80001f8880c71100000000000000000001")
def encode_value(value):
if isinstance(value, bool):
return enc_int(int(value))
if isinstance(value, int):
return enc_int(value)
if isinstance(value, tuple) and value[0] == "oid":
return enc_oid(value[1])
if isinstance(value, tuple) and value[0] == "ip":
return tlv(snmp.IP_ADDRESS, bytes(int(part) for part in value[1].split(".")))
if isinstance(value, tuple) and value[0] == "counter":
return enc_int(value[1], snmp.COUNTER32)
return enc_str(value)
class Agent:
def __init__(self, mib, community="public", users=None):
self.mib = {oid.strip("."): value for oid, value in mib.items()}
self.order = sorted(self.mib, key=oid_key)
self.community = community.encode()
self.users = users or {} # name -> credential record
self.boots, self.time = 3, 1000
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.requests = 0
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def close(self):
self.sock.close()
# MIB --------------------------------------------------------------
def _next(self, oid):
key = oid_key(oid)
return next((item for item in self.order if oid_key(item) > key), None)
def _bindings(self, pdu_type, oids, non_repeaters, repetitions):
result = []
if pdu_type == GET:
for oid in oids:
value = self.mib.get(oid)
result.append(seq(enc_oid(oid), encode_value(value) if value is not None
else tlv(snmp.NO_SUCH_OBJECT, b"")))
else:
count = repetitions if pdu_type == GET_BULK else 1
for oid in oids:
current = oid
for _ in range(max(1, count)):
nxt = self._next(current)
if nxt is None:
result.append(seq(enc_oid(current), tlv(snmp.END_OF_MIB_VIEW, b"")))
break
result.append(seq(enc_oid(nxt), encode_value(self.mib[nxt])))
current = nxt
return seq(*result)
def _response(self, request_id, bindings, kind=RESPONSE):
return tlv(kind, enc_int(request_id) + enc_int(0) + enc_int(0) + bindings)
@staticmethod
def _read_pdu(tag, content):
request_id, a, b, varbinds = children(content)
oids = [dec_oid(children(binding)[0][1]) for _t, binding in children(varbinds[1])]
return tag, dec_value(INTEGER, request_id[1]), dec_value(INTEGER, a[1]), dec_value(INTEGER, b[1]), oids
# serving ----------------------------------------------------------
def _serve(self):
while True:
try:
data, addr = self.sock.recvfrom(65535)
except OSError:
return
self.requests += 1
try:
answer = self._handle(data)
except Exception: # noqa: BLE001 - ignore garbage like a real agent
answer = None
if answer:
self.sock.sendto(answer, addr)
def _handle(self, data):
_tag, content, _pos = decode(data)
items = children(content)
version = dec_value(INTEGER, items[0][1])
if version == 1:
if items[1][1] != self.community:
return None
tag, request_id, a, b, oids = self._read_pdu(*items[2])
bindings = self._bindings(tag, oids, a, b)
return seq(enc_int(1), enc_str(self.community), self._response(request_id, bindings))
return self._handle_v3(data, items)
def _handle_v3(self, data, items):
_v, header, (_t, usm_raw), (data_tag, data_raw) = items
header_items = children(header[1])
msg_id = dec_value(INTEGER, header_items[0][1])
flags = header_items[2][1][0]
_t, usm_content, _p = decode(usm_raw)
engine_id, _boots, _time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
user = bytes(user).decode()
def report(oid):
body = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(
msg_id, seq(seq(enc_oid(oid), enc_int(1, snmp.COUNTER32))), REPORT))
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(b""),
enc_str(b""))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x00"), enc_int(3)),
enc_str(usm), body)
if not engine_id:
return report("1.3.6.1.6.3.15.1.1.4.0")
record = self.users.get(user)
if record is None:
return report("1.3.6.1.6.3.15.1.1.3.0")
hash_func, size = AUTH_PROTOCOLS[record["auth_protocol"]]
auth_key = localize(password_to_key(record["auth_password"], hash_func), ENGINE_ID, hash_func)
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if not flags & 1 or hmac.new(auth_key, zeroed, hash_func).digest()[:size] != auth_params:
return report("1.3.6.1.6.3.15.1.1.5.0")
protocol = record.get("priv_protocol")
key = priv_key(record["priv_password"], ENGINE_ID, hash_func, PRIV_PROTOCOLS[protocol]) if protocol else None
if data_tag == OCTET_STRING:
plain = self._crypt(protocol, key, bytes(data_raw), bytes(priv_params), _boots, _time, decrypt=True)
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_ce, _cn, pdu = children(scoped)
tag, request_id, a, b, oids = self._read_pdu(*pdu)
scoped_out = seq(enc_str(ENGINE_ID), enc_str(b""), self._response(request_id, self._bindings(tag, oids, a, b)))
salt = b""
if protocol:
salt = struct.pack(">Q", 99) if protocol != "DES" else struct.pack(">II", self.boots, 77)
encrypted = self._crypt(protocol, key, scoped_out, salt, dec_value(INTEGER, enc_int(self.boots)[2:]),
self.time, decrypt=False)
body = enc_str(encrypted)
else:
body = scoped_out
out_flags = flags & 0x03
def build(params):
usm = seq(enc_str(ENGINE_ID), enc_int(self.boots), enc_int(self.time), enc_str(user), enc_str(params),
enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([out_flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * size)
return build(hmac.new(auth_key, packet, hash_func).digest()[:size])
@staticmethod
def _crypt(protocol, key, data, salt, boots, engine_time, decrypt):
if protocol == "DES":
iv = bytes(a ^ b for a, b in zip(key[8:16], salt))
cipher = Cipher(TripleDES(key[:8] * 3), modes.CBC(iv))
if not decrypt:
data += b"\x00" * (-len(data) % 8)
else:
boots = boots if isinstance(boots, int) else dec_value(INTEGER, boots)
engine_time = engine_time if isinstance(engine_time, int) else dec_value(INTEGER, engine_time)
return snmp.aes_cfb(key, struct.pack(">II", boots, engine_time) + salt, data, decrypt)
worker = cipher.decryptor() if decrypt else cipher.encryptor()
return worker.update(data) + worker.finalize()
+118
View File
@@ -0,0 +1,118 @@
"""NetBox Windows Agent protocol v1 against a small in-process agent (same rules as the C# agent)."""
import base64
import hashlib
import hmac
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
import pytest
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from netbox_sync.core import agent_client
from netbox_sync.core.clients import apply_scan, new_row, scan_clients
KEY = "test-key-0123456789abcdef"
INVENTORY = {
"ok": True, "source": "agent", "agent_version": "0.2.0", "name": "pc0815", "domain": "firma.local",
"part_of_domain": True, "manufacturer": "LENOVO", "model": "21MW", "product_name": "21MW",
"product_version": "ThinkBook 16 G7 ARP", "serial": "PW0K84A9", "bios_version": "N3BET", "chassis": [10],
"user": "FIRMA\\anna", "memory": 16 * 1024 ** 3, "cpu": "AMD Ryzen 5", "cores": 6,
"os": "Microsoft Windows 11 Pro", "os_version": "10.0.26100", "os_build": "26100", "os_display_version": "24H2",
"os_architecture": "64-Bit", "installed": "2025-01-01T10:00:00", "last_boot": "2026-11-18T08:00:00",
"nics": [{"name": "Ethernet", "description": "Realtek PCIe GbE", "mac": "84:BA:59:60:C8:B7",
"ips": ["192.168.65.43", "fe80::1"], "masks": ["255.255.255.0", "64"], "gateway": ["192.168.65.1"],
"dhcp": True, "physical": True, "speed": 1000000000},
{"name": "", "description": "OpenVPN", "mac": "", "ips": ["10.8.0.2"], "masks": ["255.255.255.0"],
"gateway": [], "dhcp": False, "physical": False, "speed": 0}],
"disks": [{"device_id": "\\\\.\\PHYSICALDRIVE0", "model": "Samsung SSD", "serial": "S1", "size": 512110190592}],
"memory_modules": [], "software": [{"name": "7-Zip", "version": "24.08", "publisher": "Igor Pavlov"}],
}
class _Handler(BaseHTTPRequestHandler):
seen = set()
def log_message(self, *_args):
pass
def _send(self, status, data):
body = json.dumps(data).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self): # noqa: N802 - http.server API
url = urlparse(self.path)
if url.path == "/v1/info":
return self._send(200, {"agent": "netbox-windows-agent", "version": "0.2.0", "protocol": 1})
query = {key: values[0] for key, values in parse_qs(url.query).items()}
nonce, ts = query.get("nonce", ""), query.get("ts", "0")
if abs(time.time() - int(ts)) > 300:
return self._send(401, {"error": "clock skew too large"})
expected = hmac.new(agent_client.derive_key(KEY, "netbox-agent auth v1"),
f"GET\n/v1/inventory\n{nonce}\n{ts}".encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, self.headers.get("X-Agent-Signature", "")):
return self._send(401, {"error": "wrong key"})
if nonce in self.seen:
return self._send(401, {"error": "nonce reused"})
self.seen.add(nonce)
iv = os.urandom(12)
data = AESGCM(agent_client.derive_key(KEY, "netbox-agent enc v1")).encrypt(
iv, json.dumps(INVENTORY).encode(), nonce.encode())
self._send(200, {"protocol": 1, "iv": base64.b64encode(iv).decode(), "data": base64.b64encode(data).decode()})
@pytest.fixture
def agent():
server = HTTPServer(("127.0.0.1", 0), _Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield server.server_address[1]
server.shutdown()
def test_info_and_encrypted_inventory(agent):
assert agent_client.info("127.0.0.1", agent)["version"] == "0.2.0"
raw = agent_client.query("127.0.0.1", KEY, agent)
assert raw["ok"] and raw["host"] == "127.0.0.1" and raw["serial"] == "PW0K84A9"
def test_wrong_key_is_explained(agent):
raw = agent_client.query("127.0.0.1", "another-key-0123456789", agent)
assert raw == {"host": "127.0.0.1", "ok": False, "error": "Agent-Schlüssel stimmt nicht"}
def test_unreachable_agent_is_reported_not_raised():
raw = agent_client.query("127.0.0.1", KEY, 1, timeout=1)
assert not raw["ok"] and raw["error"].startswith("Agent nicht erreichbar")
def test_agent_inventory_runs_through_the_client_scan(agent):
rows = scan_clients([new_row("127.0.0.1")], query=lambda host: agent_client.query(host, KEY, agent),
port=agent, service="Agent")
row = rows[0]
assert row["status"] == "ok" and row["name"] == "PC0815" and row["source"] == "agent"
# Lenovo: marketing name from the product version, VPN adapter (not physical) left out
assert row["model"] == "ThinkBook 16 G7 ARP" and row["machine_type"] == "21MW"
assert [(item["name"], item["ips"]) for item in row["interfaces"]] == [("Ethernet", ["192.168.65.43/24"])]
assert row["software_count"] == 1 and row["disks"][0]["model"] == "Samsung SSD"
def test_offline_host_names_the_agent_port():
row = scan_clients([new_row("127.0.0.1")], query=lambda host: {}, port=1, service="Agent")[0]
assert row["status"] == "offline" and "Agent-Port 1" in row["message"]
def test_generated_configuration_is_valid_for_the_agent():
key = agent_client.new_scan_key()
config = agent_client.agent_config(key, 8731, ["10.0.0.0/24"])
assert len(key) >= 16 and config["mode"] == "listen" and config["scan_key"] == key
assert config["allowed_networks"] == ["10.0.0.0/24"] and config["listen_port"] == 8731
assert apply_scan(new_row("x"), dict(INVENTORY, host="x"))["os_display_version"] == "24H2"
+22
View File
@@ -1,3 +1,4 @@
import ipaddress
from types import SimpleNamespace
import pytest
@@ -128,3 +129,24 @@ def test_without_tenant_the_whole_netbox_is_searched_and_tenant_comes_from_the_c
assert [ap["device"].id if ap["device"] else None for ap in aps] == [102, 101, None]
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21, "tenant": 7}}, role_id=30, dry_run=False)
assert report["errors"] == [] and nb.dcim.devices.created[-1]["tenant"] == 7
def test_ip_goes_into_the_vrf_of_the_tenant_prefix():
nb = _netbox()
vrf = nb.ipam.vrfs.create({"name": "Kunde", "tenant": 7})
nb.ipam.vrfs.create({"name": "Fremd", "tenant": 999})
nb.ipam.prefixes.create({"prefix": "10.0.0.0/8", "vrf": None})
nb.ipam.prefixes.create({"prefix": "0.0.0.0/0", "vrf": None})
for ap in parse_csv(CSV):
if ap["ip"]:
network = ipaddress.ip_network(f"{ap['ip']}/24", strict=False)
if not nb.ipam.prefixes.filter(prefix=str(network)):
nb.ipam.prefixes.create({"prefix": str(network), "vrf": SimpleNamespace(id=vrf.id, name="Kunde")})
engine = APSyncEngine(nb)
engine.load_context(7)
aps = parse_csv(CSV)
engine.match(aps)
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21}}, role_id=30, dry_run=False)
assert report["errors"] == []
created = nb.ipam.ip_addresses.created
assert created and all(payload["vrf"] == vrf.id and payload["address"].endswith("/24") for payload in created)
+94
View File
@@ -222,3 +222,97 @@ def test_scan_runs_in_process(monkeypatch):
status = {row["host"]: row["status"] for row in results}
assert status == {"pc01.firma.local": "ok", "off": "offline", "unknown": "offline"}
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
+44
View File
@@ -295,3 +295,47 @@ def test_reparse_fixes_older_exports():
assert rebuilt["discovered_at"] == 123
assert next(item for item in rebuilt["interfaces"] if item["name"] == "2")["neighbor"]["system_name"] == "AP-005"
assert lancom.reparse({"platform": "aruba_cx", "raw": {}}) == {"platform": "aruba_cx", "raw": {}}
# Real "show info" layout: lower-case "Local port", empty values and lines indented after a paging prompt.
REAL_NEIGHBORS = """show info 1-26
Local port : Port 2
Chassis ID : 00-A0-57-00-00-01
Port ID : LAN1
Port Description : LAN1
System Name : AP-005
Management Address : 10.0.0.22 (IPv4)
Management Address : fe80::1 (IPv6)
Local port : Port 12
Chassis ID : PC-020
Port ID : C4-EF-BB-00-00-01
Port Description :
System Name :
System Description :
Local port : Port 25
Chassis ID : MikroTik
Port ID : bridge/ether1
Port Description :
System Name :
System Description : 6.49.17 (stable) MikroTik
Management Address : 192.168.88.3 (IPv4)
SW-08(lldp)# """
def test_real_neighbor_layout():
neighbors = lancom.parse_neighbors(REAL_NEIGHBORS)
assert [(item["local_port"], item["system_name"], item["remote_port"]) for item in neighbors] == [
("2", "AP-005", "LAN1"), ("12", "PC-020", "C4-EF-BB-00-00-01"), ("25", "MikroTik", "bridge/ether1")]
assert neighbors[0]["management_ip"] == "10.0.0.22" and neighbors[1]["port_description"] == ""
def test_prompt_is_no_port_description():
config = PORT_CONFIG.replace("25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n\n",
"25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n")
ports = lancom.parse_port_config(config.replace("\nSW-08(port)#", "\n\nSW-08(port)#"))
assert ports[25]["description"] == "" and ports[1]["description"] == "Uplink"
ports = lancom.parse_port_config("26 Enabled Auto Disabled 9600 Discard Disabled\n\n\nSW-08(port)# ")
assert ports[26]["description"] == ""
+183
View File
@@ -0,0 +1,183 @@
from types import SimpleNamespace
import pytest
from fake_netbox import FakeNetBox, Record
from snmp_agent import Agent
from netbox_sync.core import printers, snmp
from netbox_sync.core.printers import PrinterSyncEngine, printer_key, read_printer, supplies_text, to_import
IP = "10.20.0.50"
MIB = {
printers.SYS_DESCR: "HP ETHERNET MULTI-ENVIRONMENT,ROM none,JETDIRECT,JD153,EEPROM JSI24090012",
printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.11.2.3.9.1"),
printers.SYS_NAME: "NPI1A2B3C",
printers.SYS_LOCATION: "Geschäftsstelle 1. OG",
printers.SYS_CONTACT: "IT",
f"{printers.HR_DEVICE_TYPE}.1": ("oid", printers.HR_PRINTER),
f"{printers.HR_DEVICE_TYPE}.2": ("oid", "1.3.6.1.2.1.25.3.1.4"),
f"{printers.HR_DEVICE_DESCR}.1": "HP Color LaserJet Pro M454dw",
f"{printers.HR_PRINTER_STATUS}.1": 3,
f"{printers.HR_PRINTER_ERRORS}.1": b"\x20\x00", # low toner
f"{printers.PRT_SERIAL}.1": "vnb3k12345",
f"{printers.PRT_LIFE_COUNT}.1.1": ("counter", 48211),
f"{printers.PRT_SUPPLIES}.3.1.1": 1, f"{printers.PRT_SUPPLIES}.3.1.2": 2,
f"{printers.PRT_SUPPLIES}.5.1.1": 21, f"{printers.PRT_SUPPLIES}.5.1.2": 21,
f"{printers.PRT_SUPPLIES}.6.1.1": "Black Cartridge HP W2030A",
f"{printers.PRT_SUPPLIES}.6.1.2": "Cyan Cartridge HP W2031A",
f"{printers.PRT_SUPPLIES}.8.1.1": 2400, f"{printers.PRT_SUPPLIES}.8.1.2": 100,
f"{printers.PRT_SUPPLIES}.9.1.1": 600, f"{printers.PRT_SUPPLIES}.9.1.2": -3,
f"{printers.PRT_COLORANT}.1.1": "black", f"{printers.PRT_COLORANT}.1.2": "cyan",
f"{printers.PRT_INPUT}.9.1.2": 250, f"{printers.PRT_INPUT}.10.1.2": 120,
f"{printers.PRT_INPUT}.13.1.2": "Fach 2",
f"{printers.PRT_DISPLAY}.1.1": "Bereit",
f"{printers.IF_TABLE}.2.2": "eth0", f"{printers.IF_TABLE}.3.2": 6,
f"{printers.IF_TABLE}.6.2": bytes.fromhex("a0b1c2d3e4f5"),
f"{printers.IP_ADDR_IFINDEX}.{IP}": 2,
f"{printers.IP_ADDR_MASK}.{IP}": ("ip", "255.255.255.0"),
"1.3.6.1.2.1.47.1.1.1.1.10.1": "20240115",
}
USER = {"version": "3", "username": "scan", "auth_protocol": "SHA", "auth_password": "authpass123",
"priv_protocol": "AES", "priv_password": "privpass123"}
@pytest.fixture
def agent():
instance = Agent(MIB, community="geheim", users={"scan": USER})
yield instance
instance.close()
def _client(agent, record):
return snmp.SnmpClient("127.0.0.1", record, timeout=0.5, retries=0, port=agent.port)
def test_v2c_get_and_walk(agent):
client = _client(agent, {"version": "2c", "community": "geheim"})
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
walked = client.walk(printers.PRT_SUPPLIES)
assert len(walked) == 10 and all(snmp.in_subtree(oid, printers.PRT_SUPPLIES) for oid in walked)
with pytest.raises(snmp.SnmpTimeout):
_client(agent, {"version": "2c", "community": "public"}).get([printers.SYS_NAME])
@pytest.mark.parametrize("auth, priv", [("SHA", "AES"), ("MD5", "DES"), ("SHA-256", "AES-256"), ("SHA-512", ""),
("SHA-224", "AES-192")])
def test_v3_auth_and_privacy(auth, priv):
record = dict(USER, auth_protocol=auth, priv_protocol=priv)
agent = Agent(MIB, users={"scan": record})
try:
client = _client(agent, record)
assert client.get([printers.SYS_NAME])[printers.SYS_NAME] == b"NPI1A2B3C"
assert len(client.walk(printers.PRT_SUPPLIES)) == 10
finally:
agent.close()
def test_connect_tries_all_credentials_and_explains_v3_errors(agent):
wrong_v3 = dict(USER, id="b", auth_password="falsch-falsch")
client, notes = snmp.connect("127.0.0.1", [{"id": "a", "version": "2c", "community": "public"}, wrong_v3,
dict(USER, id="c")], timeout=0.3, retries=0, port=agent.port)
assert client.credential.record["id"] == "c"
assert notes == ["SNMPv3 scan: falsches Authentifizierungs-Passwort oder -Protokoll"]
with pytest.raises(snmp.SnmpAuthError, match="unbekannter Benutzer"):
snmp.connect("127.0.0.1", [dict(USER, username="nobody")], timeout=0.3, retries=0, port=agent.port)
def test_printer_data_is_read_from_standard_mibs(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
assert info["manufacturer"] == "HP" and info["model"] == "Color LaserJet Pro M454dw"
assert info["serial"] == "VNB3K12345" and info["mac"] == "A0:B1:C2:D3:E4:F5" and info["prefix_length"] == 24
assert info["page_count"] == 48211 and info["color"] is True and info["firmware"] == "20240115"
assert info["site_hint"] == "Geschäftsstelle 1. OG" and info["status"] == "bereit"
assert info["errors"] == ["wenig Toner"] and info["display"] == ["Bereit"]
assert info["trays"] == [{"name": "Fach 2", "media": "", "capacity": 250, "level": "120/250 Blatt"}]
assert supplies_text(info["supplies"]) == "Black Cartridge HP W2030A: 25 %\nCyan Cartridge HP W2031A: vorhanden"
def test_non_printer_is_ignored():
agent = Agent({printers.SYS_NAME: "switch", printers.SYS_OBJECT_ID: ("oid", "1.3.6.1.4.1.9.1.1")})
try:
assert read_printer(_client(agent, {"version": "2c", "community": "public"}), IP) is None
finally:
agent.close()
def _netbox():
nb = FakeNetBox()
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Kunde", group=None))
nb.dcim.sites.records.append(Record(nb.dcim.sites, id=21, name="Geschäftsstelle", tenant=SimpleNamespace(id=7)))
nb.dcim.device_roles.records.append(Record(nb.dcim.device_roles, id=31, name="Drucker"))
old = Record(nb.dcim.devices, id=201, name="Drucker EG", serial="", tenant=SimpleNamespace(id=7),
role=SimpleNamespace(id=31), site=SimpleNamespace(id=21), description="", primary_ip4=None,
custom_fields={"printer_page_count": 100})
nb.dcim.devices.records.append(old)
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=301, name="eth0", device=old, mac_address=None))
nb.ipam.ip_addresses.records.append(Record(nb.ipam.ip_addresses, id=401, address="10.20.0.60/24", vrf=None,
assigned_object_type="dcim.interface",
assigned_object=SimpleNamespace(id=301, device=SimpleNamespace(id=201)),
assigned_object_id=301, tenant=None))
return nb
def test_sync_creates_fields_and_printers_and_updates_counters(agent):
info = read_printer(_client(agent, {"version": "2c", "community": "geheim"}), IP)
new = to_import(dict(info, ip=IP, snmp="SNMPv2c", notes=[]))
known = to_import(dict(info, ip="10.20.0.60", snmp="SNMPv2c", notes=[], serial="", mac="",
name="Drucker EG", page_count=200))
nb = _netbox()
engine = PrinterSyncEngine(nb, role_id=31)
engine.load_context(7)
items = [new, known]
engine.match(items)
assert known["method"] in ("Name", "IP-Adresse") and new.get("device") is None
preview = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=True)
assert preview["errors"] == [] and nb.extras.custom_fields.created == []
assert any("Seitenzähler" in change for change in preview["changes"])
report = engine.sync(items, {printer_key(new): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
assert report["errors"] == []
assert {field["name"] for field in nb.extras.custom_fields.created} == {name for name, *_ in printers.CUSTOM_FIELDS}
created = nb.dcim.devices.created[-1]
assert created["name"] == "NPI1A2B3C" and created["serial"] == "VNB3K12345" and "platform" not in created
assert created["custom_fields"]["printer_page_count"] == 48211 and created["custom_fields"]["printer_color"]
assert nb.dcim.manufacturers.created[0]["name"] == "HP"
assert nb.dcim.device_types.created[0]["model"] == "Color LaserJet Pro M454dw"
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
assert nb.dcim.devices.get(201).custom_fields["printer_page_count"] == 200
def test_hp_jetdirect_model_comes_from_printer_name_not_generic_sysdescr():
mib = {key: value for key, value in MIB.items() if not key.startswith(printers.HR_DEVICE_DESCR)}
mib[printers.HP_DEVICE_ID] = "MFG:Hewlett-Packard;CMD:PJL,PCL;MDL:HP LaserJet M402dn;CLS:PRINTER;"
agent = Agent(mib)
try:
info = read_printer(_client(agent, {"version": "2c", "community": "public"}), IP)
assert info["model"] == "LaserJet M402dn" and info["manufacturer"] == "HP"
mib[f"{printers.PRT_PRINTER_NAME}.1"] = "HP LaserJet Pro M404dn"
finally:
agent.close()
agent = Agent(mib)
try:
assert read_printer(_client(agent, {"version": "2c", "community": "public"}), IP)["model"] == \
"LaserJet Pro M404dn"
finally:
agent.close()
def test_missing_model_can_be_mapped_to_an_existing_device_type():
nb = _netbox()
nb.dcim.manufacturers.records.append(Record(nb.dcim.manufacturers, id=50, name="HP", slug="hp"))
nb.dcim.device_types.records.append(Record(nb.dcim.device_types, id=60, model="LaserJet Pro M404",
manufacturer=SimpleNamespace(id=50, name="HP")))
printer = to_import({"ip": "10.20.0.70", "name": "Drucker24", "manufacturer": "HP", "model": "LaserJet Pro M404dn",
"serial": "PHCLJ40175", "mac": "", "snmp": "SNMPv2c", "notes": []})
engine = PrinterSyncEngine(nb, role_id=31, counters=False)
engine.load_context(7)
engine.match([printer])
assert not engine.type_exists(printer) and engine.suggest_type(printer) == 60
engine.type_map = {printers.model_key(printer): 60}
report = engine.sync([printer], {printer_key(printer): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
assert report["errors"] == [] and nb.dcim.device_types.created == []
assert nb.dcim.devices.created[-1]["device_type"] == 60
+67
View File
@@ -612,3 +612,70 @@ def test_vlans_of_another_site_are_only_labelled():
assert [note for note in report["notes"] if "VLAN 10" in note] == [
"VLAN 10 „MOBILE“ gehört zu einem anderen Standort als access-01 – nur im Label vermerkt, nicht am Port "
"zugewiesen (VLAN global machen, um es zuzuweisen)"]
def test_skipped_cables_are_explained():
nb, switch, snapshot = _numbered_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0
assert any("nicht in NetBox gefunden" in note for note in report["notes"])
switch["neighbor_devices"] = {"1/1/2": 0} # "no cable" is chosen deliberately: no note
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert not any("übersprungen" in note for note in report["notes"])
def test_wireless_interfaces_are_no_cable_targets():
"""LANCOM LW-600: eth1 plus wlan0/wlan1; LLDP reports "LAN1" – wlan1 must not make it ambiguous."""
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=52, name="wlan1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="LAN1", port_description="LAN1")
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert report["errors"] == []
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
def _ap_with_two_ports():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="eth2", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=52, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="Uplink", port_description="")
return nb, switch, snapshot
def test_far_end_interface_can_be_chosen():
nb, switch, snapshot = _ap_with_two_ports()
plan = plan_switch_sync(nb, switch, snapshot)
neighbor = plan["neighbors"][0]
assert [item["name"] for item in neighbor["interfaces"]] == ["eth1", "eth2"] # no Wi-Fi
assert neighbor["suggested_interface"] is None and neighbor["interface_id"] is None
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0 and any("keine passende Schnittstelle" in n for n in report["notes"])
switch["neighbor_interfaces"] = {"1/1/2": 51}
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] == 51
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 51}]
def test_chosen_interface_of_another_device_is_ignored():
nb, switch, snapshot = _ap_with_two_ports()
switch["neighbor_interfaces"] = {"1/1/2": 20} # belongs to server-01, not AP-005
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0