Compare commits

..
7 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 05d34e4823 chore: release 4.17.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:46 +01:00
MrBlakeandClaude Opus 5.5 f134db0c16 fix: put access point IPs into the VRF of the matching tenant prefix instead of always global
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 09:05:45 +01:00
MrBlakeandClaude Opus 5.5 1352514577 chore: release 4.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:50:33 +01:00
MrBlakeandClaude Opus 5.5 fc503bd7d3 feat: choose the far-end interface of a cable in the review dialog
The neighbor tab gets a "Nachbar-Schnittstelle" column with the cable targets
of the neighbor device (no wireless interfaces) and the automatic choice;
the selection is stored per switch as neighbor_interfaces.

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

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

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

No files matched your search

+5 -1
View File
@@ -106,7 +106,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
assignments) are supported; without the plugin the step is skipped with a note 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. - 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 Neighbors that report their MAC address as port ID (e.g. access points) are
matched by MAC, and a device with a single physical port is cabled there matched by MAC, and a device with a single physical port is cabled there.
Wireless interfaces (Wi-Fi, LTE …) are never cable targets. In the review
dialog the far-end interface can be chosen per neighbor ("automatisch" shows
the interface that would be used); the choice is stored in the profile.
Every skipped cable is listed as a note with its reason
- Existing cables are checked against LLDP/CDP: a different far end is reported - 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 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 a warning, NetBox is the source of truth) the cable is moved to the reported
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.16.4" #define AppVersion "4.17.1"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.16.4" APP_VERSION = "4.17.1"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+26 -5
View File
@@ -13,6 +13,7 @@ import ipaddress
import re import re
from netbox_sync.core.client_sync import ClientSyncEngine 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 from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id, uses_mac_objects
MANUFACTURER = "Sophos" MANUFACTURER = "Sophos"
@@ -260,6 +261,7 @@ class APSyncEngine(ClientSyncEngine):
""" """
report = self.new_report() report = self.new_report()
self._planned = set() self._planned = set()
self._vrf_cache = {}
for ap in aps: for ap in aps:
try: try:
changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report, changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report,
@@ -327,7 +329,9 @@ class APSyncEngine(ClientSyncEngine):
else "")) else ""))
if ap["ip"]: if ap["ip"]:
report["ips_created"] += 1 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 return changes
device = self.nb.dcim.devices.create(payload) device = self.nb.dcim.devices.create(payload)
if dry_run and device is None: if dry_run and device is None:
@@ -350,6 +354,21 @@ class APSyncEngine(ClientSyncEngine):
interface = self.nb.dcim.interfaces.create({"device": device.id, "name": INTERFACE_NAME, "type": "1000base-t"}) interface = self.nb.dcim.interfaces.create({"device": device.id, "name": INTERFACE_NAME, "type": "1000base-t"})
return interface, [f"Schnittstelle {INTERFACE_NAME} anlegen"] 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): def _sync_network(self, device, ap, tenant_id, dry_run, report):
if not ap["mac"] and not ap["ip"]: if not ap["mac"] and not ap["ip"]:
return [] return []
@@ -359,10 +378,12 @@ class APSyncEngine(ClientSyncEngine):
changes.append(f"MAC {ap['mac']} zugeordnet") changes.append(f"MAC {ap['mac']} zugeordnet")
if not ap["ip"]: if not ap["ip"]:
return changes return changes
prefix = next(iter(self.nb.ipam.prefixes.filter(contains=ap["ip"], vrf_id="null")), None) prefix = self._prefix_for(ap["ip"], tenant_id)
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32" length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32"
vrf_id = related_id(prefix, "vrf") if prefix else None
address = f"{ap['ip']}/{length}" 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: if existing:
ip = existing[0] ip = existing[0]
assigned = getattr(ip, "assigned_object_id", None) assigned = getattr(ip, "assigned_object_id", None)
@@ -378,11 +399,11 @@ class APSyncEngine(ClientSyncEngine):
"tenant": related_id(ip, "tenant") or tenant_id}) "tenant": related_id(ip, "tenant") or tenant_id})
else: else:
report["ips_created"] += 1 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: if dry_run or interface is None:
return changes return changes
ip = self.nb.ipam.ip_addresses.create({ 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, "assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
}) })
if not dry_run and related_id(device, "primary_ip4") != ip.id: if not dry_run and related_id(device, "primary_ip4") != ip.id:
+15 -8
View File
@@ -12,6 +12,7 @@ import time
from netbox_sync.core.switches import ( from netbox_sync.core.switches import (
CLI_ERROR, CLI_ERROR,
CLI_PROMPT, CLI_PROMPT,
MAC_PATTERN,
_compress_vlans, _compress_vlans,
_interface, _interface,
_membership, _membership,
@@ -120,7 +121,9 @@ def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, w
def _field(text, label): def _field(text, label):
match = re.search(rf"(?im)^{re.escape(label)}\s*:\s*(.*?)\s*$", text or "") # Only spaces/tabs around the colon: an empty value must not swallow the next line. Lines after a
# paging prompt are indented, hence the optional leading blanks.
match = re.search(rf"(?im)^[ \t]*{re.escape(label)}[ \t]*:[ \t]*(.*?)[ \t]*$", text or "")
return match.group(1) if match else "" return match.group(1) if match else ""
@@ -148,17 +151,17 @@ def parse_status(output):
def parse_port_config(output): def parse_port_config(output):
"""``show configuration``: a port line followed by its description line.""" """``show configuration``: a port line, directly followed by its (possibly empty) description line."""
ports, current = {}, None ports, current = {}, None
for line in clean_output(output).splitlines(): for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)\s+(Enabled|Disabled)\s", line, re.I) match = re.match(r"^\s*(\d+)\s+(Enabled|Disabled)\s", line, re.I)
if match: if match:
current = int(match.group(1)) current = int(match.group(1))
ports[current] = {"enabled": match.group(2).lower() == "enabled", "description": ""} ports[current] = {"enabled": match.group(2).lower() == "enabled", "description": ""}
elif current is not None and line.strip() and not set(line.strip()) <= {"-"}: elif current is not None:
ports[current]["description"] = line.strip() text = line.strip()
current = None if text and not set(text) <= {"-"} and not CLI_PROMPT.search(text):
elif current is not None and set(line.strip()) <= {"-"} and line.strip(): ports[current]["description"] = text
current = None current = None
return ports return ports
@@ -240,14 +243,18 @@ def parse_neighbors(output):
if not local: if not local:
continue continue
port = re.search(r"(\d+)", local) # "Port 2" → "2", the name of the switch port 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({ neighbors.append({
"local_port": port.group(1) if port else local, "local_port": port.group(1) if port else local,
"system_name": _field(block, "System Name"), "system_name": name,
"remote_port": _field(block, "Port ID") or _field(block, "Port Description"), "remote_port": _field(block, "Port ID") or _field(block, "Port Description"),
"port_description": _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")) "management_ip": (re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", _field(block, "Management Address"))
or [""])[0], or [""])[0],
"chassis_id": _field(block, "Chassis ID"), "chassis_id": chassis,
"protocol": "LLDP", "protocol": "LLDP",
}) })
return neighbors return neighbors
+64 -13
View File
@@ -1095,6 +1095,14 @@ def _physical_record(record):
and not re.match(r"^(?:vlan|lo|mgmt|oobm)", interface_key(record.name))) 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): def _physical_interface(interface):
return netbox_interface_type(interface) not in ("virtual", "lag") return netbox_interface_type(interface) not in ("virtual", "lag")
@@ -1420,7 +1428,15 @@ def plan_switch_sync(nb, config, snapshot):
if remote and remote.id not in known and remote.id != device.id: if remote and remote.id not in known and remote.id != device.id:
devices.append({"id": remote.id, "name": remote.name}) devices.append({"id": remote.id, "name": remote.name})
known.add(remote.id) 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). # 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 []): for member_device in ([device, *filter(None, members.values())] if members else []):
if member_device.id not in known: if member_device.id not in known:
@@ -1523,10 +1539,13 @@ class _RemoteLookup:
self.devices[cache_key] = found self.devices[cache_key] = found
return 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): def interface(self, device, neighbor):
if device.id not in self.interfaces: records = self.records(device.id)
self.interfaces[device.id] = _device_interfaces(self.nb, device.id)
records = self.interfaces[device.id]
candidates = [neighbor.get("remote_port"), neighbor.get("port_description")] candidates = [neighbor.get("remote_port"), neighbor.get("port_description")]
if neighbor.get("port_description"): if neighbor.get("port_description"):
candidates.append(neighbor["port_description"].split()[0]) candidates.append(neighbor["port_description"].split()[0])
@@ -1538,7 +1557,7 @@ class _RemoteLookup:
number = _port_number(neighbor.get("remote_port")) number = _port_number(neighbor.get("remote_port"))
if number is not None: if number is not None:
found = [record for record in records.values() 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: if len(found) == 1:
return found[0] return found[0]
# Access points and phones often report their MAC address as port ID. # Access points and phones often report their MAC address as port ID.
@@ -1550,10 +1569,18 @@ class _RemoteLookup:
return found[0] return found[0]
# An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there. # 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() physical = [record for record in records.values()
if _physical_record(record) and not getattr(record, "mgmt_only", False)] if _cableable_record(record) and not getattr(record, "mgmt_only", False)]
return physical[0] if len(physical) == 1 else None 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 _NEW = "new" # placeholder ID of objects a dry run would create
@@ -2030,34 +2057,58 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if create_cables: if create_cables:
lookup = _RemoteLookup(nb) lookup = _RemoteLookup(nb)
manual_devices = config.get("neighbor_devices") or {} manual_devices = config.get("neighbor_devices") or {}
manual_interfaces = config.get("neighbor_interfaces") or {}
for neighbor in snapshot["neighbors"]: 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: try:
key = interface_key(neighbor["local_port"]) key = interface_key(neighbor["local_port"])
if key not in records: if key not in records:
skip(f"lokaler Port „{neighbor['local_port']}“ gehört zu keiner Schnittstelle")
continue continue
local = records[key] local = records[key]
if local is None: # interface only created by this (dry) run
if not dry_run:
skip("lokale Schnittstelle wurde nicht angelegt")
continue
existing = getattr(local, "cable", None) if local is not None else None existing = getattr(local, "cable", None) if local is not None else None
if neighbor["local_port"] in manual_devices: if neighbor["local_port"] in manual_devices:
# 0 means "no device" was chosen in the review dialog. # 0 means "no device" was chosen in the review dialog.
chosen = int(manual_devices[neighbor["local_port"]] or 0) 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: else:
remote_device = lookup.device(neighbor) remote_device = lookup.device(neighbor)
if not remote_device: if not remote_device:
report["cables_skipped"] += 1 skip("Nachbargerät nicht in NetBox gefunden – bei Bedarf im Reiter „Nachbarn“ zuordnen")
continue continue
if remote_device.id in own_devices: if remote_device.id in own_devices:
continue continue
remote = lookup.interface(remote_device, neighbor) # A far-end interface chosen in the review dialog wins – as long as it belongs to the device.
chosen_interface = manual_interfaces.get(neighbor["local_port"])
remote = next((record for record in lookup.records(remote_device.id).values()
if chosen_interface and record.id == chosen_interface), None)
remote = remote or lookup.interface(remote_device, neighbor)
if existing: if existing:
if remote: if remote:
_check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report) _check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report)
else: else:
report["cables_skipped"] += 1 skip(f"lokaler Port hat bereits ein Kabel, Schnittstelle „{neighbor.get('remote_port')}“ "
f"auf {remote_device.name} nicht gefunden")
continue continue
if not remote or getattr(remote, "cable", None): if not remote:
report["cables_skipped"] += 1 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 continue
report["cables_created"] += 1 report["cables_created"] += 1
report["changes"].append(f"Kabel {device.name} {label}") report["changes"].append(f"Kabel {device.name} {label}")
+3 -1
View File
@@ -16,6 +16,7 @@ from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.netbox import NetBoxError, related_id, related_name from netbox_sync.core.netbox import NetBoxError, related_id, related_name
from netbox_sync.core.switches import ( from netbox_sync.core.switches import (
PLATFORMS, PLATFORMS,
cable_targets,
describe_snapshot, describe_snapshot,
discover_switch, discover_switch,
plan_switch_sync, plan_switch_sync,
@@ -525,7 +526,8 @@ class Actions:
# Started after the planning task has finished, so the next # Started after the planning task has finished, so the next
# task is not rejected as "still busy". # task is not rejected as "still busy".
if needs_review: 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(): if not dialog.exec():
return return
stored = {switch["id"]: switch for switch in self.state.switches} stored = {switch["id"]: switch for switch in self.state.switches}
+57 -9
View File
@@ -619,7 +619,10 @@ class SwitchMappingDialog(_Dialog):
NEW = "\x00new" 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", super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte " "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.", "erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
@@ -716,9 +719,9 @@ class SwitchMappingDialog(_Dialog):
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: " "Fü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“ " f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
"überspringt den Nachbarn.", muted=True, wrap=True)) "ü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)", 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 switch, plan in plans:
for neighbor in plan["neighbors"]: for neighbor in plan["neighbors"]:
row = self.neighbor_table.rowCount() row = self.neighbor_table.rowCount()
@@ -727,14 +730,22 @@ class SwitchMappingDialog(_Dialog):
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]], combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
neighbor.get("device_id") or 0) neighbor.get("device_id") or 0)
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or 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): for column, text in enumerate(texts):
self.neighbor_table.setItem(row, column, QTableWidgetItem(text)) self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
self.neighbor_table.setCellWidget(row, 4, combo) self.neighbor_table.setCellWidget(row, 4, combo)
self.neighbor_rows.append((switch, neighbor, combo)) port_combo = SearchableComboBox("Schnittstelle suchen …")
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260)) 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) 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)") tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks -------------------------------------------------------------- # Networks --------------------------------------------------------------
@@ -959,13 +970,43 @@ class SwitchMappingDialog(_Dialog):
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked) status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning"))) 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): def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows: for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name") self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
def accept(self): def accept(self):
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}), 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} for switch, _plan in self.plans}
# Members moved to another device: their port choices refer to the old # Members moved to another device: their port choices refer to the old
# device and are dropped, so the ports are matched again automatically. # device and are dropped, so the ports are matched again automatically.
@@ -996,7 +1037,7 @@ class SwitchMappingDialog(_Dialog):
mapping.pop(item["name"], None) mapping.pop(item["name"], None)
else: else:
mapping[item["name"]] = target 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 = combo.valid_data()
chosen = int(chosen or 0) chosen = int(chosen or 0)
stored = result[switch["id"]]["neighbor_devices"] stored = result[switch["id"]]["neighbor_devices"]
@@ -1004,6 +1045,13 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None) stored.pop(neighbor["local_port"], None)
else: else:
stored[neighbor["local_port"]] = chosen 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) network_map = dict(self.previous_network_map)
for item, combo, status in self.network_rows: for item, combo, status in self.network_rows:
chosen = combo.currentData() chosen = combo.currentData()
+4
View File
@@ -31,6 +31,10 @@ def _matches(record, key, value):
vrf = getattr(record, "vrf", None) vrf = getattr(record, "vrf", None)
vrf_id = vrf if isinstance(vrf, int) else getattr(vrf, "id", 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 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": if key == "address":
return str(getattr(record, "address", "")).split("/")[0] == str(value).split("/")[0] return str(getattr(record, "address", "")).split("/")[0] == str(value).split("/")[0]
if key.endswith("_id") and not hasattr(record, key): if key.endswith("_id") and not hasattr(record, key):
+22
View File
@@ -1,3 +1,4 @@
import ipaddress
from types import SimpleNamespace from types import SimpleNamespace
import pytest 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] 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) 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 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)
+44
View File
@@ -295,3 +295,47 @@ def test_reparse_fixes_older_exports():
assert rebuilt["discovered_at"] == 123 assert rebuilt["discovered_at"] == 123
assert next(item for item in rebuilt["interfaces"] if item["name"] == "2")["neighbor"]["system_name"] == "AP-005" 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": {}} 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"] == ""
+67
View File
@@ -612,3 +612,70 @@ def test_vlans_of_another_site_are_only_labelled():
assert [note for note in report["notes"] if "VLAN 10" in note] == [ 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 " "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)"] "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