Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76f12069b5 | ||
|
|
76662dd378 | ||
|
|
9603add434 | ||
|
|
a67b0d3e5c | ||
|
|
43c5e5e85a | ||
|
|
b1cfdf7a5c | ||
|
|
2db5e1f251 | ||
|
|
4d77528266 | ||
|
|
596bbabb54 | ||
|
|
235fb8e26a | ||
|
|
05d34e4823 | ||
|
|
f134db0c16 | ||
|
|
1352514577 | ||
|
|
fc503bd7d3 | ||
|
|
144e5f9eb8 | ||
|
|
823d968b33 | ||
|
|
0241509845 | ||
|
|
b89a364bf0 | ||
|
|
97ee72e610 | ||
|
|
c85df7402d | ||
|
|
5427cc015e | ||
|
|
1aa1c15aa8 | ||
|
|
51f3fc70cd | ||
|
|
411c5446fe | ||
|
|
1bd2d42b5d | ||
|
|
2092f41624 | ||
|
|
e9e1783360 | ||
|
|
576f245b7d | ||
|
|
0e04dae354 | ||
|
|
63ed535a37 | ||
|
|
781ed7d17b | ||
|
|
05695a8471 | ||
|
|
1949f03bae | ||
|
|
dfe985bb9e | ||
|
|
d853f08445 | ||
|
|
f4c507de6c | ||
|
|
3c8bc7879c | ||
|
|
770edc4a03 | ||
|
|
eee60d26ad | ||
|
|
63fd7b987a | ||
|
|
899b4c58fc | ||
|
|
89fe37ea04 |
No files matched your search
@@ -62,6 +62,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
- VLAN membership per port (untagged and tagged, read from the running
|
||||
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
|
||||
only VLAN-related lines of the configuration are kept in the raw data
|
||||
- LAG members (Aruba CX `lag N`, ArubaOS-Switch `trunk … trkN`, Comware
|
||||
`port link-aggregation group N`) get their LAG in the label, e.g.
|
||||
`10,20 (LAG 1)`, and are assigned to the LAG interface in NetBox (field
|
||||
*LAG*; only on the same device). Members without own VLAN configuration take
|
||||
the VLANs of their LAG. NetBox Utilities 0.25.0 or later ignores the LAG note
|
||||
when it evaluates VLAN labels
|
||||
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
|
||||
`1/1/5`): equal name, then equal port number, then natural order
|
||||
- **Mapping review** before the preview: non-obvious port mappings and every
|
||||
@@ -87,9 +93,47 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
IRF): every member is assigned to its own NetBox device (suggested from the
|
||||
NetBox virtual chassis positions, stored per switch) and gets its own ports;
|
||||
LAGs and VLAN interfaces stay on the switch's device
|
||||
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
|
||||
- Optional: with the [NetBox Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
|
||||
plugin (0.24.0 or later) a detected stack is also entered as its switch stack
|
||||
(the switch's device as stack switch, the other member devices as members);
|
||||
members entered by hand are kept. Without the plugin this step is skipped
|
||||
- Optional configuration backup ("Konfiguration als Anhang sichern"): with the
|
||||
[netbox-attachments](https://github.com/Kani999/netbox-attachments) plugin the
|
||||
running configuration is attached to the switch's device as a text file.
|
||||
Passwords, keys and SNMP communities are removed first; a new attachment is
|
||||
only added when the configuration changed (SHA-256 in the description).
|
||||
Older plugin versions (parent on the attachment) and newer ones (separate
|
||||
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.
|
||||
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
|
||||
neighbor; such changes are marked with ⚠ in the preview. Cables to patch
|
||||
panels (front/rear ports) and far ends that already have another cable are
|
||||
never changed
|
||||
- The switch configuration is only changed when "Enable LLDP if needed" is
|
||||
explicitly switched on
|
||||
- LANCOM switches with the mode-based LCOS SX 3.x CLI (e.g. GS-2326P+) are read
|
||||
over SSH: `system`, `port`, `vlan`, `ip` and `lldp` modes with their `show`
|
||||
commands. Untagged/tagged VLANs follow the egress rule (Access, Hybrid = PVID
|
||||
untagged, Trunk). There is no running-config; the collected outputs are
|
||||
attached as backup. "Enable LLDP if needed" switches ports whose LLDP mode is
|
||||
Disabled/Tx only to `enable` (not saved) and waits one LLDP interval
|
||||
- One-off import without SSH ("Backup importieren …"): configuration backups
|
||||
of D-Link DGS-1210 (`config.bin`) and Linksys LGS (`*.cfg` or the contained
|
||||
`SNCSR.conf`) switches are read offline. Hostname, location, management IP,
|
||||
port descriptions, admin state, untagged/tagged VLANs and VLAN names are
|
||||
taken over; the switch is matched to the NetBox device by its hostname and
|
||||
then synchronized like an SSH result (no LLDP neighbors, hence no cables)
|
||||
The D-Link `config.bin` is attached to the device unchanged (it contains the
|
||||
switch's secrets as stored by the switch); the Linksys configuration is
|
||||
attached as text with secrets removed
|
||||
|
||||
### Sophos access points (CSV from Sophos Central)
|
||||
|
||||
@@ -108,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)
|
||||
|
||||
@@ -145,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
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.10.5"
|
||||
#define AppVersion "4.20.1"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.10.5"
|
||||
APP_VERSION = "4.20.1"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
"""One-off import of switch configuration backups (no SSH).
|
||||
|
||||
Some small switches cannot be read over SSH in a useful way, but their web UI
|
||||
exports a configuration backup. These parsers turn such a backup into the
|
||||
same snapshot that :func:`netbox_sync.core.switches.build_snapshot` produces,
|
||||
so the normal review and synchronization run unchanged.
|
||||
|
||||
Supported formats:
|
||||
|
||||
* D-Link DGS-1210 series (``config.bin``): a short header with the model name
|
||||
followed by a zlib-compressed dump of SNMP objects (``OID<TAB>type<TAB>value``).
|
||||
* Linksys LGS series (``*.cfg``): a firmware header followed by a tar archive
|
||||
whose ``current_config/SNCSR.conf`` holds an ISS-style CLI configuration.
|
||||
A plain text ``SNCSR.conf`` is accepted as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
import tarfile
|
||||
import time
|
||||
import zlib
|
||||
|
||||
from netbox_sync.core.switches import _interface, _membership, mask_config
|
||||
|
||||
BACKUP_PLATFORMS = {
|
||||
"dlink_backup": "D-Link (Backup-Datei)",
|
||||
"linksys_backup": "Linksys LGS (Backup-Datei)",
|
||||
}
|
||||
|
||||
FILE_FILTER = "Switch-Backups (*.bin *.cfg *.conf *.txt);;Alle Dateien (*)"
|
||||
|
||||
|
||||
class BackupError(ValueError):
|
||||
"""The file is no supported switch backup."""
|
||||
|
||||
|
||||
def parse_backup(data, filename=""):
|
||||
"""Snapshot of a backup file plus ``name``, ``host`` and ``model`` from its configuration.
|
||||
|
||||
Returns ``(switch, snapshot)`` where ``switch`` is a profile entry without credentials.
|
||||
"""
|
||||
if isinstance(data, str):
|
||||
data = data.encode("utf-8")
|
||||
dump = _dlink_dump(data)
|
||||
if dump is not None:
|
||||
switch, snapshot = _dlink_snapshot(dump, data)
|
||||
# The original file is attached 1:1 so it can be restored on the switch.
|
||||
snapshot["config_file"] = {"name": filename or "config.bin", "data": base64.b64encode(data).decode("ascii")}
|
||||
return switch, snapshot
|
||||
text = _linksys_text(data)
|
||||
if text is not None:
|
||||
return _linksys_snapshot(text)
|
||||
raise BackupError(f"„{filename or 'Datei'}“ ist kein unterstütztes Backup (D-Link DGS-1210 oder Linksys LGS).")
|
||||
|
||||
|
||||
def _snapshot(platform, interfaces, vlan_names, config_backup=""):
|
||||
ips = [{"interface": item["name"], "address": address}
|
||||
for item in interfaces for address in item["ip_addresses"]]
|
||||
return {
|
||||
"platform": platform,
|
||||
"interfaces": interfaces,
|
||||
"ip_addresses": ips,
|
||||
"neighbors": [],
|
||||
"lldp_neighbors": [],
|
||||
"cdp_neighbors": [],
|
||||
"raw": {},
|
||||
"vlans_read": True,
|
||||
"config_backup": config_backup,
|
||||
"vlan_names": vlan_names,
|
||||
"stack": [],
|
||||
"lldp_disabled": False,
|
||||
"lldp_enabled_automatically": False,
|
||||
"discovered_at": time.time(),
|
||||
"source": "backup",
|
||||
}
|
||||
|
||||
|
||||
def _address(address, mask):
|
||||
try:
|
||||
value = ipaddress.ip_interface(f"{address}/{mask}")
|
||||
except ValueError:
|
||||
return None
|
||||
return None if value.ip.is_unspecified else str(value)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# D-Link DGS-1210
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_DLINK_OID = re.compile(rb"^1\.3\.6\.1\.")
|
||||
|
||||
|
||||
def _dlink_dump(data):
|
||||
"""Decompressed SNMP dump of a D-Link backup, or ``None``."""
|
||||
if _DLINK_OID.match(data):
|
||||
return data
|
||||
if not data[:4] in (b"DGS-", b"DES-", b"DXS-"):
|
||||
return None
|
||||
for match in re.finditer(rb"\x78[\x01\x5e\x9c\xda]", data[:512]):
|
||||
try:
|
||||
dump = zlib.decompressobj().decompress(data[match.start():])
|
||||
except zlib.error:
|
||||
continue
|
||||
if _DLINK_OID.match(dump):
|
||||
return dump
|
||||
raise BackupError("D-Link-Backup erkannt, aber die Konfiguration lässt sich nicht entpacken.")
|
||||
|
||||
|
||||
def parse_snmp_dump(dump):
|
||||
"""``{OID: value}``; octet strings are ``bytes`` (they may contain line breaks), the rest ``str``."""
|
||||
values, position, size = {}, 0, len(dump)
|
||||
while position < size:
|
||||
if dump[position] in b"\x00\r\n":
|
||||
position += 1
|
||||
continue
|
||||
tab = dump.find(b"\t", position)
|
||||
if tab < 0:
|
||||
break
|
||||
oid = dump[position:tab].decode("ascii", "replace").strip()
|
||||
type_end = dump.find(b"\t", tab + 1)
|
||||
line_end = dump.find(b"\n", tab + 1)
|
||||
if line_end < 0:
|
||||
line_end = size
|
||||
if type_end < 0 or type_end > line_end:
|
||||
position = line_end + 1 # unknown line format
|
||||
continue
|
||||
kind = dump[tab + 1:type_end].strip()
|
||||
if kind == b"4":
|
||||
length_end = dump.find(b"\t", type_end + 1)
|
||||
try:
|
||||
length = int(dump[type_end + 1:length_end])
|
||||
except ValueError:
|
||||
position = line_end + 1
|
||||
continue
|
||||
start = length_end + 1
|
||||
values[oid] = dump[start:start + length]
|
||||
position = start + length + 1
|
||||
else:
|
||||
values[oid] = dump[type_end + 1:line_end].decode("ascii", "replace").strip()
|
||||
position = line_end + 1
|
||||
return values
|
||||
|
||||
|
||||
def _text(value):
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", "replace").strip("\x00").strip()
|
||||
return (value or "").strip()
|
||||
|
||||
|
||||
def _bitmap_ports(value):
|
||||
"""Ports set in an SNMP PortList (byte 0, bit 7 = port 1)."""
|
||||
ports = set()
|
||||
for index, byte in enumerate(value or b""):
|
||||
for bit in range(8):
|
||||
if byte & (0x80 >> bit):
|
||||
ports.add(index * 8 + bit + 1)
|
||||
return ports
|
||||
|
||||
|
||||
def _table(values, prefix):
|
||||
"""``{last index: value}`` of all OIDs ``<prefix>.<index>``."""
|
||||
result = {}
|
||||
for oid, value in values.items():
|
||||
if oid.startswith(prefix + ".") and oid[len(prefix) + 1:].isdigit():
|
||||
result[int(oid[len(prefix) + 1:])] = value
|
||||
return result
|
||||
|
||||
|
||||
def _dlink_snapshot(dump, data):
|
||||
values = parse_snmp_dump(dump)
|
||||
# The enterprise subtree of the model, e.g. 1.3.6.1.4.1.171.10.76.21.1 for DGS-1210-28P.
|
||||
base = next((match.group(1) for match in
|
||||
(re.match(r"^(1\.3\.6\.1\.4\.1\.171\.10(?:\.\d+)+?)\.7\.6\.1\.1\.\d+$", oid) for oid in values)
|
||||
if match), None)
|
||||
names, egress, untagged, pvids = {}, {}, {}, {}
|
||||
if base:
|
||||
names = _table(values, f"{base}.7.6.1.1")
|
||||
egress = _table(values, f"{base}.7.6.1.2")
|
||||
untagged = _table(values, f"{base}.7.6.1.4")
|
||||
pvids = _table(values, f"{base}.7.7.1.1")
|
||||
if not egress: # standard Q-BRIDGE-MIB
|
||||
names = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.1")
|
||||
egress = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.2")
|
||||
untagged = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.4")
|
||||
pvids = _table(values, "1.3.6.1.2.1.17.7.1.4.5.1.1")
|
||||
admin = _table(values, "1.3.6.1.2.1.2.2.1.7")
|
||||
descriptions = _table(values, f"{base}.1.16.1.2") if base else {}
|
||||
if not descriptions:
|
||||
descriptions = _table(values, "1.3.6.1.2.1.31.1.1.1.18")
|
||||
port_numbers = sorted(set(pvids) | set(admin) | set(descriptions))
|
||||
if not port_numbers:
|
||||
raise BackupError("Im D-Link-Backup wurden keine Ports gefunden.")
|
||||
|
||||
members = {port: {"untagged": set(), "tagged": set()} for port in port_numbers}
|
||||
for vid, bitmap in egress.items():
|
||||
untagged_ports = _bitmap_ports(untagged.get(vid))
|
||||
for port in _bitmap_ports(bitmap):
|
||||
if port in members:
|
||||
members[port]["untagged" if port in untagged_ports else "tagged"].add(vid)
|
||||
interfaces = []
|
||||
for port in port_numbers:
|
||||
entry = members[port]
|
||||
interfaces.append(_interface(
|
||||
str(port),
|
||||
enabled=str(admin.get(port, "1")) != "2",
|
||||
description=_text(descriptions.get(port)),
|
||||
vlans=_membership(entry["untagged"], entry["tagged"]) if entry["untagged"] or entry["tagged"] else None,
|
||||
lag=None,
|
||||
))
|
||||
if base:
|
||||
address = _address(_text(values.get(f"{base}.2.5.2.0")), _text(values.get(f"{base}.2.5.3.0")))
|
||||
if address:
|
||||
interfaces.append(_interface(_text(values.get(f"{base}.2.5.5.0")) or "System", connected=True,
|
||||
description="Management-Interface", virtual=True,
|
||||
ip_addresses=[address], vlans=None, lag=None))
|
||||
vlan_names = {vid: _text(name) for vid, name in names.items() if _text(name)}
|
||||
model = data[:16].split(b"\x00", 1)[0].decode("ascii", "replace") if not _DLINK_OID.match(data) else ""
|
||||
name = _text(values.get("1.3.6.1.2.1.1.5.0")) or (_text(values.get(f"{base}.2.7.0")) if base else "")
|
||||
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
|
||||
switch = {"name": name, "host": host, "model": model, "platform": "dlink_backup",
|
||||
"location": _text(values.get("1.3.6.1.2.1.1.6.0"))}
|
||||
return switch, _snapshot("dlink_backup", interfaces, vlan_names)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Linksys LGS (ISS CLI configuration)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_LINKSYS_MEMBER = "current_config/SNCSR.conf"
|
||||
|
||||
|
||||
def _linksys_text(data):
|
||||
"""``SNCSR.conf`` of a Linksys backup, or ``None``."""
|
||||
offset = data.find(_LINKSYS_MEMBER.encode())
|
||||
if offset >= 0:
|
||||
try:
|
||||
with tarfile.open(fileobj=io.BytesIO(data[offset:]), mode="r:") as archive:
|
||||
stream = archive.extractfile(_LINKSYS_MEMBER)
|
||||
if stream is not None:
|
||||
return stream.read().decode("utf-8", "replace")
|
||||
except (tarfile.TarError, KeyError) as error:
|
||||
raise BackupError(f"Linksys-Backup erkannt, aber nicht lesbar: {error}") from error
|
||||
head = data[:200_000].decode("utf-8", "replace")
|
||||
if re.search(r"(?m)^interface gigabitethernet \d+/\d+\s*$", head) and re.search(r"(?m)^vlan \d+\s*$", head):
|
||||
return data.decode("utf-8", "replace")
|
||||
return None
|
||||
|
||||
|
||||
_GI_PORT = re.compile(r"(?:gigabitethernet|gi)\s*(\d+)/(\d+)(?:-(\d+))?", re.I)
|
||||
|
||||
|
||||
def _linksys_ports(text):
|
||||
"""Port numbers in ``gigabitethernet 0/1``, ``gi 0/1-4`` or comma lists."""
|
||||
ports = []
|
||||
for match in _GI_PORT.finditer(text):
|
||||
start, end = int(match.group(2)), int(match.group(3) or match.group(2))
|
||||
ports += range(start, end + 1)
|
||||
return ports
|
||||
|
||||
|
||||
def _linksys_blocks(text):
|
||||
"""``(header, lines)`` for every top-level block; ISS repeats blocks per feature."""
|
||||
header, body = None, []
|
||||
for raw in text.replace("\r", "").splitlines():
|
||||
line = raw.strip()
|
||||
if line == "!":
|
||||
if header:
|
||||
yield header, body
|
||||
header, body = None, []
|
||||
elif header is None and re.match(r"^(?:interface|vlan)\s+", line, re.I):
|
||||
header, body = line, []
|
||||
elif header is not None:
|
||||
body.append(line)
|
||||
if header:
|
||||
yield header, body
|
||||
|
||||
|
||||
def _linksys_snapshot(text):
|
||||
ports, vlan_names, vlan_members, lags = {}, {}, {}, {}
|
||||
ips = {}
|
||||
for header, body in _linksys_blocks(text):
|
||||
port = re.match(r"(?i)^interface gigabitethernet (\d+)/(\d+)$", header)
|
||||
vlan_interface = re.match(r"(?i)^interface vlan (\d+)$", header)
|
||||
vlan = re.match(r"(?i)^vlan (\d+)$", header)
|
||||
if port:
|
||||
entry = ports.setdefault(int(port.group(2)), {"enabled": True, "description": ""})
|
||||
for line in body:
|
||||
if line == "shutdown":
|
||||
entry["enabled"] = False
|
||||
elif line == "no shutdown":
|
||||
entry["enabled"] = True
|
||||
description = re.match(r'^description\s+"?(.*?)"?$', line)
|
||||
if description:
|
||||
entry["description"] = description.group(1)
|
||||
group = re.match(r"^channel-group (\d+)\b", line)
|
||||
if group:
|
||||
lags[int(port.group(2))] = f"Po{group.group(1)}"
|
||||
elif vlan_interface:
|
||||
for line in body:
|
||||
address = re.match(r"^ip address (\S+) (\S+)$", line)
|
||||
if address:
|
||||
value = _address(address.group(1), address.group(2))
|
||||
if value:
|
||||
ips.setdefault(int(vlan_interface.group(1)), []).append(value)
|
||||
elif vlan:
|
||||
vid = int(vlan.group(1))
|
||||
members = vlan_members.setdefault(vid, {"untagged": set(), "tagged": set()})
|
||||
for line in body:
|
||||
name = re.match(r'^(?:ports\s+)?name\s+"?(.+?)"?$', line)
|
||||
if name:
|
||||
vlan_names[vid] = name.group(1)
|
||||
added = re.match(r"(?i)^ports add (.+?)(?:\s+untagged\s+(.+))?$", line)
|
||||
if added:
|
||||
untagged = set(_linksys_ports(added.group(2) or ""))
|
||||
for number in _linksys_ports(added.group(1)):
|
||||
members["untagged" if number in untagged else "tagged"].add(number)
|
||||
if not ports:
|
||||
raise BackupError("In der Linksys-Konfiguration wurden keine Ports gefunden.")
|
||||
|
||||
interfaces = []
|
||||
for number in sorted(ports):
|
||||
untagged = {vid for vid, item in vlan_members.items() if number in item["untagged"]}
|
||||
tagged = {vid for vid, item in vlan_members.items() if number in item["tagged"]}
|
||||
interfaces.append(_interface(
|
||||
f"GE{number}",
|
||||
enabled=ports[number]["enabled"],
|
||||
description=ports[number]["description"],
|
||||
vlans=_membership(untagged, tagged) if untagged or tagged else None,
|
||||
lag=lags.get(number),
|
||||
))
|
||||
for vid in sorted(ips):
|
||||
interfaces.append(_interface(f"vlan{vid}", connected=True, description="Management-Interface",
|
||||
virtual=True, ip_addresses=ips[vid], vlans=None, lag=None))
|
||||
system = {key: (re.search(rf'(?m)^system {key} "?(.*?)"?\s*$', text) or [None, ""])[1]
|
||||
for key in ("name", "location")}
|
||||
model = (re.search(r'(?m)^set switch-name "?(.*?)"?\s*$', text) or [None, ""])[1]
|
||||
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
|
||||
switch = {"name": system["name"], "host": host, "model": model, "platform": "linksys_backup",
|
||||
"location": system["location"]}
|
||||
return switch, _snapshot("linksys_backup", interfaces, vlan_names, mask_config(text))
|
||||
@@ -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,11 @@ 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"),
|
||||
"agent_version": raw.get("agent_version", ""),
|
||||
"software_count": len(raw.get("software") or []),
|
||||
"disks": [{"model": disk.get("model", ""), "size": int(disk.get("size") or 0)}
|
||||
for disk in raw.get("disks") 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 +367,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 +386,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 +398,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):
|
||||
|
||||
@@ -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)),
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""LANCOM switches with the LCOS SX 3.x mode-based CLI (e.g. GS-2326P+, GS-2310P+).
|
||||
|
||||
There is no ``show running-config``: every area is a mode (``port``, ``vlan``,
|
||||
``lldp``, ``system``, ``ip``) with its own ``show`` command, left with ``exit``.
|
||||
The outputs are converted into the snapshot of :mod:`netbox_sync.core.switches`.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import time
|
||||
|
||||
from netbox_sync.core.switches import (
|
||||
CLI_ERROR,
|
||||
CLI_PROMPT,
|
||||
MAC_PATTERN,
|
||||
_compress_vlans,
|
||||
_interface,
|
||||
_membership,
|
||||
clean_output,
|
||||
parse_vlan_list,
|
||||
)
|
||||
|
||||
PLATFORM = "lancom_sx3"
|
||||
|
||||
# (mode, command, output key)
|
||||
COMMANDS = (
|
||||
("system", "show", "system"),
|
||||
("port", "show status", "status"),
|
||||
("port", "show configuration", "port_config"),
|
||||
("vlan", "show vlan", "vlans"),
|
||||
("vlan", "show port-config", "vlan_ports"),
|
||||
("ip", "show", "ip"),
|
||||
("lldp", "show config", "lldp_config"),
|
||||
# "{ports}" becomes the port list from "show status", e.g. "1-26".
|
||||
("lldp", "show info {ports}", "neighbors"),
|
||||
)
|
||||
|
||||
|
||||
# The CLI pages long outputs ("-- more --, next page: Space, ..., q to quit") and cannot be told not to.
|
||||
PAGER = re.compile(r"(?im)^[^\n]*(?:q to quit|-+\s*more\s*-+)[^\n]*\Z")
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
"""Run a command; this CLI executes it only on "\r" ("\n" is just echoed).
|
||||
|
||||
Paging prompts are answered with Space and removed from the output.
|
||||
"""
|
||||
channel.send(command + "\r")
|
||||
chunks, started = [], time.monotonic()
|
||||
while time.monotonic() - started < timeout:
|
||||
if channel.recv_ready():
|
||||
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
|
||||
text = clean_output("".join(chunks))
|
||||
if PAGER.search(text):
|
||||
chunks = [PAGER.sub("", text)]
|
||||
channel.send(" ")
|
||||
started = time.monotonic() # every page gets the full timeout
|
||||
continue
|
||||
if CLI_PROMPT.search(text):
|
||||
return text
|
||||
time.sleep(0.05)
|
||||
text = clean_output("".join(chunks))
|
||||
tail = " | ".join(line.strip() for line in text.splitlines()[-3:] if line.strip())
|
||||
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. Der Switch hat die CLI-Ausgabe nicht "
|
||||
f"mit einem vollständigen Prompt abgeschlossen. Letzte Ausgabe: {tail[-300:] or '–'}")
|
||||
|
||||
|
||||
def probe(channel):
|
||||
"""``True`` when the "system" mode shows a LANCOM model; leaves the mode again."""
|
||||
_run_cli_command(channel, "system")
|
||||
system = _run_cli_command(channel, "show", timeout=30)
|
||||
_run_cli_command(channel, "exit")
|
||||
return is_lancom(system)
|
||||
|
||||
|
||||
def is_lancom(text):
|
||||
return bool(re.search(r"(?i)Model Name\s*:\s*LANCOM", text or ""))
|
||||
|
||||
|
||||
# Neighbors usually send LLDP every 30 seconds; after enabling reception we wait for one round.
|
||||
LLDP_WAIT_SECONDS = 35
|
||||
|
||||
|
||||
def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, wait=LLDP_WAIT_SECONDS):
|
||||
"""Run :data:`COMMANDS` in their modes; a missing command only leaves its output empty.
|
||||
|
||||
With ``enable_lldp`` ports that do not receive LLDP are switched to ``enable``
|
||||
(running configuration only, nothing is saved).
|
||||
"""
|
||||
outputs, mode = {"lldp_enabled_automatically": False}, None
|
||||
for wanted, command, key in COMMANDS:
|
||||
if mode != wanted:
|
||||
if mode:
|
||||
_run_cli_command(channel, "exit")
|
||||
_run_cli_command(channel, wanted)
|
||||
mode = wanted
|
||||
if "{ports}" in command:
|
||||
numbers = sorted(parse_status(outputs.get("status", "")))
|
||||
if not numbers:
|
||||
outputs[key] = ""
|
||||
continue
|
||||
command = command.format(ports=_compress_vlans(numbers))
|
||||
output = _run_cli_command(channel, command, timeout=60)
|
||||
if CLI_ERROR.search(output):
|
||||
log(f"{name}: „{wanted} → {command}“ wird nicht unterstützt")
|
||||
output = ""
|
||||
outputs[key] = output
|
||||
if key == "lldp_config" and enable_lldp:
|
||||
ports = not_receiving(output)
|
||||
if ports:
|
||||
result = _run_cli_command(channel, f"mode {_compress_vlans(ports)} enable")
|
||||
if CLI_ERROR.search(result) or re.search(r"(?i)permission|denied|privilege", result):
|
||||
raise RuntimeError(f"LLDP konnte nicht aktiviert werden: {clean_output(result).strip()[:200]}")
|
||||
outputs["lldp_enabled_automatically"] = True
|
||||
log(f"{name}: LLDP auf Port(s) {_compress_vlans(ports)} aktiviert – warte {wait} s auf Nachbarn …")
|
||||
time.sleep(wait)
|
||||
outputs[key] = _run_cli_command(channel, "show config", timeout=60)
|
||||
if mode:
|
||||
_run_cli_command(channel, "exit")
|
||||
return outputs
|
||||
|
||||
|
||||
def _field(text, label):
|
||||
# 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 ""
|
||||
|
||||
|
||||
def _speed(text):
|
||||
match = re.match(r"(?i)^(\d+(?:\.\d+)?)(G|M)?$", text or "")
|
||||
if not match:
|
||||
return None
|
||||
return int(float(match.group(1)) * (1000 if (match.group(2) or "").upper() == "G" else 1))
|
||||
|
||||
|
||||
def parse_status(output):
|
||||
"""``show status``: ``2/UTP Enabled Up Enabled 1G Full ...``."""
|
||||
ports = {}
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)/(\w+)\s+(Enabled|Disabled)\s+(Up|Down)\s+\S+\s+(\S+)", line, re.I)
|
||||
if match:
|
||||
up = match.group(4).lower() == "up"
|
||||
ports[int(match.group(1))] = {
|
||||
"enabled": match.group(3).lower() == "enabled", "connected": up,
|
||||
"speed_mbps": _speed(match.group(5)) if up else None,
|
||||
# Copper ports of these switches are Gigabit; the combo ports report SFP while a module is active.
|
||||
"media": "SFP" if match.group(2).upper() == "SFP" else "1000T",
|
||||
}
|
||||
return ports
|
||||
|
||||
|
||||
def parse_port_config(output):
|
||||
"""``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:
|
||||
text = line.strip()
|
||||
if text and not set(text) <= {"-"} and not CLI_PROMPT.search(text):
|
||||
ports[current]["description"] = text
|
||||
current = None
|
||||
return ports
|
||||
|
||||
|
||||
def parse_vlans(output):
|
||||
"""``show vlan``: ``({vid: name}, {vid: {ports}})``."""
|
||||
names, members, current = {}, {}, None
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+(.*?)\s+(Static|Combined|GVRP|MSTP|MVR|NAS|VCL|Voice)\b\s*(.*)$", line, re.I)
|
||||
if match:
|
||||
current = int(match.group(1))
|
||||
if match.group(2).strip():
|
||||
names[current] = match.group(2).strip()
|
||||
members[current] = parse_vlan_list(match.group(4))
|
||||
elif current is not None and re.match(r"^\s+[\d,\-\s]+$", line):
|
||||
members[current] |= parse_vlan_list(line) # wrapped port list
|
||||
else:
|
||||
current = None
|
||||
return names, members
|
||||
|
||||
|
||||
def parse_vlan_ports(output):
|
||||
"""``show port-config``: ``{port: (pvid, egress rule)}``."""
|
||||
ports = {}
|
||||
for line in clean_output(output).splitlines():
|
||||
match = re.match(r"^\s*(\d+)\s+(\d+)\s+\S+\s+\S+\s+(Access|Hybrid|Trunk)\b", line, re.I)
|
||||
if match:
|
||||
ports[int(match.group(1))] = (int(match.group(2)), match.group(3).lower())
|
||||
return ports
|
||||
|
||||
|
||||
def port_membership(vids, pvid, rule):
|
||||
"""Access: untagged; Trunk: all tagged; Hybrid: the PVID untagged, the rest tagged."""
|
||||
if not vids:
|
||||
return None
|
||||
if rule == "access":
|
||||
return _membership(vids)
|
||||
if rule == "trunk":
|
||||
return _membership((), vids)
|
||||
return _membership({pvid} & vids, vids - {pvid})
|
||||
|
||||
|
||||
def parse_ip(output):
|
||||
"""``ip → show``: management address with its VLAN, using the "Current" column."""
|
||||
def current(label):
|
||||
values = _field(output, label).split()
|
||||
return values[-1] if values else ""
|
||||
try:
|
||||
address = ipaddress.ip_interface(f"{current('IP Address')}/{current('IP Mask')}")
|
||||
except ValueError:
|
||||
return None, None
|
||||
vlan = current("VLAN ID")
|
||||
return (None if address.ip.is_unspecified else str(address)), (int(vlan) if vlan.isdigit() else None)
|
||||
|
||||
|
||||
def _lldp_modes(output):
|
||||
"""``lldp → show config``: ``{port: mode}``."""
|
||||
return {int(port): mode.lower() for port, mode in re.findall(
|
||||
r"(?im)^\s*(\d+)\s+(Enabled|Disabled|Rx[ _-]?only|Tx[ _-]?only)\b", clean_output(output or ""))}
|
||||
|
||||
|
||||
def not_receiving(output):
|
||||
"""Ports that drop received LLDP (mode Disabled or Tx only)."""
|
||||
return sorted(port for port, mode in _lldp_modes(output).items() if mode == "disabled" or mode.startswith("tx"))
|
||||
|
||||
|
||||
def lldp_receiving(output):
|
||||
"""``False`` when no port receives LLDP; ``True`` when unknown (no warning)."""
|
||||
modes = _lldp_modes(output)
|
||||
return not modes or len(not_receiving(output)) < len(modes)
|
||||
|
||||
|
||||
def parse_neighbors(output):
|
||||
"""``lldp → show info``: one block per neighbor, ``Label : value`` lines."""
|
||||
neighbors = []
|
||||
blocks = re.split(r"(?im)^(?=\s*Local Port\s*:)", clean_output(output or ""))
|
||||
for block in blocks:
|
||||
local = _field(block, "Local Port")
|
||||
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": 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": chassis,
|
||||
"protocol": "LLDP",
|
||||
})
|
||||
return neighbors
|
||||
|
||||
|
||||
def build_snapshot(outputs):
|
||||
status = parse_status(outputs.get("status", ""))
|
||||
config = parse_port_config(outputs.get("port_config", ""))
|
||||
names, members = parse_vlans(outputs.get("vlans", ""))
|
||||
vlan_ports = parse_vlan_ports(outputs.get("vlan_ports", ""))
|
||||
vlans_read = bool(members and vlan_ports)
|
||||
interfaces = []
|
||||
for number in sorted(set(status) | set(config)):
|
||||
vids = {vid for vid, ports in members.items() if number in ports}
|
||||
pvid, rule = vlan_ports.get(number, (1, "hybrid"))
|
||||
values = dict(status.get(number, {}))
|
||||
values["enabled"] = config.get(number, {}).get("enabled", values.get("enabled", True))
|
||||
interfaces.append(_interface(str(number), description=config.get(number, {}).get("description", ""),
|
||||
vlans=port_membership(vids, pvid, rule) if vlans_read else None,
|
||||
lag=None, **values))
|
||||
address, vlan = parse_ip(outputs.get("ip", ""))
|
||||
ip_addresses = []
|
||||
if address:
|
||||
name = f"vlan{vlan}" if vlan else "System"
|
||||
interfaces.append(_interface(name, connected=True, description="Management-Interface", virtual=True,
|
||||
ip_addresses=[address], vlans=None, lag=None))
|
||||
ip_addresses.append({"interface": name, "address": address})
|
||||
neighbors = parse_neighbors(outputs.get("neighbors", ""))
|
||||
by_name = {item["name"]: item for item in interfaces}
|
||||
for neighbor in neighbors:
|
||||
if neighbor["local_port"] in by_name:
|
||||
by_name[neighbor["local_port"]]["neighbor"] = neighbor
|
||||
system = outputs.get("system", "")
|
||||
mac = _field(system, "Host MAC Address")
|
||||
raw = {key: value for key, value in outputs.items() if key != "platform" and isinstance(value, str)}
|
||||
return {
|
||||
"platform": PLATFORM,
|
||||
"interfaces": interfaces,
|
||||
"ip_addresses": ip_addresses,
|
||||
"neighbors": neighbors,
|
||||
"lldp_neighbors": neighbors,
|
||||
"cdp_neighbors": [],
|
||||
"raw": raw,
|
||||
"vlans_read": vlans_read,
|
||||
# No configuration file over the CLI; the readable state serves as backup.
|
||||
"config_backup": "\n\n".join(f"### {mode} → {command}\n{clean_output(outputs.get(key, '')).strip()}"
|
||||
for mode, command, key in COMMANDS if outputs.get(key)),
|
||||
"vlan_names": names,
|
||||
"stack": [],
|
||||
"lldp_disabled": not lldp_receiving(outputs.get("lldp_config", "")),
|
||||
"lldp_enabled_automatically": bool(outputs.get("lldp_enabled_automatically")),
|
||||
"discovered_at": time.time(),
|
||||
"system": {"name": _field(system, "Device Name"), "model": _field(system, "Model Name"),
|
||||
"location": _field(system, "Location"), "mac": mac,
|
||||
"serial": _field(system, "Serial Number"), "firmware": _field(system, "Firmware Version")},
|
||||
}
|
||||
|
||||
|
||||
def reparse(snapshot):
|
||||
"""Rebuild a stored snapshot from its raw outputs with the current parsers.
|
||||
|
||||
Exchange files keep all LANCOM outputs, so parser fixes also apply to older exports.
|
||||
"""
|
||||
raw = snapshot.get("raw") or {}
|
||||
if snapshot.get("platform") != PLATFORM or not raw.get("status"):
|
||||
return snapshot
|
||||
rebuilt = build_snapshot(dict(raw, lldp_enabled_automatically=snapshot.get("lldp_enabled_automatically")))
|
||||
rebuilt["discovered_at"] = snapshot.get("discovered_at", rebuilt["discovered_at"])
|
||||
return rebuilt
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+404
-32
@@ -1,5 +1,8 @@
|
||||
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
import threading
|
||||
@@ -8,13 +11,14 @@ from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
from netbox_sync.core.netbox import assign_mac, related_id
|
||||
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
||||
|
||||
PLATFORMS = {
|
||||
"auto": "Automatisch erkennen",
|
||||
"aruba_cx": "Aruba CX (AOS-CX)",
|
||||
"aruba_aos": "ArubaOS-Switch / ProCurve",
|
||||
"hpe_comware": "HPE Comware",
|
||||
"lancom_sx3": "LANCOM LCOS SX 3.x (GS-23xx)",
|
||||
}
|
||||
|
||||
COMMANDS = {
|
||||
@@ -171,8 +175,9 @@ def _read_available(channel, timeout=20, initialize_session=False):
|
||||
return output
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
channel.send(command + "\n")
|
||||
def _run_cli_command(channel, command, timeout=20, newline="\n"):
|
||||
# LANCOM LCOS SX 3.x only executes a command on "\r" (like PuTTY's Enter); "\n" is just echoed.
|
||||
channel.send(command + newline)
|
||||
try:
|
||||
return _read_available(channel, timeout=timeout)
|
||||
except TimeoutError as error:
|
||||
@@ -257,25 +262,80 @@ def detect_platform(channel, banner):
|
||||
"""Identify the switch OS from prompt and ``show version`` output."""
|
||||
if COMWARE_PROMPT.search(banner):
|
||||
return "hpe_comware"
|
||||
_run_cli_command(channel, "no page")
|
||||
try:
|
||||
_run_cli_command(channel, "no page")
|
||||
except TimeoutError:
|
||||
# The command was only echoed: a CLI that needs "\r" as Enter (LANCOM LCOS SX 3.x).
|
||||
from netbox_sync.core import lancom
|
||||
channel.send("\r")
|
||||
_read_available(channel, timeout=20)
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
raise
|
||||
version = _run_cli_command(channel, "show version", timeout=30)
|
||||
if re.search(r"(?i)ArubaOS-CX|AOS-CX|\b[A-Z]{2}\.10\.\d+", version):
|
||||
return "aruba_cx"
|
||||
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
|
||||
return "aruba_aos"
|
||||
if CLI_ERROR.search(version):
|
||||
# LANCOM LCOS SX 3.x has no "show version"; its system information is in the "system" mode.
|
||||
from netbox_sync.core import lancom
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
display = _run_cli_command(channel, "display version", timeout=30)
|
||||
if re.search(r"(?i)Comware", display):
|
||||
return "hpe_comware"
|
||||
raise RuntimeError("Plattform konnte nicht automatisch erkannt werden – bitte im Switch-Dialog manuell wählen.")
|
||||
|
||||
|
||||
class _SessionRecorder:
|
||||
"""Channel wrapper that records everything sent and received for the raw data view."""
|
||||
|
||||
def __init__(self, channel, session):
|
||||
self._channel = channel
|
||||
self._session = session
|
||||
|
||||
def send(self, data):
|
||||
self._session.append(f"»» {data.strip()}\n" if data.strip() else "»» <Enter>\n")
|
||||
return self._channel.send(data)
|
||||
|
||||
def recv(self, size):
|
||||
data = self._channel.recv(size)
|
||||
self._session.append(data.decode("utf-8", errors="replace"))
|
||||
return data
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._channel, name)
|
||||
|
||||
|
||||
def session_text(session):
|
||||
"""The recorded CLI session without passwords, keys and communities."""
|
||||
return mask_config("".join(session))
|
||||
|
||||
|
||||
def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
|
||||
"""CLI outputs of a switch; ``outputs["session"]`` is the full recorded session.
|
||||
|
||||
On errors the session up to the failure is attached to the exception as
|
||||
``error.transcript`` so it can be shown as raw data.
|
||||
"""
|
||||
session = []
|
||||
try:
|
||||
outputs = _run_switch_commands(config, enable_lldp, known_hosts, log, session)
|
||||
except Exception as error:
|
||||
error.transcript = session_text(session)
|
||||
raise
|
||||
outputs["session"] = session_text(session)
|
||||
return outputs
|
||||
|
||||
|
||||
def _run_switch_commands(config, enable_lldp, known_hosts, log, session):
|
||||
platform = config.get("platform", "auto")
|
||||
if platform not in PLATFORMS:
|
||||
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
|
||||
client = _open_client(config, known_hosts, log)
|
||||
try:
|
||||
channel = client.invoke_shell(width=240, height=1000)
|
||||
channel = _SessionRecorder(client.invoke_shell(width=240, height=1000), session)
|
||||
try:
|
||||
banner = _read_available(channel, timeout=45, initialize_session=True)
|
||||
except TimeoutError as error:
|
||||
@@ -283,6 +343,10 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
|
||||
if platform == "auto":
|
||||
platform = detect_platform(channel, banner)
|
||||
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}")
|
||||
if platform == "lancom_sx3":
|
||||
from netbox_sync.core import lancom
|
||||
return dict(lancom.run_commands(channel, log, config.get("name", config["host"]), enable_lldp),
|
||||
platform=platform)
|
||||
pager_command, interface_command, neighbor_command = COMMANDS[platform]
|
||||
_run_cli_command(channel, pager_command)
|
||||
|
||||
@@ -608,8 +672,8 @@ def _parse_neighbor_table(output):
|
||||
# VLAN membership from the running configuration
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$")
|
||||
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode")
|
||||
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*[A-Za-z]?)(\d+)-(?:\1)?(\d+)$")
|
||||
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode|^\s*lag \d|^trunk\s|link-aggregation")
|
||||
|
||||
|
||||
def parse_vlan_list(text):
|
||||
@@ -776,6 +840,44 @@ def vlan_label(vlans, limit=64):
|
||||
return text
|
||||
|
||||
|
||||
def port_label(vlans, lag=None, limit=64):
|
||||
"""NetBox label of a port: its VLANs plus its LAG, e.g. ``10,20 (LAG 1)``."""
|
||||
number = re.search(r"(\d+)$", lag or "")
|
||||
suffix = f"(LAG {number.group(1)})" if number else ""
|
||||
text = vlan_label(vlans, limit - len(suffix) - 1 if suffix else limit)
|
||||
return f"{text} {suffix}".strip()
|
||||
|
||||
|
||||
def parse_lags(config, platform):
|
||||
"""LAG of every member port as ``{interface_key(port): LAG name}``."""
|
||||
lags = {}
|
||||
if platform == "aruba_aos":
|
||||
# "trunk 49-50 trk1 lacp" is a global line.
|
||||
for match in re.finditer(r"(?im)^trunk\s+(\S+)\s+trk(\d+)\b", clean_output(config or "")):
|
||||
for port in _expand_ports(match.group(1)):
|
||||
lags[interface_key(port)] = f"Trk{match.group(2)}"
|
||||
return lags
|
||||
member = {"aruba_cx": (re.compile(r"(?i)^lag (\d+)$"), "lag{}"),
|
||||
"hpe_comware": (re.compile(r"(?i)^port link-aggregation group (\d+)$"), "Bridge-Aggregation{}")}
|
||||
if platform not in member:
|
||||
return lags
|
||||
pattern, name = member[platform]
|
||||
for match, body in _config_blocks(config or "", re.compile(r"^interface\s+(\S+)\s*$", re.I)):
|
||||
group = next((found.group(1) for found in map(pattern.match, body) if found), None)
|
||||
if group:
|
||||
lags[interface_key(match.group(1))] = name.format(group)
|
||||
return lags
|
||||
|
||||
|
||||
# Values after these words are removed from configuration backups.
|
||||
_SECRET = re.compile(r"(?i)\b(password|secret|key|community|ciphertext|plaintext|psk|passphrase)\b(\s+).*$")
|
||||
|
||||
|
||||
def mask_config(config):
|
||||
"""Running configuration without passwords, keys and SNMP communities."""
|
||||
return "\n".join(_SECRET.sub(r"\1\2<entfernt>", line) for line in clean_output(config).splitlines()).strip()
|
||||
|
||||
|
||||
def _vlan_config_excerpt(config):
|
||||
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
|
||||
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
|
||||
@@ -824,10 +926,18 @@ def parse_stack(config, platform, interfaces=()):
|
||||
|
||||
|
||||
def build_snapshot(outputs, platform):
|
||||
if platform == "lancom_sx3":
|
||||
from netbox_sync.core import lancom
|
||||
return lancom.build_snapshot(outputs)
|
||||
interfaces = parse_interfaces(outputs["interfaces"], platform)
|
||||
vlans = parse_vlans(outputs.get("config", ""), platform)
|
||||
lags = parse_lags(outputs.get("config", ""), platform)
|
||||
for interface in interfaces:
|
||||
interface["vlans"] = vlans.get(interface_key(interface["name"]))
|
||||
interface["lag"] = lags.get(interface_key(interface["name"]))
|
||||
if interface["lag"] and not interface["vlans"]:
|
||||
# Aruba CX/Comware: the VLANs are configured on the LAG and apply to its member ports.
|
||||
interface["vlans"] = vlans.get(interface_key(interface["lag"]))
|
||||
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
|
||||
lldp_neighbors = parse_neighbors(outputs["neighbors"])
|
||||
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
|
||||
@@ -863,6 +973,7 @@ def build_snapshot(outputs, platform):
|
||||
"raw": {**{key: value for key, value in outputs.items() if key != "config"},
|
||||
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
|
||||
"vlans_read": bool(outputs.get("config")),
|
||||
"config_backup": mask_config(outputs["config"]) if outputs.get("config") else "",
|
||||
"vlan_names": parse_vlan_names(outputs.get("config", "")),
|
||||
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
|
||||
"lldp_disabled": outputs.get("lldp_disabled", False),
|
||||
@@ -885,6 +996,8 @@ def suggest_platform(*texts):
|
||||
text = " ".join(str(value or "") for value in texts).casefold()
|
||||
if not text.strip():
|
||||
return "auto"
|
||||
if re.search(r"lancom|\bgs-23\d\d", text):
|
||||
return "lancom_sx3"
|
||||
if re.search(r"comware|h3c|\b(?:19[0-9]0|51[234]0|55[01]0|57[01]0|59[0-9]0|75\d\d|10500|12500|12900)\b", text):
|
||||
return "hpe_comware"
|
||||
if re.search(r"aos-?cx|arubaos-?cx|\bcx\b|\b(?:4100i|6000|6100|6200[fm]?|6300[fm]?|6400|8100|8320|8325|8360|8400|9300|10000)\b", text):
|
||||
@@ -982,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")
|
||||
|
||||
@@ -1307,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:
|
||||
@@ -1357,7 +1486,7 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
"interfaces": [
|
||||
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
|
||||
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id,
|
||||
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
|
||||
"vlan_label": port_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)), item.get("lag"))}
|
||||
for item in snapshot["interfaces"] if owners[item["name"]] is not None
|
||||
for record, method in [matches[item["name"]]]
|
||||
],
|
||||
@@ -1410,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])
|
||||
@@ -1425,10 +1557,28 @@ 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]
|
||||
return None
|
||||
# Access points and phones often report their MAC address as port ID.
|
||||
mac = normalize_mac(neighbor.get("remote_port"))
|
||||
if mac:
|
||||
found = [record for record in records.values()
|
||||
if normalize_mac(getattr(record, "mac_address", None)) == mac]
|
||||
if len(found) == 1:
|
||||
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 _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
|
||||
@@ -1515,8 +1665,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
|
||||
report["errors"].append(f"Prefix {network}: {error}")
|
||||
|
||||
|
||||
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
|
||||
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report, sites=None):
|
||||
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved.
|
||||
|
||||
``sites`` receives ``{VLAN ID: (site ID or None, name)}`` for the site check of the ports.
|
||||
"""
|
||||
sites = {} if sites is None else sites
|
||||
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
|
||||
approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"}
|
||||
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
|
||||
@@ -1524,6 +1678,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
for vid, (record, method, name) in matches.items():
|
||||
if record is not None:
|
||||
present[vid] = record.id
|
||||
sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid))
|
||||
continue
|
||||
if method != "new" or vid not in approved:
|
||||
continue
|
||||
@@ -1536,6 +1691,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
||||
if site_id:
|
||||
payload["site"] = site_id
|
||||
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
|
||||
sites[vid] = (site_id, name)
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"VLAN {vid}: {error}")
|
||||
return present
|
||||
@@ -1577,13 +1733,194 @@ def _new_report():
|
||||
return {
|
||||
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
|
||||
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
|
||||
"cables_created": 0, "cables_skipped": 0,
|
||||
"cables_created": 0, "cables_updated": 0, "cables_skipped": 0,
|
||||
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
|
||||
"changes": [], "errors": [], "notes": [],
|
||||
}
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
|
||||
def _sync_switch_stack(nb, device, members, dry_run, report):
|
||||
"""Fill in the switch stack of the optional NetBox Utilities plugin.
|
||||
|
||||
The switch's device is the stack switch, the other member devices are
|
||||
added to it; members entered by hand stay. Without the plugin nothing happens.
|
||||
"""
|
||||
others = {member.id: member for member in members.values() if member is not None and member.id != device.id}
|
||||
if not others:
|
||||
return
|
||||
try:
|
||||
endpoint = nb.plugins.utilities.switch_stacks
|
||||
stacks = list(endpoint.filter(device_id=device.id))
|
||||
except AttributeError:
|
||||
return
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) != 404:
|
||||
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||
return
|
||||
stack = stacks[0] if stacks else None
|
||||
current = [getattr(item, "id", item) for item in (getattr(stack, "members", None) or [])]
|
||||
missing = [member_id for member_id in others if member_id not in current]
|
||||
if not missing:
|
||||
return
|
||||
names = ", ".join(others[member_id].name for member_id in missing)
|
||||
report["changes"].append(f"Switch-Stack {device.name}: Mitglieder {names} eintragen (NetBox Utilities)"
|
||||
if stack else f"Switch-Stack {device.name} neu mit Mitgliedern {names} (NetBox Utilities)")
|
||||
if dry_run:
|
||||
return
|
||||
try:
|
||||
if stack:
|
||||
stack.update({"members": current + missing})
|
||||
else:
|
||||
endpoint.create({"device": device.id, "members": missing})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||
|
||||
|
||||
def _vlans_for_site(vlan_ids, vlan_sites, site_id, owner, reported, report):
|
||||
"""VLANs a port of ``owner`` may use: NetBox only allows global VLANs or VLANs of the device's site.
|
||||
|
||||
Other VLANs stay in the label; each is reported once per device.
|
||||
"""
|
||||
allowed = {}
|
||||
for vid, netbox_id in vlan_ids.items():
|
||||
vlan_site, name = vlan_sites.get(vid, (None, str(vid)))
|
||||
if vlan_site in (None, site_id):
|
||||
allowed[vid] = netbox_id
|
||||
elif (owner.id, vid) not in reported:
|
||||
reported.add((owner.id, vid))
|
||||
report["notes"].append(f"VLAN {vid} „{name}“ gehört zu einem anderen Standort als {owner.name} – "
|
||||
f"nur im Label vermerkt, nicht am Port zugewiesen (VLAN global machen, "
|
||||
f"um es zuzuweisen)")
|
||||
return allowed
|
||||
|
||||
|
||||
def _sync_lag_members(snapshot, owners, records, dry_run, report):
|
||||
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
|
||||
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
|
||||
for interface in snapshot["interfaces"]:
|
||||
key, lag_key = interface_key(interface["name"]), interface_key(interface.get("lag") or "")
|
||||
if not interface.get("lag") or key not in records or lag_key not in records:
|
||||
continue
|
||||
record, lag_record = records[key], records[lag_key]
|
||||
owner, lag_owner = owners[interface["name"]], owners[names[lag_key]]
|
||||
if owner.id != lag_owner.id:
|
||||
# NetBox only allows a LAG of the same device (or virtual chassis).
|
||||
report["notes"].append(f"Interface {interface['name']}: LAG {names[lag_key]} liegt auf {lag_owner.name} "
|
||||
f"– nur im Label vermerkt")
|
||||
continue
|
||||
if record and lag_record and related_id(record, "lag") == lag_record.id:
|
||||
continue
|
||||
report["changes"].append(f"Interface {record.name if record else interface['name']}: LAG {names[lag_key]}")
|
||||
if not dry_run and record and lag_record:
|
||||
try:
|
||||
record.update({"lag": lag_record.id})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}")
|
||||
|
||||
|
||||
def _backup_config(nb, device, snapshot, dry_run, report):
|
||||
"""Attach the running configuration to the device (optional netbox-attachments plugin).
|
||||
|
||||
A new attachment is only added when the configuration of this device changed
|
||||
since the last backup; the hash in the description identifies it.
|
||||
"""
|
||||
original = snapshot.get("config_file")
|
||||
if original:
|
||||
# Backup file from the switch's web UI (e.g. D-Link config.bin), attached unchanged.
|
||||
content = base64.b64decode(original["data"])
|
||||
extension = Path(original.get("name") or "config.bin").suffix or ".bin"
|
||||
content_type = "application/octet-stream"
|
||||
else:
|
||||
config = snapshot.get("config_backup")
|
||||
if not config:
|
||||
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
|
||||
return
|
||||
content, extension, content_type = config.encode("utf-8"), ".txt", "text/plain"
|
||||
digest = hashlib.sha256(f"{device.id}\n".encode("utf-8") + content).hexdigest()[:16]
|
||||
try:
|
||||
app = nb.plugins.netbox_attachments
|
||||
known = [item for item in app.netbox_attachments.filter(q=digest)
|
||||
if digest in (getattr(item, "description", "") or "")]
|
||||
except AttributeError:
|
||||
return
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) == 404:
|
||||
report["notes"].append("Konfigurations-Backup übersprungen: Plugin netbox-attachments ist nicht installiert")
|
||||
else:
|
||||
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||
return
|
||||
if known:
|
||||
return
|
||||
stamp = time.strftime("%Y-%m-%d %H-%M", time.localtime(snapshot.get("discovered_at") or time.time()))
|
||||
name = f"Running-Config {device.name} {stamp}"
|
||||
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
|
||||
if dry_run:
|
||||
return
|
||||
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + extension
|
||||
try:
|
||||
attachment = app.netbox_attachments.create({
|
||||
"name": name, "description": f"Running-Config, SHA-256 {digest}",
|
||||
# Older plugin versions keep the parent on the attachment itself.
|
||||
"object_type": "dcim.device", "object_id": device.id,
|
||||
"file": (filename, io.BytesIO(content), content_type),
|
||||
})
|
||||
if hasattr(attachment, "assignments"):
|
||||
# Newer plugin versions assign attachments to objects separately.
|
||||
app.netbox_attachment_assignments.create({"attachment": attachment.id, "object_type": "dcim.device",
|
||||
"object_id": device.id})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||
|
||||
|
||||
def _term(value, key):
|
||||
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
|
||||
|
||||
|
||||
def _termination_text(termination):
|
||||
item = _term(termination, "object") or {}
|
||||
owner = _term(_term(item, "device") or {}, "name")
|
||||
return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id"))
|
||||
|
||||
|
||||
def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
|
||||
"""Compare an existing cable of a switch port with its LLDP/CDP neighbor.
|
||||
|
||||
NetBox is the source of truth: a different far end is only reported unless
|
||||
``update_cables`` is set. Cables to patch panels (front/rear ports) or with
|
||||
several terminations are never touched.
|
||||
"""
|
||||
cable = nb.dcim.cables.get(related_id(local, "cable"))
|
||||
if cable is None:
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])]
|
||||
local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None)
|
||||
far = sides[1] if local_side is sides[0] else sides[0]
|
||||
if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface":
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
if _term(far[0], "object_id") == remote.id:
|
||||
report["cables_skipped"] += 1
|
||||
return
|
||||
old = _termination_text(far[0])
|
||||
remote_cable = related_id(remote, "cable")
|
||||
if not update_cables or (remote_cable and remote_cable != cable.id):
|
||||
reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables
|
||||
else "„Bestehende Kabel anpassen“ ist aus")
|
||||
report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})")
|
||||
return
|
||||
report["cables_updated"] += 1
|
||||
report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}")
|
||||
if not dry_run:
|
||||
cable.update({
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||
})
|
||||
remote.cable = cable
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||
backup_config=False, update_cables=False):
|
||||
"""Write a discovery snapshot to NetBox.
|
||||
|
||||
With ``dry_run`` nothing is written; the returned report lists what would
|
||||
@@ -1600,7 +1937,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
device_id = device.id
|
||||
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
|
||||
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
|
||||
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
|
||||
vlan_sites = {}
|
||||
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report, vlan_sites)
|
||||
ignored = ignored_vlans(config.get("vlan_map"))
|
||||
members = stack_devices(nb, config, snapshot, device)
|
||||
owners = _interface_owners(snapshot, members, device)
|
||||
@@ -1611,7 +1949,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
skipped = sum(1 for name, owner in owners.items() if owner is None
|
||||
and stack_member(name, snapshot.get("platform")) == member)
|
||||
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
||||
records = {}
|
||||
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||
records, foreign = {}, set()
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
@@ -1621,7 +1960,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
record, method = matches[interface["name"]]
|
||||
where = f" auf {owner.name}" if owner.id != device_id else ""
|
||||
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
||||
label = vlan_label(port["vlans"])
|
||||
label = port_label(port["vlans"], interface.get("lag"))
|
||||
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
|
||||
try:
|
||||
if record:
|
||||
changes = {}
|
||||
@@ -1631,7 +1971,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
# routed ports and snapshots without configuration.
|
||||
if label and (getattr(record, "label", "") or "") != label:
|
||||
changes["label"] = label
|
||||
changes.update(_vlan_assignment(port, vlan_ids, record))
|
||||
changes.update(_vlan_assignment(port, owner_vlans, record))
|
||||
if changes:
|
||||
report["interfaces_updated"] += 1
|
||||
texts = []
|
||||
@@ -1656,7 +1996,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
}
|
||||
if label:
|
||||
payload["label"] = label
|
||||
payload.update(_vlan_assignment(port, vlan_ids))
|
||||
payload.update(_vlan_assignment(port, owner_vlans))
|
||||
if interface.get("description"):
|
||||
payload["description"] = interface["description"][:200]
|
||||
report["interfaces_created"] += 1
|
||||
@@ -1670,6 +2010,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Interface {interface['name']}: {error}")
|
||||
|
||||
_sync_lag_members(snapshot, owners, records, dry_run, report)
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
if key not in records:
|
||||
@@ -1715,30 +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 not None and getattr(local, "cable", None):
|
||||
report["cables_skipped"] += 1
|
||||
continue
|
||||
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)
|
||||
if not remote or getattr(remote, "cable", None):
|
||||
report["cables_skipped"] += 1
|
||||
# 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:
|
||||
skip(f"lokaler Port hat bereits ein Kabel, Schnittstelle „{neighbor.get('remote_port')}“ "
|
||||
f"auf {remote_device.name} nicht gefunden")
|
||||
continue
|
||||
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}")
|
||||
@@ -1752,6 +2122,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
remote.cable = True # avoid a second cable from the reverse direction
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
|
||||
+93
-14
@@ -1,6 +1,7 @@
|
||||
"""Long-running operations started from the UI. Everything here runs in background tasks."""
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
@@ -8,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 exchange, 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,
|
||||
@@ -319,6 +321,7 @@ class Actions:
|
||||
return
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, data["switches"], lambda: uuid.uuid4().hex)
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
snapshot = lancom.reparse(snapshot)
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Datei · " + describe_snapshot(snapshot))
|
||||
if added:
|
||||
@@ -328,6 +331,50 @@ class Actions:
|
||||
logger("switch").log(25, "%s", text)
|
||||
self.window.toast(text)
|
||||
|
||||
def import_switch_backups(self):
|
||||
"""One-off import of D-Link/Linksys configuration backups instead of SSH."""
|
||||
if self.state.profile is None:
|
||||
return
|
||||
paths, _filter = QFileDialog.getOpenFileNames(self.window, "Switch-Backup importieren", "",
|
||||
backups.FILE_FILTER)
|
||||
if not paths:
|
||||
return
|
||||
devices = {row["name"].casefold(): row for row in self.state.netbox_devices or []}
|
||||
items, failures = [], []
|
||||
for path in paths:
|
||||
name = Path(path).name
|
||||
try:
|
||||
switch, snapshot = backups.parse_backup(Path(path).read_bytes(), name)
|
||||
except (OSError, backups.BackupError) as error:
|
||||
failures.append(f"{name}: {error}")
|
||||
continue
|
||||
switch["name"] = switch["name"] or Path(path).stem
|
||||
device = devices.get(switch["name"].casefold())
|
||||
items.append({"switch": {"name": device["name"] if device else switch["name"],
|
||||
"device_id": device["id"] if device else None,
|
||||
"platform": switch["platform"], "host": switch["host"], "port": 22},
|
||||
"snapshot": snapshot, "file": name})
|
||||
if items:
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, items, lambda: uuid.uuid4().hex)
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Backup · " + describe_snapshot(snapshot))
|
||||
stored = by_id.get(switch_id)
|
||||
if stored and stored.get("platform", "auto") == "auto":
|
||||
stored["platform"] = snapshot["platform"]
|
||||
self.state.touch()
|
||||
if added:
|
||||
self.state.touch()
|
||||
self.state.switches_changed.emit()
|
||||
names = ", ".join(item["switch"]["name"] for item in items)
|
||||
logger("switch").log(25, "Backup importiert: %s", names)
|
||||
self.window.toast(f"{len(items)} Switch-Backup(s) geladen" + (f", {added} neu im Profil" if added else "")
|
||||
+ " – jetzt „Nach NetBox übertragen“ wählen")
|
||||
if failures:
|
||||
widgets.message(self.window, "Nicht alle Backups gelesen",
|
||||
f"{len(items)} von {len(paths)} Datei(en) importiert.", "warning", "\n".join(failures))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Switches
|
||||
# ------------------------------------------------------------------
|
||||
@@ -358,7 +405,8 @@ class Actions:
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def discover_switches(self, switches):
|
||||
switches = [dict(switch) for switch in switches if switch.get("enabled", True)]
|
||||
switches = [dict(switch) for switch in switches if switch.get("enabled", True)
|
||||
and switch.get("platform") not in backups.BACKUP_PLATFORMS]
|
||||
if not switches:
|
||||
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
|
||||
return
|
||||
@@ -367,7 +415,7 @@ class Actions:
|
||||
known_hosts = known_hosts_path()
|
||||
|
||||
def work(ctx):
|
||||
snapshots, failures = {}, {}
|
||||
snapshots, failures, transcripts = {}, {}, {}
|
||||
ctx.progress(0, len(switches), "Verbinde …")
|
||||
with ThreadPoolExecutor(max_workers=min(parallel, len(switches))) as pool:
|
||||
futures = {}
|
||||
@@ -395,15 +443,22 @@ class Actions:
|
||||
"Stack-Mitglieder werden über den Stack-Master ausgelesen und können aus "
|
||||
"dem Profil entfernt werden.")
|
||||
failures[switch["id"]] = problem
|
||||
if getattr(error, "transcript", ""):
|
||||
transcripts[switch["id"]] = error.transcript
|
||||
ctx.log(f"{switch['name']}: {problem}", "error")
|
||||
ctx.progress(done, len(switches), switch["name"])
|
||||
if ctx.cancelled:
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
return snapshots, failures
|
||||
return snapshots, failures, transcripts
|
||||
|
||||
def success(result):
|
||||
snapshots, failures = result
|
||||
snapshots, failures, transcripts = result
|
||||
for switch_id in snapshots:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
for switch_id in failures:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.update(transcripts)
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
platform_updates = 0
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
@@ -432,6 +487,8 @@ class Actions:
|
||||
if not self.require_netbox_config():
|
||||
return
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
backup = self.state.settings.get("backup_config")
|
||||
update_cables = create_cables and bool(self.state.settings.get("update_cables"))
|
||||
# VLAN and network decisions are shared by all switches of the profile.
|
||||
vlan_map = self.state.profile.setdefault("vlan_map", {})
|
||||
network_map = self.state.profile.setdefault("network_map", {})
|
||||
@@ -469,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}
|
||||
@@ -498,7 +556,8 @@ class Actions:
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
ctx.log(f"{switch['name']}: berechne Änderungen …")
|
||||
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
|
||||
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True,
|
||||
backup_config=backup, update_cables=update_cables)))
|
||||
return nb, reports
|
||||
|
||||
def show_preview(result):
|
||||
@@ -509,22 +568,26 @@ class Actions:
|
||||
# follow-up task is not rejected as "still busy".
|
||||
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
||||
if dialog.exec():
|
||||
self._apply_switch_sync(nb, items, create_cables, log)
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log):
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
|
||||
def work(ctx):
|
||||
reports = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.check_cancelled()
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False,
|
||||
backup_config=self.state.settings.get("backup_config"),
|
||||
update_cables=update_cables)
|
||||
for error in report["errors"]:
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
for note in report.get("notes", []):
|
||||
ctx.log(f"{switch['name']}: {note}", "warning")
|
||||
reports.append((switch, report))
|
||||
return reports
|
||||
|
||||
@@ -582,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
|
||||
@@ -621,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
+97
-27
@@ -546,9 +546,14 @@ class SyncPreviewDialog(_Dialog):
|
||||
items.append((f"{totals[key]} {text}", "info"))
|
||||
if create_cables:
|
||||
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
|
||||
if totals.get("cables_updated"):
|
||||
items.append((f"{totals['cables_updated']} Kabel angepasst", "error"))
|
||||
errors = sum(len(report["errors"]) for _switch, report in reports)
|
||||
if errors:
|
||||
items.append((f"{errors} Probleme", "error"))
|
||||
notes = sum(len(report.get("notes", [])) for _switch, report in reports)
|
||||
if notes:
|
||||
items.append((f"{notes} Hinweis(e)", "warning"))
|
||||
for text, kind in items:
|
||||
summary.addWidget(Badge(text, kind))
|
||||
summary.addStretch(1)
|
||||
@@ -564,7 +569,9 @@ class SyncPreviewDialog(_Dialog):
|
||||
changes = report["changes"]
|
||||
total_changes += len(changes)
|
||||
unchanged = report["interfaces_unchanged"]
|
||||
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
|
||||
hints = len(report.get("notes", []))
|
||||
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"
|
||||
+ (f", {hints} Hinweis(e)" if hints else "")])
|
||||
top.setIcon(0, icon("network", theme.color("accent")))
|
||||
font = top.font(0)
|
||||
font.setBold(True)
|
||||
@@ -593,7 +600,7 @@ class SyncPreviewDialog(_Dialog):
|
||||
top.addChild(member)
|
||||
member.setExpanded(True)
|
||||
tree.addTopLevelItem(top)
|
||||
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
|
||||
top.setExpanded(len(reports) == 1 or bool(report["errors"]) or bool(hints))
|
||||
self.root.addWidget(tree, 1)
|
||||
if total_changes == 0:
|
||||
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
|
||||
@@ -612,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.",
|
||||
@@ -709,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()
|
||||
@@ -720,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 --------------------------------------------------------------
|
||||
@@ -952,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.
|
||||
@@ -989,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"]
|
||||
@@ -997,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()
|
||||
@@ -1031,17 +1086,22 @@ class RawDataDialog(_Dialog):
|
||||
SECTIONS = {
|
||||
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
|
||||
# LANCOM LCOS SX 3.x
|
||||
"system": "System", "status": "Port-Status", "port_config": "Port-Konfiguration", "vlans": "VLANs",
|
||||
"vlan_ports": "VLAN-Ports", "ip": "IP", "lldp_config": "LLDP-Konfiguration",
|
||||
"session": "Sitzung",
|
||||
}
|
||||
|
||||
def __init__(self, parent, items, selected_id=None):
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche.",
|
||||
width=900)
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche. "
|
||||
"„Sitzung“ zeigt den kompletten Ablauf, bei Fehlern bis zum Abbruch.", width=900)
|
||||
self.resize(1040, 700)
|
||||
self.items = items
|
||||
top = QHBoxLayout()
|
||||
self.switch_combo = QComboBox()
|
||||
for switch, _snapshot in items:
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']})", switch["id"])
|
||||
for switch, snapshot in items:
|
||||
suffix = " – abgebrochen" if snapshot.get("failed") else ""
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']}){suffix}", switch["id"])
|
||||
if selected_id:
|
||||
self.switch_combo.setCurrentIndex(max(0, self.switch_combo.findData(selected_id)))
|
||||
top.addWidget(self.switch_combo, 1)
|
||||
@@ -1049,14 +1109,6 @@ class RawDataDialog(_Dialog):
|
||||
top.addWidget(button("Alles speichern …", "download", on_click=self.save_all))
|
||||
self.root.addLayout(top)
|
||||
self.tabs = QTabWidget()
|
||||
self.editors = {}
|
||||
for key, title in self.SECTIONS.items():
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
self.tabs.addTab(editor, title)
|
||||
self.editors[key] = editor
|
||||
self.root.addWidget(self.tabs, 1)
|
||||
close = button("Schließen", variant="primary", on_click=self.accept)
|
||||
self.root.addWidget(close, 0, Qt.AlignRight)
|
||||
@@ -1066,15 +1118,32 @@ class RawDataDialog(_Dialog):
|
||||
def _current(self):
|
||||
return self.items[max(0, self.switch_combo.currentIndex())]
|
||||
|
||||
@classmethod
|
||||
def _sections(cls, raw):
|
||||
"""Known outputs in a fixed order, unknown ones after them, the session last."""
|
||||
keys = [key for key in cls.SECTIONS if key != "session" and key in raw]
|
||||
keys += sorted(key for key in raw if key not in cls.SECTIONS and isinstance(raw[key], str))
|
||||
keys += ["session"] if "session" in raw else []
|
||||
return [(key, cls.SECTIONS.get(key, key)) for key in keys] or [("", "Rohdaten")]
|
||||
|
||||
def show_switch(self, *_args):
|
||||
_switch, snapshot = self._current()
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, editor in self.editors.items():
|
||||
self.tabs.clear()
|
||||
for key, title in self._sections(raw):
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
editor.setPlainText(str(raw.get(key) or "(keine Ausgabe)"))
|
||||
self.tabs.addTab(editor, title)
|
||||
if snapshot.get("failed"):
|
||||
self.tabs.setCurrentIndex(self.tabs.count() - 1)
|
||||
|
||||
def copy_current(self):
|
||||
editor = self.tabs.currentWidget()
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
if editor is not None:
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
|
||||
def save_all(self):
|
||||
path, _filter = QFileDialog.getSaveFileName(self, "SSH-Rohdaten speichern", "ssh-rohdaten.txt", "Text (*.txt)")
|
||||
@@ -1082,9 +1151,10 @@ class RawDataDialog(_Dialog):
|
||||
return
|
||||
sections = []
|
||||
for switch, snapshot in self.items:
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}) {'=' * 20}")
|
||||
suffix = " (abgebrochen)" if snapshot.get("failed") else ""
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}){suffix} {'=' * 20}")
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, title in self.SECTIONS.items():
|
||||
for key, title in self._sections(raw):
|
||||
sections.extend((f"\n--- {title.upper()} ---", str(raw.get(key) or "(keine Ausgabe)")))
|
||||
with open(path, "w", encoding="utf-8") as stream:
|
||||
stream.write("\n".join(sections))
|
||||
@@ -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"/>',
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
+155
-13
@@ -1,9 +1,13 @@
|
||||
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,
|
||||
@@ -15,6 +19,7 @@ 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
|
||||
@@ -22,7 +27,18 @@ from netbox_sync.ui.client_help import ClientHelpDialog
|
||||
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 +71,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 +106,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 +156,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 +186,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, "
|
||||
@@ -250,6 +275,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 +301,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 +314,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()
|
||||
@@ -416,12 +554,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 +576,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()
|
||||
@@ -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")
|
||||
@@ -4,7 +4,8 @@ import uuid
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
|
||||
|
||||
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
|
||||
from netbox_sync.core.backups import BACKUP_PLATFORMS
|
||||
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, port_label, without_vlans
|
||||
from netbox_sync.ui import widgets
|
||||
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
|
||||
from netbox_sync.ui.icons import icon
|
||||
@@ -23,7 +24,8 @@ def _speed(value):
|
||||
class SwitchesPage(Page):
|
||||
title = "Switche"
|
||||
subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung "
|
||||
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware.")
|
||||
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware und LANCOM LCOS SX 3.x – D-Link und Linksys "
|
||||
"per Backup-Datei.")
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
@@ -36,7 +38,7 @@ class SwitchesPage(Page):
|
||||
self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover))
|
||||
columns = [
|
||||
Column("name", "NetBox-Gerät", 200),
|
||||
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform"), row.get("platform"))),
|
||||
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform")) or BACKUP_PLATFORMS.get(row.get("platform"), row.get("platform"))),
|
||||
Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"),
|
||||
Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein",
|
||||
color=lambda row: None if row.get("enabled", True) else "text_faint"),
|
||||
@@ -81,6 +83,11 @@ class SwitchesPage(Page):
|
||||
self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
|
||||
tooltip="Ausleseergebnisse aus einer im Offline-Modus "
|
||||
"erstellten Exportdatei (JSON) laden."))
|
||||
self.backup_button = result_card.add_action(button(
|
||||
"Backup importieren …", "folder", on_click=self.actions.import_switch_backups,
|
||||
tooltip="Einmal-Import ohne SSH: Konfigurations-Backup eines D-Link- (DGS-1210, config.bin) oder "
|
||||
"Linksys-Switches (LGS, *.cfg) laden. Der Switch wird über seinen Hostnamen dem NetBox-Gerät "
|
||||
"zugeordnet."))
|
||||
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
|
||||
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
|
||||
on_click=self.sync))
|
||||
@@ -93,13 +100,30 @@ class SwitchesPage(Page):
|
||||
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
|
||||
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
|
||||
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
|
||||
self.update_cables_option = checkbox(
|
||||
"Bestehende Kabel anpassen",
|
||||
tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, "
|
||||
"wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie "
|
||||
"verändert. Ohne diese Option werden Abweichungen nur gemeldet.")
|
||||
self.backup_option = checkbox("Konfiguration als Anhang sichern",
|
||||
tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät "
|
||||
"(Plugin netbox-attachments). Passwörter, Schlüssel und Communities "
|
||||
"werden entfernt; ein neuer Anhang entsteht nur bei Änderungen.")
|
||||
# Two rows: filters for the table, then the options of the NetBox transfer.
|
||||
filters.setSpacing(12)
|
||||
filters.addWidget(self.search, 2)
|
||||
filters.addWidget(self.switch_filter, 1)
|
||||
filters.addWidget(self.only_up)
|
||||
filters.addWidget(self.only_neighbors)
|
||||
filters.addStretch(1)
|
||||
filters.addWidget(self.cables_option)
|
||||
result_card.add(filters)
|
||||
options = QHBoxLayout()
|
||||
options.setSpacing(16)
|
||||
options.addWidget(label("Übertragen:", muted=True))
|
||||
options.addWidget(self.cables_option)
|
||||
options.addWidget(self.update_cables_option)
|
||||
options.addWidget(self.backup_option)
|
||||
options.addStretch(1)
|
||||
result_card.add(options)
|
||||
result_columns = [
|
||||
Column("switch", "Switch", 140),
|
||||
Column("name", "Schnittstelle", 150),
|
||||
@@ -108,8 +132,8 @@ class SwitchesPage(Page):
|
||||
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
|
||||
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
|
||||
sort=lambda row: row.get("speed_mbps") or 0),
|
||||
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
|
||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
|
||||
Column("vlans", "VLANs", 110, value=lambda row: port_label(without_vlans(
|
||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))), row.get("lag"))),
|
||||
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
|
||||
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
|
||||
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
|
||||
@@ -144,6 +168,9 @@ class SwitchesPage(Page):
|
||||
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
|
||||
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
|
||||
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
|
||||
self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
|
||||
self.update_cables_option.toggled.connect(self._toggle_update_cables)
|
||||
self.cables_option.toggled.connect(self.update_cables_option.setEnabled)
|
||||
self.state.switches_changed.connect(self.refresh)
|
||||
self.state.profile_switched.connect(self.refresh)
|
||||
self.state.profile_edited.connect(self.refresh_switches)
|
||||
@@ -155,10 +182,25 @@ class SwitchesPage(Page):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_settings(self):
|
||||
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
|
||||
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"),
|
||||
(self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")):
|
||||
widget.blockSignals(True)
|
||||
widget.setChecked(bool(self.state.settings.get(key)))
|
||||
widget.blockSignals(False)
|
||||
self.update_cables_option.setEnabled(self.cables_option.isChecked())
|
||||
|
||||
def _toggle_update_cables(self, value):
|
||||
if value and not widgets.confirm(
|
||||
self.window, "Bestehende Kabel anpassen?",
|
||||
"NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht "
|
||||
"zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox "
|
||||
"verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.",
|
||||
ok_text="Einschalten", destructive=True):
|
||||
self.update_cables_option.blockSignals(True)
|
||||
self.update_cables_option.setChecked(False)
|
||||
self.update_cables_option.blockSignals(False)
|
||||
return
|
||||
self.state.update_settings(update_cables=value)
|
||||
|
||||
def _status_text(self, row):
|
||||
status = self.state.switch_status.get(row["id"])
|
||||
@@ -248,11 +290,13 @@ class SwitchesPage(Page):
|
||||
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data
|
||||
else "Nach NetBox übertragen …")
|
||||
self.cables_option.setVisible(not offline)
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots or self.state.switch_failed_raw),
|
||||
"Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
|
||||
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
|
||||
self.add_button.setEnabled(not busy)
|
||||
self.file_button.setEnabled(not busy)
|
||||
self.backup_button.setEnabled(not busy)
|
||||
|
||||
def set_busy(self, busy):
|
||||
self._update_buttons()
|
||||
@@ -306,6 +350,7 @@ class SwitchesPage(Page):
|
||||
if dialog.result.get("device_id") != current.get("device_id"):
|
||||
self.state.switch_snapshots.pop(current["id"], None)
|
||||
self.state.switch_status.pop(current["id"], None)
|
||||
self.state.switch_failed_raw.pop(current["id"], None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -323,6 +368,7 @@ class SwitchesPage(Page):
|
||||
for switch_id in ids:
|
||||
self.state.switch_snapshots.pop(switch_id, None)
|
||||
self.state.switch_status.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -352,7 +398,11 @@ class SwitchesPage(Page):
|
||||
|
||||
def show_raw(self):
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in self.state.switch_snapshots.items() if key in by_id]
|
||||
raw = dict(self.state.switch_snapshots)
|
||||
# A failed discovery is newer than an older result: show its session up to the error.
|
||||
for key, transcript in self.state.switch_failed_raw.items():
|
||||
raw[key] = {"raw": {"session": transcript}, "failed": True}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in raw.items() if key in by_id]
|
||||
if not items:
|
||||
return
|
||||
selected = self._selected()
|
||||
@@ -365,7 +415,8 @@ class SwitchesPage(Page):
|
||||
menu = QMenu(self)
|
||||
menu.addAction(icon("play", muted), "Auslesen", self.discover)
|
||||
menu.addAction(icon("pencil", muted), "Bearbeiten …", self.edit_switch)
|
||||
if any(switch["id"] in self.state.switch_snapshots for switch in self._selected()):
|
||||
if any(switch["id"] in self.state.switch_snapshots or switch["id"] in self.state.switch_failed_raw
|
||||
for switch in self._selected()):
|
||||
menu.addAction(icon("terminal", muted), "SSH-Rohdaten …", self.show_raw)
|
||||
menu.addSeparator()
|
||||
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_switches)
|
||||
|
||||
@@ -48,6 +48,8 @@ class AppState(QObject):
|
||||
self.netbox_devices = None
|
||||
self.switch_snapshots = {}
|
||||
self.switch_status = {}
|
||||
# CLI session of failed discoveries (switch id → masked text) for the raw data view.
|
||||
self.switch_failed_raw = {}
|
||||
self.clients = []
|
||||
self.clients_loaded_at = None
|
||||
self.client_engine = None
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@ PySide6-Essentials>=6.7
|
||||
pynetbox>=7.4
|
||||
pyvmomi>=8.0
|
||||
requests>=2.31
|
||||
paramiko>=3.4
|
||||
paramiko>=3.4,<4 # 4.x+ dropped ssh-rsa (SHA-1) and ssh-dss host keys used by older switches (e.g. LANCOM GS-23xx)
|
||||
pywin32>=306; sys_platform == "win32"
|
||||
@@ -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())
|
||||
@@ -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()
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
@@ -0,0 +1,151 @@
|
||||
import io
|
||||
import tarfile
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_sync.core.backups import BackupError, parse_backup, parse_snmp_dump
|
||||
|
||||
BASE = "1.3.6.1.4.1.171.10.76.21.1"
|
||||
|
||||
|
||||
def _octets(oid, value):
|
||||
value = value if isinstance(value, bytes) else value.encode()
|
||||
return f"{oid}\t 4\t{len(value):4d}\t".encode() + value + b"\n"
|
||||
|
||||
|
||||
def _scalar(oid, kind, value):
|
||||
return f"{oid}\t{kind:>2}\t{value}\n".encode()
|
||||
|
||||
|
||||
def dlink_backup():
|
||||
dump = b"".join([
|
||||
_octets("1.3.6.1.2.1.1.5.0", "SW-01"),
|
||||
_octets("1.3.6.1.2.1.1.6.0", "Keller"),
|
||||
_octets(f"{BASE}.1.16.1.2.1", "Uplink"),
|
||||
_octets(f"{BASE}.1.16.1.2.2", ""),
|
||||
_octets(f"{BASE}.1.16.1.2.3", ""),
|
||||
_octets(f"{BASE}.7.6.1.1.10", "LAN"),
|
||||
_octets(f"{BASE}.7.6.1.1.20", "VOICE"),
|
||||
# Bitmaps may contain a line break (0x0a) – the parser must honour the length.
|
||||
_octets(f"{BASE}.7.6.1.2.10", b"\xe0\x00\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.4.10", b"\x60\x00\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.2.20", b"\x80\x0a\x00\x00"),
|
||||
_octets(f"{BASE}.7.6.1.4.20", b"\x00\x00\x00\x00"),
|
||||
_scalar(f"{BASE}.7.7.1.1.1", 66, 10),
|
||||
_scalar(f"{BASE}.7.7.1.1.2", 66, 10),
|
||||
_scalar(f"{BASE}.7.7.1.1.3", 66, 10),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.1", 2, 1),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.2", 2, 1),
|
||||
_scalar("1.3.6.1.2.1.2.2.1.7.3", 2, 2),
|
||||
_scalar(f"{BASE}.2.5.2.0", 64, "10.0.0.5"),
|
||||
_scalar(f"{BASE}.2.5.3.0", 64, "255.255.255.0"),
|
||||
_octets(f"{BASE}.2.5.5.0", "System"),
|
||||
])
|
||||
header = b"DGS-1210-28P".ljust(32, b"\x00") + b"\x00" * 16
|
||||
return header + zlib.compress(dump)
|
||||
|
||||
|
||||
LINKSYS_CONF = """
|
||||
system name "SW-02"
|
||||
system location "Büro"
|
||||
interface gigabitethernet 0/1
|
||||
shutdown
|
||||
description "AP"
|
||||
!
|
||||
interface gigabitethernet 0/2
|
||||
shutdown
|
||||
description ""
|
||||
!
|
||||
interface gigabitethernet 0/3
|
||||
description ""
|
||||
!
|
||||
interface gigabitethernet 0/1
|
||||
no shutdown
|
||||
!
|
||||
vlan 1
|
||||
ports name default
|
||||
!
|
||||
vlan 10
|
||||
ports add gigabitethernet 0/1 untagged gigabitethernet 0/1
|
||||
ports add gigabitethernet 0/2
|
||||
!
|
||||
vlan 20
|
||||
ports add gigabitethernet 0/2
|
||||
!
|
||||
interface vlan 1
|
||||
ip address 10.0.0.6 255.255.255.0
|
||||
!
|
||||
snmp community name SECRET security noAuthUser
|
||||
set switch-name LGS328MPC
|
||||
"""
|
||||
|
||||
|
||||
def linksys_backup():
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w") as archive:
|
||||
data = LINKSYS_CONF.encode()
|
||||
info = tarfile.TarInfo("current_config/SNCSR.conf")
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return b"`A \x00 IMG-3.01.252 header".ljust(64, b"\x00") + buffer.getvalue()
|
||||
|
||||
|
||||
def test_snmp_dump_keeps_binary_octets():
|
||||
values = parse_snmp_dump(_octets("1.2", b"a\nb") + _scalar("1.3", 2, 7))
|
||||
assert values == {"1.2": b"a\nb", "1.3": "7"}
|
||||
|
||||
|
||||
def test_dlink_backup():
|
||||
switch, snapshot = parse_backup(dlink_backup(), "config.bin")
|
||||
assert switch["name"] == "SW-01" and switch["host"] == "10.0.0.5" and switch["model"] == "DGS-1210-28P"
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1"]["description"] == "Uplink"
|
||||
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
|
||||
assert ports["2"]["vlans"]["untagged"] == [10]
|
||||
assert ports["3"]["enabled"] is False
|
||||
assert ports["System"]["ip_addresses"] == ["10.0.0.5/24"] and ports["System"]["virtual"]
|
||||
assert snapshot["vlan_names"] == {10: "LAN", 20: "VOICE"}
|
||||
|
||||
|
||||
def test_linksys_backup():
|
||||
switch, snapshot = parse_backup(linksys_backup(), "x.cfg")
|
||||
assert switch == {"name": "SW-02", "host": "10.0.0.6", "model": "LGS328MPC", "platform": "linksys_backup",
|
||||
"location": "Büro"}
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["GE1"]["enabled"] is True and ports["GE1"]["description"] == "AP"
|
||||
assert ports["GE1"]["vlans"]["untagged"] == [10]
|
||||
assert ports["GE2"]["enabled"] is False
|
||||
assert ports["GE2"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
|
||||
assert ports["GE3"]["vlans"] is None
|
||||
assert ports["vlan1"]["ip_addresses"] == ["10.0.0.6/24"]
|
||||
assert "SECRET" not in snapshot["config_backup"]
|
||||
|
||||
|
||||
def test_linksys_plain_text():
|
||||
switch, _snapshot = parse_backup(LINKSYS_CONF, "SNCSR.conf")
|
||||
assert switch["name"] == "SW-02"
|
||||
|
||||
|
||||
def test_unknown_file():
|
||||
with pytest.raises(BackupError):
|
||||
parse_backup(b"hello world", "x.bin")
|
||||
|
||||
|
||||
def test_dlink_original_file_is_attached():
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
|
||||
from netbox_sync.core.switches import _backup_config
|
||||
|
||||
data = dlink_backup()
|
||||
_switch, snapshot = parse_backup(data, "config.bin")
|
||||
created = []
|
||||
attachments = SimpleNamespace(filter=lambda **_kw: [], create=lambda payload: created.append(payload)
|
||||
or SimpleNamespace())
|
||||
nb = SimpleNamespace(plugins=SimpleNamespace(netbox_attachments=SimpleNamespace(netbox_attachments=attachments)))
|
||||
report = {"notes": [], "errors": [], "changes": []}
|
||||
_backup_config(nb, SimpleNamespace(id=1, name="SW-01"), snapshot, False, report)
|
||||
filename, stream, content_type = created[0]["file"]
|
||||
assert filename.endswith(".bin") and content_type == "application/octet-stream"
|
||||
assert stream.read() == data == base64.b64decode(snapshot["config_file"]["data"])
|
||||
@@ -0,0 +1,341 @@
|
||||
from netbox_sync.core import lancom
|
||||
from netbox_sync.core.switches import build_snapshot, netbox_interface_type, suggest_platform
|
||||
|
||||
SYSTEM = """
|
||||
Model Name : LANCOM GS-2326P+
|
||||
Location : Keller
|
||||
Device Name : SW-08
|
||||
Firmware Version : v3.34.0205RU4
|
||||
Serial Number : 4006846720000000
|
||||
Host MAC Address : 00-a0-57-00-00-01
|
||||
SW-08(system)#"""
|
||||
|
||||
STATUS = """
|
||||
Port/Media State Link Auto Nego Speed Duplex Rx Pause Tx Pause
|
||||
---------- -------- -------------- --------- ------------ -------- --------
|
||||
1/UTP Enabled Down Enabled Down Disabled Disabled
|
||||
2/UTP Enabled Up Enabled 1G Full Disabled Disabled
|
||||
3/UTP Disabled Down Enabled Down Disabled Disabled
|
||||
4/UTP Enabled Up Enabled 100 Full Disabled Disabled
|
||||
25/SFP Enabled Up Enabled 1G Full Disabled Disabled
|
||||
SW-08(port)#"""
|
||||
|
||||
PORT_CONFIG = """
|
||||
Port State Speed Duplex Flow Control Max. Frame Excessive Power
|
||||
Description
|
||||
--------------------------------------------------------------------------------
|
||||
1 Enabled Auto Disabled 9600 Discard Disabled
|
||||
Uplink
|
||||
--------------------------------------------------------------------------------
|
||||
2 Enabled Auto Disabled 9600 Discard Disabled
|
||||
AP005
|
||||
--------------------------------------------------------------------------------
|
||||
3 Disabled Auto Disabled 9600 Discard Disabled
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
4 Enabled Auto Disabled 9600 Discard Disabled
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled
|
||||
|
||||
SW-08(port)#"""
|
||||
|
||||
VLANS = """
|
||||
VID VLAN Name User Ports
|
||||
---- -------------------------------- ---------- -----------------
|
||||
36 LAN Static 1-4,25
|
||||
136 MOBILE Static 1-2
|
||||
236 GUEST Static 1,3
|
||||
SW-08(vlan)#"""
|
||||
|
||||
VLAN_PORTS = """
|
||||
Port PVID Frame Type Ingress Filter Egress Rule Port Type
|
||||
---- ---- ---------- -------------- ----------- -------------
|
||||
1 1 All Disabled Trunk C-Port
|
||||
2 36 All Disabled Hybrid C-Port
|
||||
3 36 All Disabled Hybrid C-Port
|
||||
4 36 All Disabled Access C-Port
|
||||
25 1 All Disabled Hybrid C-Port
|
||||
SW-08(vlan)#"""
|
||||
|
||||
IP = """
|
||||
Configured Current
|
||||
--------------- ---------------
|
||||
DHCP Client : Disabled
|
||||
IP Address : 10.0.0.8 10.0.0.8
|
||||
IP Mask : 255.255.255.0 255.255.255.0
|
||||
VLAN ID : 36 36
|
||||
SW-08(ip)#"""
|
||||
|
||||
|
||||
def outputs():
|
||||
return {"system": SYSTEM, "status": STATUS, "port_config": PORT_CONFIG, "vlans": VLANS,
|
||||
"vlan_ports": VLAN_PORTS, "ip": IP, "neighbors": ""}
|
||||
|
||||
|
||||
def test_snapshot():
|
||||
snapshot = build_snapshot(outputs(), "lancom_sx3")
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1"]["description"] == "Uplink" and not ports["1"]["connected"]
|
||||
assert ports["2"]["connected"] and ports["2"]["speed_mbps"] == 1000
|
||||
assert ports["4"]["speed_mbps"] == 100
|
||||
assert ports["3"]["enabled"] is False
|
||||
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [36, 136, 236], "tagged_all": False}
|
||||
assert ports["2"]["vlans"] == {"untagged": [36], "tagged": [136], "tagged_all": False}
|
||||
assert ports["4"]["vlans"]["untagged"] == [36]
|
||||
assert ports["25"]["vlans"] == {"untagged": [], "tagged": [36], "tagged_all": False}
|
||||
assert netbox_interface_type(ports["25"]) == "1000base-x-sfp"
|
||||
assert netbox_interface_type(ports["1"]) == "1000base-t"
|
||||
assert ports["vlan36"]["ip_addresses"] == ["10.0.0.8/24"]
|
||||
assert snapshot["vlan_names"] == {36: "LAN", 136: "MOBILE", 236: "GUEST"}
|
||||
assert snapshot["system"]["model"] == "LANCOM GS-2326P+"
|
||||
assert "show port-config" in snapshot["config_backup"]
|
||||
|
||||
|
||||
def test_detection_helpers():
|
||||
assert lancom.is_lancom(SYSTEM)
|
||||
assert suggest_platform("LANCOM Systems", "GS-2326P+") == "lancom_sx3"
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
"""Answers like the mode-based CLI and records what was sent."""
|
||||
|
||||
def __init__(self):
|
||||
self.sent, self.mode, self.buffer = [], "", ""
|
||||
|
||||
def send(self, data):
|
||||
if not data.endswith("\r"):
|
||||
self.buffer += data # like the real CLI: "\n" is only echoed, nothing is executed
|
||||
return
|
||||
command = data.strip()
|
||||
self.sent.append(command)
|
||||
answers = {("system", "show"): SYSTEM, ("port", "show status"): STATUS,
|
||||
("port", "show configuration"): PORT_CONFIG, ("vlan", "show vlan"): VLANS,
|
||||
("vlan", "show port-config"): VLAN_PORTS, ("ip", "show"): IP}
|
||||
if command == "exit":
|
||||
self.mode = ""
|
||||
output = ""
|
||||
elif not self.mode and command in ("system", "port", "vlan", "ip", "lldp"):
|
||||
self.mode = command
|
||||
output = ""
|
||||
else:
|
||||
output = answers.get((self.mode, command), "% Unrecognized command")
|
||||
self.buffer += output + f"\nSW-08{'(' + self.mode + ')' if self.mode else ''}# "
|
||||
|
||||
def recv_ready(self):
|
||||
return bool(self.buffer)
|
||||
|
||||
def recv(self, _size):
|
||||
data, self.buffer = self.buffer, ""
|
||||
return data.encode()
|
||||
|
||||
|
||||
def test_run_commands_switches_modes():
|
||||
channel = FakeChannel()
|
||||
result = lancom.run_commands(channel)
|
||||
assert result["vlans"].strip().startswith("VID") and result["neighbors"] == ""
|
||||
assert channel.sent[:3] == ["system", "show", "exit"]
|
||||
assert channel.mode == ""
|
||||
assert "show info 1-4,25" in channel.sent
|
||||
|
||||
|
||||
LLDP_CONFIG = """
|
||||
Interval : 30
|
||||
Port System System System Management CDP
|
||||
Port Mode Description Name Description Capability Address awareness
|
||||
---- -------- ----------- -------- ----------- ----------- ---------- ---------
|
||||
1 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
|
||||
2 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
|
||||
SW-08(lldp)#"""
|
||||
|
||||
|
||||
def test_lldp_disabled_is_reported():
|
||||
snapshot = build_snapshot(dict(outputs(), lldp_config=LLDP_CONFIG, neighbors="No LLDP entries found"),
|
||||
"lancom_sx3")
|
||||
assert snapshot["lldp_disabled"] is True and snapshot["neighbors"] == []
|
||||
enabled = LLDP_CONFIG.replace("1 Disabled", "1 Enabled ")
|
||||
assert build_snapshot(dict(outputs(), lldp_config=enabled), "lancom_sx3")["lldp_disabled"] is False
|
||||
|
||||
|
||||
def test_enable_lldp_on_disabled_ports():
|
||||
channel = FakeChannel()
|
||||
state = {"config": LLDP_CONFIG}
|
||||
original = channel.send
|
||||
|
||||
def send(data):
|
||||
command = data.strip()
|
||||
if channel.mode == "lldp" and command == "show config":
|
||||
channel.sent.append(command)
|
||||
channel.buffer += state["config"] + "\nSW-08(lldp)# "
|
||||
elif channel.mode == "lldp" and command.startswith("mode "):
|
||||
channel.sent.append(command)
|
||||
state["config"] = LLDP_CONFIG.replace("Disabled Enabled", "Enabled Enabled")
|
||||
channel.buffer += "\nSW-08(lldp)# "
|
||||
else:
|
||||
original(data)
|
||||
|
||||
channel.send = send
|
||||
result = lancom.run_commands(channel, enable_lldp=True, wait=0)
|
||||
assert "mode 1-2 enable" in channel.sent
|
||||
assert result["lldp_enabled_automatically"] is True
|
||||
snapshot = build_snapshot(dict(outputs(), **result), "lancom_sx3")
|
||||
assert snapshot["lldp_enabled_automatically"] and not snapshot["lldp_disabled"]
|
||||
assert all(isinstance(value, str) for value in snapshot["raw"].values())
|
||||
|
||||
|
||||
def test_auto_detection_falls_back_to_carriage_return(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
|
||||
def quick(channel, timeout=20, initialize_session=False):
|
||||
return real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session)
|
||||
|
||||
monkeypatch.setattr(switches, "_read_available", quick)
|
||||
channel = FakeChannel()
|
||||
assert switches.detect_platform(channel, "SW-08# ") == "lancom_sx3"
|
||||
assert channel.mode == ""
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, channel):
|
||||
self.channel = channel
|
||||
|
||||
def invoke_shell(self, **_kwargs):
|
||||
return self.channel
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _quick_reads(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
monkeypatch.setattr(switches, "_read_available", lambda channel, timeout=20, initialize_session=False:
|
||||
real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session))
|
||||
command = lancom._run_cli_command
|
||||
monkeypatch.setattr(lancom, "_run_cli_command", lambda channel, text, timeout=20:
|
||||
command(channel, text, timeout=min(timeout, 0.3)))
|
||||
return switches
|
||||
|
||||
|
||||
def test_session_is_recorded(monkeypatch):
|
||||
switches = _quick_reads(monkeypatch)
|
||||
channel = FakeChannel()
|
||||
channel.buffer = "snmp community secret123\nSW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
outputs = switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "»» system" in outputs["session"] and "Model Name" in outputs["session"]
|
||||
assert "secret123" not in outputs["session"]
|
||||
assert "Sitzung" not in outputs # only raw outputs, no UI titles
|
||||
assert build_snapshot(outputs, "lancom_sx3")["raw"]["session"] == outputs["session"]
|
||||
|
||||
|
||||
def test_session_is_attached_to_errors(monkeypatch):
|
||||
import pytest
|
||||
|
||||
switches = _quick_reads(monkeypatch)
|
||||
|
||||
class Silent(FakeChannel):
|
||||
def send(self, data):
|
||||
self.sent.append(data.strip()) # never answers with a prompt
|
||||
|
||||
channel = Silent()
|
||||
channel.buffer = "SW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "SW-08#" in caught.value.transcript and "»» system" in caught.value.transcript
|
||||
|
||||
|
||||
def test_paging_is_answered_with_space():
|
||||
class Paging(FakeChannel):
|
||||
def send(self, data):
|
||||
if data == " ":
|
||||
self.sent.append("<space>")
|
||||
self.buffer += "\r \rFlash Size : 32\nSW-08(system)# "
|
||||
elif data.strip() == "show" and self.mode == "system":
|
||||
self.sent.append("show")
|
||||
self.buffer += "show\nModel Name : LANCOM GS-2326P+\nRAM Size : 128\n -- more --, next page: Space, q to quit"
|
||||
else:
|
||||
super().send(data)
|
||||
|
||||
channel = Paging()
|
||||
channel.mode = "system"
|
||||
output = lancom._run_cli_command(channel, "show", timeout=2)
|
||||
assert channel.sent == ["show", "<space>"]
|
||||
assert "RAM Size : 128" in output and "Flash Size : 32" in output
|
||||
assert "quit" not in output and "more" not in output
|
||||
|
||||
|
||||
def test_neighbor_on_named_local_port():
|
||||
neighbors = """
|
||||
Local Port : Port 2
|
||||
Chassis ID : 00-a0-57-11-22-33
|
||||
Port ID : LAN1
|
||||
System Name : AP-005
|
||||
Management Address : 10.0.0.50 (IPv4)
|
||||
SW-08(lldp)#"""
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
port = next(item for item in snapshot["interfaces"] if item["name"] == "2")
|
||||
assert port["neighbor"]["local_port"] == "2"
|
||||
assert port["neighbor"]["system_name"] == "AP-005" and port["neighbor"]["remote_port"] == "LAN1"
|
||||
assert port["neighbor"]["management_ip"] == "10.0.0.50"
|
||||
|
||||
|
||||
def test_reparse_fixes_older_exports():
|
||||
neighbors = "Local Port : Port 2\nPort ID : LAN1\nSystem Name : AP-005\nSW-08(lldp)#"
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
snapshot["neighbors"][0]["local_port"] = "Port 2" # as written by 4.16.3
|
||||
for item in snapshot["interfaces"]:
|
||||
item["neighbor"] = None
|
||||
snapshot["discovered_at"] = 123
|
||||
rebuilt = lancom.reparse(snapshot)
|
||||
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"] == ""
|
||||
@@ -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
|
||||
+305
-1
@@ -1,12 +1,15 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fake_netbox import FakeNetBox, Record
|
||||
from fake_netbox import Endpoint, FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.switches import (
|
||||
build_snapshot,
|
||||
mask_config,
|
||||
match_interfaces,
|
||||
parse_lags,
|
||||
parse_stack,
|
||||
plan_switch_sync,
|
||||
port_label,
|
||||
stack_member,
|
||||
sync_snapshot_to_netbox,
|
||||
)
|
||||
@@ -366,6 +369,32 @@ def test_stack_members_go_to_their_own_netbox_devices():
|
||||
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
|
||||
|
||||
|
||||
def test_stack_is_filled_in_netbox_utilities_when_the_plugin_exists():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
|
||||
switch["stack_devices"] = {"1": 1, "2": 4}
|
||||
# Without the plugin the stack is simply not written.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert not report["errors"] and not any("Switch-Stack" in change for change in report["changes"])
|
||||
|
||||
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(switch_stacks=Endpoint()))
|
||||
stacks = nb.plugins.utilities.switch_stacks
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Switch-Stack access-01 neu mit Mitgliedern access-01-2 (NetBox Utilities)" in report["changes"]
|
||||
assert stacks.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert stacks.created == [{"device": 1, "members": [4]}]
|
||||
stacks.records[0].device = SimpleNamespace(id=1)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("Switch-Stack" in change for change in report["changes"]), "already complete"
|
||||
|
||||
# Members entered by hand stay, missing ones are added.
|
||||
stacks.records[0].members = [9]
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert stacks.updates[-1] == (stacks.records[0].id, {"members": [9, 4]})
|
||||
|
||||
|
||||
def test_virtual_chassis_positions_are_suggested():
|
||||
nb, switch, _snapshot = _numbered_setup()
|
||||
snapshot = _stack_snapshot()
|
||||
@@ -375,3 +404,278 @@ def test_virtual_chassis_positions_are_suggested():
|
||||
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
|
||||
|
||||
|
||||
CX_LAG_BRIEF = """
|
||||
Port Native Mode Type Enabled Status Reason Speed Description
|
||||
1/1/1 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||
1/1/2 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||
1/1/23 120 access 1G-BT yes up 1000 FritzBox
|
||||
lag1 1 trunk -- yes up -- 20000 Etage 1 Uplink
|
||||
"""
|
||||
|
||||
CX_LAG_CONFIG = """vlan 1
|
||||
vlan 100
|
||||
interface lag 1
|
||||
no routing
|
||||
vlan trunk native 1
|
||||
vlan trunk allowed 100,110,120,201,209-213
|
||||
interface 1/1/1
|
||||
no shutdown
|
||||
lag 1
|
||||
interface 1/1/2
|
||||
no shutdown
|
||||
lag 1
|
||||
interface 1/1/23
|
||||
no routing
|
||||
vlan access 120
|
||||
"""
|
||||
|
||||
|
||||
def test_lags_are_parsed_for_all_platforms():
|
||||
assert parse_lags(CX_LAG_CONFIG, "aruba_cx") == {"1/1/1": "lag1", "1/1/2": "lag1"}
|
||||
assert parse_lags("trunk 49-50 trk1 lacp\ntrunk 1/A1-1/A2 Trk2 trunk\n", "aruba_aos") == {
|
||||
"49": "Trk1", "50": "Trk1", "1/a1": "Trk2", "1/a2": "Trk2"}
|
||||
comware = "interface GigabitEthernet1/0/49\n port link-aggregation group 3\n#\n"
|
||||
assert parse_lags(comware, "hpe_comware") == {"ge1/0/49": "Bridge-Aggregation3"}
|
||||
|
||||
|
||||
def test_lag_members_take_the_lag_vlans_and_name_the_lag_in_the_label():
|
||||
snapshot = build_snapshot({"interfaces": CX_LAG_BRIEF, "neighbors": "", "config": CX_LAG_CONFIG}, "aruba_cx")
|
||||
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||
assert ports["1/1/1"]["lag"] == "lag1" and ports["1/1/23"]["lag"] is None
|
||||
assert port_label(ports["1/1/1"]["vlans"], ports["1/1/1"]["lag"]) == "1,100,110,120,201,209-213 (LAG 1)"
|
||||
assert port_label(ports["1/1/23"]["vlans"], ports["1/1/23"]["lag"]) == "120"
|
||||
assert port_label(None, "Trk2") == "(LAG 2)"
|
||||
assert len(port_label({"untagged": [], "tagged": list(range(2, 400, 2)), "tagged_all": False}, "lag1")) <= 64
|
||||
assert " lag 1" in snapshot["raw"]["vlan_config"]
|
||||
|
||||
|
||||
def test_lag_members_are_assigned_to_their_lag_in_netbox():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=30, name="lag1", device=SimpleNamespace(id=1),
|
||||
type=SimpleNamespace(value="lag"), enabled=True, cable=None, label=""))
|
||||
snapshot["interfaces"].append({"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [],
|
||||
"vlans": None})
|
||||
for item in snapshot["interfaces"][:2]:
|
||||
item["lag"] = "lag1"
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Interface 1: LAG lag1" in report["changes"] and nb.dcim.interfaces.updates == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert nb.dcim.interfaces.get(1).lag == 30 and nb.dcim.interfaces.get(1).label == "10 (LAG 1)"
|
||||
assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("LAG lag1" in change for change in report["changes"]), "already assigned"
|
||||
|
||||
|
||||
class _AttachmentEndpoint(Endpoint):
|
||||
def create(self, payload):
|
||||
record = super().create(payload)
|
||||
if self.assignments is not None:
|
||||
record.assignments = []
|
||||
return record
|
||||
|
||||
def filter(self, **kwargs):
|
||||
query = kwargs.pop("q", "")
|
||||
return [item for item in super().filter(**kwargs) if query in (getattr(item, "description", "") or "")]
|
||||
|
||||
|
||||
def _attachments(newer=True):
|
||||
attachments = _AttachmentEndpoint()
|
||||
attachments.assignments = [] if newer else None
|
||||
return SimpleNamespace(netbox_attachments=attachments, netbox_attachment_assignments=Endpoint())
|
||||
|
||||
|
||||
def test_config_backup_masks_secrets():
|
||||
config = ('hostname core\nuser admin group administrators password ciphertext AQBapW==\n'
|
||||
'snmp-server community geheim\nradius-server host 10.0.0.1 key plaintext topsecret\n')
|
||||
masked = mask_config(config)
|
||||
assert "AQBapW" not in masked and "geheim" not in masked and "topsecret" not in masked
|
||||
assert "hostname core" in masked and "password <entfernt>" in masked
|
||||
|
||||
|
||||
def test_config_is_attached_only_when_it_changed():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
snapshot["config_backup"] = "hostname access-01"
|
||||
# Without the plugin nothing happens.
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
assert not report["errors"]
|
||||
|
||||
nb.plugins = SimpleNamespace(netbox_attachments=_attachments())
|
||||
app = nb.plugins.netbox_attachments
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||
assert any(change.startswith("Konfigurations-Backup: Anhang „Running-Config access-01")
|
||||
for change in report["changes"]) and app.netbox_attachments.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
payload = app.netbox_attachments.created[0]
|
||||
assert payload["file"][1].getvalue() == b"hostname access-01" and payload["file"][0].endswith(".txt")
|
||||
assert app.netbox_attachment_assignments.created == [
|
||||
{"attachment": app.netbox_attachments.records[0].id, "object_type": "dcim.device", "object_id": 1}]
|
||||
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||
assert not any("Konfigurations-Backup" in change for change in report["changes"]), "unchanged"
|
||||
snapshot["config_backup"] = "hostname access-01\nvlan 10"
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
assert len(app.netbox_attachments.created) == 2
|
||||
|
||||
|
||||
def test_config_backup_with_older_attachment_plugin():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
snapshot["config_backup"] = "hostname access-01"
|
||||
nb.plugins = SimpleNamespace(netbox_attachments=_attachments(newer=False))
|
||||
app = nb.plugins.netbox_attachments
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||
payload = app.netbox_attachments.created[0]
|
||||
assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1)
|
||||
assert app.netbox_attachment_assignments.created == []
|
||||
|
||||
|
||||
def test_cable_to_access_point_that_reports_its_mac_as_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records += [
|
||||
Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E",
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
]
|
||||
snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e")
|
||||
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||
|
||||
# A device with a single port is cabled there even if neither name nor MAC match.
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5),
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
|
||||
snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc")
|
||||
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||
|
||||
|
||||
def _cabled_setup(far_type="dcim.interface"):
|
||||
"""Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0."""
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
far = {"object_type": far_type, "object_id": 99,
|
||||
"object": {"name": "eth9", "device": {"name": "old-device"}}}
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 2}]))
|
||||
switch["neighbor_devices"] = {"1/1/2": 2}
|
||||
return nb, switch, snapshot
|
||||
|
||||
|
||||
def test_differing_cable_is_only_reported_by_default():
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == []
|
||||
assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"])
|
||||
|
||||
|
||||
def test_differing_cable_is_moved_when_allowed():
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True)
|
||||
assert report["cables_updated"] == 1 and nb.dcim.cables.updates == []
|
||||
assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"])
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert nb.dcim.cables.updates == [(70, {
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": 2}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})]
|
||||
assert nb.dcim.cables.created == []
|
||||
|
||||
|
||||
def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
|
||||
nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport")
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"]
|
||||
|
||||
nb, switch, snapshot = _cabled_setup()
|
||||
nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71)
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||
assert nb.dcim.cables.updates == []
|
||||
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])
|
||||
|
||||
|
||||
def test_vlans_of_another_site_are_only_labelled():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.get(1).site = SimpleNamespace(id=2)
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=110, vid=10, name="MOBILE", tenant=SimpleNamespace(id=7), site=SimpleNamespace(id=1)),
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="CLIENTS", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert report["errors"] == []
|
||||
assert nb.dcim.interfaces.get(1).label == "10" and getattr(nb.dcim.interfaces.get(1), "untagged_vlan", None) is None
|
||||
assert nb.dcim.interfaces.get(2).untagged_vlan == 120, "global VLANs are always assigned"
|
||||
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
|
||||
Reference in new issue
Block a user