feat: VLAN labels, automatic port mapping and neighbour review for switches

- Read VLAN membership (untagged and tagged) from the running configuration
  on Aruba CX, ArubaOS-Switch and HPE Comware and write it to the NetBox
  interface label (e.g. "10", "1,20-22", "all")
- Keep only VLAN-related configuration lines in the raw data / offline export
- Map switch ports to NetBox interfaces with differing names automatically:
  equal name, equal port number (1/1/5 <-> 5), then natural order
- New "Review mapping" dialog before the preview: correct port mappings and
  assign each LLDP/CDP neighbour to a device of the switch's tenant group;
  choices are stored per switch in the profile
- Ignore the local Gitea token file

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-30 13:16:22 +01:00
1 parent f249c3e1c9
commit 39a29b9230
8 files changed
+750 -29

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ output/
# Lokale Konfigurationen und Zugangsdaten
config.json
*.tmp
.gitea-token
+8
View File
@@ -54,6 +54,14 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
sent after confirmation
- Interface types from device type templates are left untouched; Comware short
names (`GE1/0/1`) are mapped to full NetBox names (`GigabitEthernet1/0/1`)
- 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
- 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
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
+393 -20
View File
@@ -29,6 +29,14 @@ IP_COMMANDS = {
"hpe_comware": ("display ip interface brief", "display ipv6 interface brief"),
}
# The running configuration is the only output that shows untagged and tagged
# VLAN membership per port on all three platforms.
CONFIG_COMMANDS = {
"aruba_cx": "show running-config",
"aruba_aos": "show running-config",
"hpe_comware": "display current-configuration interface",
}
LLDP_CONTROL = {
"aruba_cx": {
"status": "show lldp configuration",
@@ -311,6 +319,10 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
cdp_ports.append(match.group(1))
details = [_run_cli_command(channel, f"show cdp neighbor-info {port}", timeout=30) for port in cdp_ports]
cdp_neighbors = "\n".join([cdp_summary, *details])
config_output = _run_cli_command(channel, CONFIG_COMMANDS[platform], timeout=90)
if CLI_ERROR.search(config_output[:500]):
log(f"{config.get('name', config['host'])}: Konfiguration nicht lesbar – VLANs werden nicht übernommen")
config_output = ""
return {
"platform": platform,
"interfaces": interfaces,
@@ -318,6 +330,7 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
"ipv6_interfaces": ip_outputs[1],
"neighbors": neighbors,
"cdp_neighbors": cdp_neighbors,
"config": config_output,
"lldp_status": lldp_status,
"lldp_disabled": lldp_disabled and not lldp_enabled_automatically,
"lldp_enabled_automatically": lldp_enabled_automatically,
@@ -591,8 +604,177 @@ def _parse_neighbor_table(output):
return neighbors
# --------------------------------------------------------------------------
# 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")
def parse_vlan_list(text):
"""``10,20-22`` (Aruba) or ``10 20 to 22`` (Comware) → set of VLAN IDs."""
text = re.sub(r"\s+to\s+", "-", text.strip(), flags=re.I)
vlans = set()
for part in re.split(r"[,\s]+", text):
match = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
if not match:
continue
start, end = int(match.group(1)), int(match.group(2) or match.group(1))
if 1 <= start <= end <= 4094:
vlans.update(range(start, end + 1))
return vlans
def _expand_ports(text):
"""ArubaOS-S port lists such as ``1-4,A1-A2,1/5-1/8,Trk1``."""
ports = []
for part in (item.strip() for item in text.split(",")):
match = _PORT_RANGE.match(part)
if match and int(match.group(2)) <= int(match.group(3)):
ports += [f"{match.group(1)}{number}" for number in range(int(match.group(2)), int(match.group(3)) + 1)]
elif part:
ports.append(part)
return ports
def _membership(untagged=(), tagged=(), tagged_all=False):
untagged = set(untagged)
return {"untagged": sorted(untagged), "tagged": sorted(set(tagged) - untagged), "tagged_all": bool(tagged_all)}
def _config_blocks(config, header):
"""Yield ``(header match, body lines)`` for indented configuration blocks."""
current, body = None, []
for line in clean_output(config).splitlines():
match = header.match(line)
if match:
if current:
yield current, body
current, body = match, []
elif current and line[:1] in (" ", "\t"):
body.append(line.strip())
elif current:
yield current, body
current, body = None, []
if current:
yield current, body
def _parse_aos_vlans(config):
ports = {}
for match, body in _config_blocks(config, re.compile(r"^vlan\s+(\d+)\s*$", re.I)):
vlan = int(match.group(1))
for line in body:
member = re.match(r"^(untagged|tagged)\s+(\S+)", line, flags=re.I)
if member:
for port in _expand_ports(member.group(2)):
entry = ports.setdefault(interface_key(port), {"untagged": set(), "tagged": set()})
entry[member.group(1).lower()].add(vlan)
return {key: _membership(entry["untagged"], entry["tagged"]) for key, entry in ports.items()}
def _parse_cx_vlans(config):
result = {}
for match, body in _config_blocks(config, re.compile(r"^interface\s+(.+?)\s*$", re.I)):
text = "\n".join(body)
access = re.search(r"(?im)^vlan access (\d+)", text)
native = re.search(r"(?im)^vlan trunk native (\d+)(\s+tag)?", text)
allowed = re.findall(r"(?im)^vlan trunk allowed (.+)$", text)
if access:
result[interface_key(match.group(1))] = _membership([int(access.group(1))])
elif native or allowed:
native_id = int(native.group(1)) if native else 1
tagged_native = bool(native and native.group(2))
tagged = set().union(*(parse_vlan_list(item) for item in allowed))
everything = not allowed or any(item.strip().lower() == "all" for item in allowed)
untagged = [] if tagged_native else [native_id]
result[interface_key(match.group(1))] = _membership(untagged, tagged | ({native_id} if tagged_native else set()),
everything)
elif re.search(r"(?im)^no routing\b", text):
result[interface_key(match.group(1))] = _membership([1])
return result
def _parse_comware_vlans(config):
result = {}
for match, body in _config_blocks(config, re.compile(r"^interface\s+(\S+)\s*$", re.I)):
name = match.group(1)
prefix = re.match(r"^[a-z]+", interface_key(name))
if not prefix or prefix.group(0) not in ("ge", "xge", "wge", "fge", "hge", "fe", "bagg"):
continue
text = "\n".join(body)
if re.search(r"(?im)^port link-mode route", text):
continue
link_type = re.search(r"(?im)^port link-type (\w+)", text)
link_type = link_type.group(1).lower() if link_type else "access"
if link_type == "trunk":
pvid = re.search(r"(?im)^port trunk pvid vlan (\d+)", text)
pvid = int(pvid.group(1)) if pvid else 1
permitted, everything = {1}, False
for undo, vlans in re.findall(r"(?im)^(undo )?port trunk permit vlan (.+)$", text):
if vlans.strip().lower() == "all":
everything = not undo
elif undo:
permitted -= parse_vlan_list(vlans)
else:
permitted |= parse_vlan_list(vlans)
untagged = [pvid] if everything or pvid in permitted else []
result[interface_key(name)] = _membership(untagged, permitted, everything)
elif link_type == "hybrid":
untagged, tagged = set(), set()
for vlans, mode in re.findall(r"(?im)^port hybrid vlan (.+?) (untagged|tagged)\s*$", text):
(untagged if mode.lower() == "untagged" else tagged).update(parse_vlan_list(vlans))
result[interface_key(name)] = _membership(untagged or {1}, tagged)
else:
access = re.search(r"(?im)^port access vlan (\d+)", text)
result[interface_key(name)] = _membership([int(access.group(1)) if access else 1])
return result
def parse_vlans(config, platform):
"""VLAN membership per port, keyed by :func:`interface_key`."""
if not config:
return {}
parser = {"aruba_aos": _parse_aos_vlans, "aruba_cx": _parse_cx_vlans, "hpe_comware": _parse_comware_vlans}
return parser[platform](config) if platform in parser else {}
def _compress_vlans(vlans):
parts, values = [], sorted(vlans)
start = previous = None
for value in values + [None]:
if start is not None and value == previous + 1:
previous = value
continue
if start is not None:
parts.append(str(start) if start == previous else f"{start}-{previous}")
start = previous = value
return ",".join(parts)
def vlan_label(vlans, limit=64):
"""All VLANs of a port (untagged and tagged) as short NetBox label."""
if not vlans:
return ""
if vlans.get("tagged_all"):
return "all"
text = _compress_vlans(set(vlans.get("untagged", [])) | set(vlans.get("tagged", [])))
if len(text) > limit:
text = text[:limit - 1].rsplit(",", 1)[0] + "…"
return text
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))
def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform)
vlans = parse_vlans(outputs.get("config", ""), platform)
for interface in interfaces:
interface["vlans"] = vlans.get(interface_key(interface["name"]))
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", ""))
@@ -625,7 +807,9 @@ def build_snapshot(outputs, platform):
"neighbors": neighbors,
"lldp_neighbors": lldp_neighbors,
"cdp_neighbors": cdp_neighbors,
"raw": outputs,
"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")),
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
@@ -712,6 +896,179 @@ def _device_interfaces(nb, device_id):
return records
MATCH_METHODS = {
"name": "gleicher Name",
"number": "gleiche Portnummer",
"order": "Reihenfolge",
"manual": "manuell",
"new": "neu anlegen",
}
_PORT_NAME = re.compile(r"^[A-Za-z\- ]*\d+(?:/\d+)*$")
def _natural_key(name):
return [int(part) if part.isdigit() else part.casefold() for part in re.split(r"(\d+)", name)]
def _port_number(name):
"""Last number of a port-like name: ``1/1/5`` → 5, ``GE1/0/5`` → 5, ``5`` → 5."""
name = (name or "").strip()
return int(re.search(r"(\d+)$", name).group(1)) if _PORT_NAME.match(name) else None
def _record_type(record):
value = getattr(record, "type", None)
return getattr(value, "value", value if isinstance(value, str) else None) or ""
def _physical_record(record):
return (_record_type(record) not in ("virtual", "lag", "bridge")
and not re.match(r"^(?:vlan|lo|mgmt|oobm)", interface_key(record.name)))
def _physical_interface(interface):
return netbox_interface_type(interface) not in ("virtual", "lag")
def match_interfaces(interfaces, records, manual=None):
"""Assign NetBox interfaces to discovered switch interfaces.
Order of precedence: stored manual choices (``{switch name: NetBox name}``,
an empty NetBox name means "create new"), equal names across vendor
spellings, an equal last port number (``1/1/5`` ↔ ``5``) and finally the
natural order of the remaining physical ports when both sides have the
same number left. Returns ``{switch name: (record or None, method)}``.
"""
manual = manual or {}
by_name = {record.name: record for record in records}
by_key = {}
for record in records:
key = interface_key(record.name)
if key not in by_key or len(record.name) > len(by_key[key].name):
by_key[key] = record
result, used = {}, set()
def assign(interface, record, method):
result[interface["name"]] = (record, method)
if record is not None:
used.add(record.id)
for interface in interfaces:
if interface["name"] not in manual:
continue
target = manual[interface["name"]]
record = by_name.get(target) if target else None
if target and (record is None or record.id in used):
continue # stale choice – fall back to the automatic match
assign(interface, record, "manual" if record else "new")
for interface in interfaces:
if interface["name"] not in result:
record = by_key.get(interface_key(interface["name"]))
if record and record.id not in used:
assign(interface, record, "name")
open_ports = [item for item in interfaces if item["name"] not in result and _physical_interface(item)]
open_records = [record for record in records if record.id not in used and _physical_record(record)]
ports_by_number, records_by_number = {}, {}
for item in open_ports:
ports_by_number.setdefault(_port_number(item["name"]), []).append(item)
for record in open_records:
records_by_number.setdefault(_port_number(record.name), []).append(record)
for number, ports in ports_by_number.items():
candidates = records_by_number.get(number, [])
if number is not None and len(ports) == 1 and len(candidates) == 1:
assign(ports[0], candidates[0], "number")
open_ports = [item for item in open_ports if item["name"] not in result]
open_records = [record for record in open_records if record.id not in used]
if open_ports and len(open_ports) == len(open_records):
open_ports.sort(key=lambda item: _natural_key(item["name"]))
open_records.sort(key=lambda record: _natural_key(record.name))
for interface, record in zip(open_ports, open_records):
assign(interface, record, "order")
for interface in interfaces:
result.setdefault(interface["name"], (None, "new"))
return result
def _resolve_device(nb, config):
"""The NetBox device of a switch config, or an error text."""
if config.get("device_id"):
device = nb.dcim.devices.get(int(config["device_id"]))
return (device, None) if device else (None, f"NetBox-Gerät #{config['device_id']} existiert nicht mehr")
# Switches captured in offline mode are only known by name.
matches = list(nb.dcim.devices.filter(name=config["name"]))
if len(matches) != 1:
return None, f"NetBox-Gerät „{config['name']}“ " + ("nicht gefunden" if not matches else "ist nicht eindeutig")
return matches[0], None
def candidate_devices(nb, device):
"""Devices a neighbor may be assigned to: the tenant group of the switch.
Falls back to the switch's tenant and, without a tenant, to all devices.
Returns ``(scope description, [{"id", "name"}])``.
"""
tenant_id = related_id(device, "tenant")
scope, devices = "alle Geräte", None
if tenant_id:
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
if group_id:
group = getattr(tenant, "group", None)
scope = f"Mandantengruppe {getattr(group, 'name', None) or group_id}"
devices = nb.dcim.devices.filter(tenant_group_id=group_id)
else:
scope = f"Mandant {getattr(tenant, 'name', None) or tenant_id}"
devices = nb.dcim.devices.filter(tenant_id=tenant_id)
if devices is None:
devices = nb.dcim.devices.all()
rows = [{"id": item.id, "name": item.name} for item in devices if getattr(item, "name", None) and item.id != device.id]
return scope, sorted(rows, key=lambda row: row["name"].casefold())
def plan_switch_sync(nb, config, snapshot):
"""Proposed interface mapping and neighbor devices for the review dialog."""
device, error = _resolve_device(nb, config)
if error:
return {"error": error}
records = list(nb.dcim.interfaces.filter(device_id=device.id))
matches = match_interfaces(snapshot["interfaces"], records, config.get("interface_map"))
scope, devices = candidate_devices(nb, device)
known = {row["id"] for row in devices}
lookup = _RemoteLookup(nb)
manual = config.get("neighbor_devices") or {}
neighbors = []
for neighbor in snapshot["neighbors"]:
local = neighbor.get("local_port")
if local in manual:
device_id, method = int(manual[local]) or None, "manual"
remote = nb.dcim.devices.get(device_id) if device_id else None
else:
remote = lookup.device(neighbor)
device_id, method = (remote.id if remote else None), "auto"
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))
devices.sort(key=lambda row: row["name"].casefold())
return {
"error": None,
"device": {"id": device.id, "name": device.name},
"interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "vlan_label": vlan_label(item.get("vlans"))}
for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]]
],
"netbox_interfaces": sorted((record.name for record in records), key=_natural_key),
"neighbors": neighbors,
"device_scope": scope,
"devices": devices,
}
class _RemoteLookup:
"""Find neighbor devices and interfaces in NetBox, cached per sync run."""
@@ -752,6 +1109,13 @@ class _RemoteLookup:
record = records.get(interface_key(candidate))
if record:
return record
# Device types often name ports "1", "2", … while LLDP reports "1/1/1".
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 len(found) == 1:
return found[0]
return None
@@ -772,37 +1136,38 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
device-type templates and manual corrections in NetBox are preserved.
"""
report = _new_report()
if config.get("device_id"):
device_id = int(config["device_id"])
device = nb.dcim.devices.get(device_id)
if not device:
report["errors"].append(f"NetBox-Gerät #{device_id} existiert nicht mehr")
device, error = _resolve_device(nb, config)
if error:
report["errors"].append(error)
return report
else:
# Switches captured in offline mode are only known by name.
matches = list(nb.dcim.devices.filter(name=config["name"]))
if len(matches) != 1:
report["errors"].append(f"NetBox-Gerät „{config['name']}“ " +
("nicht gefunden" if not matches else "ist nicht eindeutig"))
return report
device = matches[0]
device_id = device.id
tenant_id = related_id(device, "tenant")
existing = _device_interfaces(nb, device_id)
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map"))
records = {}
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record = existing.get(key)
record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans"))
try:
if record:
changes = {}
if bool(getattr(record, "enabled", True)) != bool(interface.get("enabled", True)):
changes["enabled"] = bool(interface.get("enabled", True))
# Only written when VLANs are known, so manual labels survive
# routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label
if changes:
report["interfaces_updated"] += 1
state = "aktivieren" if changes["enabled"] else "deaktivieren"
report["changes"].append(f"Interface {record.name}: {state}")
texts = []
if "enabled" in changes:
texts.append("aktivieren" if changes["enabled"] else "deaktivieren")
if "label" in changes:
texts.append(f"Label „{label}“")
target = record.name if method == "name" else f"{record.name} ({interface['name']})"
report["changes"].append(f"Interface {target}: {', '.join(texts)}")
if not dry_run:
record.update(changes)
else:
@@ -814,13 +1179,15 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
"type": netbox_interface_type(interface),
"enabled": bool(interface.get("enabled", True)),
}
if label:
payload["label"] = label
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})")
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})"
+ (f", Label „{label}“" if label else ""))
if not dry_run:
record = nb.dcim.interfaces.create(payload)
existing[key] = record
if record and not dry_run and interface.get("mac_address"):
assign_mac(nb, record, interface["mac_address"], "dcim.interface")
records[key] = record
@@ -871,6 +1238,7 @@ 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 {}
for neighbor in snapshot["neighbors"]:
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
try:
@@ -881,6 +1249,11 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if local is not None and getattr(local, "cable", None):
report["cables_skipped"] += 1
continue
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
else:
remote_device = lookup.device(neighbor)
if not remote_device:
report["cables_skipped"] += 1
+40 -4
View File
@@ -17,6 +17,7 @@ from netbox_sync.core.switches import (
PLATFORMS,
describe_snapshot,
discover_switch,
plan_switch_sync,
suggest_platform,
sync_snapshot_to_netbox,
)
@@ -24,7 +25,7 @@ from netbox_sync.core.virtualization import load_source
from netbox_sync.core.vm_sync import VMSyncEngine
from netbox_sync.ui import widgets
from netbox_sync.ui.client_dialogs import ClientPreviewDialog, ClientTargetDialog
from netbox_sync.ui.dialogs import SyncPreviewDialog
from netbox_sync.ui.dialogs import SwitchMappingDialog, SyncPreviewDialog
from netbox_sync.ui.tasks import area_log, logger
@@ -412,8 +413,44 @@ class Actions:
connect = self._connector()
log = area_log("switch")
def preview(ctx):
def plan(ctx):
nb = connect(ctx)
plans = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: ordne Schnittstellen und Nachbarn zu …")
plans.append((switch, plan_switch_sync(nb, switch, snapshot)))
return nb, plans
def review(result):
nb, plans = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
reviewable = [(switch, item) for switch, item in plans if not item["error"]]
needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"])
for _switch, item in reviewable)
def ask():
# 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)
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
for switch, _snapshot in items:
choices = dialog.result.get(switch["id"])
if choices:
switch.update(choices)
if switch["id"] in stored:
stored[switch["id"]].update(choices)
self.state.touch()
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask)
def preview(ctx, nb):
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
@@ -423,7 +460,6 @@ class Actions:
def show_preview(result):
nb, reports = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
def ask():
# Opened after the preview task has fully finished, so the
@@ -433,7 +469,7 @@ class Actions:
self._apply_switch_sync(nb, items, create_cables, log)
QTimer.singleShot(0, ask)
self.tasks.run(preview, title="Änderungen berechnen", area="switch", on_success=show_preview,
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):
+144 -3
View File
@@ -3,7 +3,7 @@
import uuid
from PySide6.QtCore import QThreadPool, Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtGui import QColor, QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
@@ -16,6 +16,8 @@ from PySide6.QtWidgets import (
QPlainTextEdit,
QPushButton,
QSpinBox,
QTableWidget,
QTableWidgetItem,
QTabWidget,
QTreeWidget,
QTreeWidgetItem,
@@ -24,7 +26,7 @@ from PySide6.QtWidgets import (
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import PLATFORMS, forget_host_key
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -566,10 +568,149 @@ class SyncPreviewDialog(_Dialog):
self.root.addWidget(buttons)
class SwitchMappingDialog(_Dialog):
"""Review interface mapping and neighbor devices before computing changes.
``plans`` is a list of ``(switch, plan)`` from ``plan_switch_sync``. After
acceptance ``result`` maps switch IDs to ``interface_map`` and
``neighbor_devices`` to be stored in the profile.
"""
NEW = "\x00new"
def __init__(self, parent, plans, create_cables):
super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, deren Name auf dem Switch anders lautet als in NetBox, wurden automatisch "
"zugeordnet. Bitte prüfen und bei Bedarf korrigieren – die Auswahl wird im Profil gespeichert.",
width=820)
self.resize(980, 660)
self.plans = plans
self.result = None
tabs = QTabWidget()
# Interfaces --------------------------------------------------------
interface_page = QWidget()
interface_layout = QVBoxLayout(interface_page)
interface_layout.setContentsMargins(0, 12, 0, 0)
self.only_unclear = checkbox("Nur Schnittstellen ohne Namensgleichheit anzeigen", True)
interface_layout.addWidget(self.only_unclear)
self.interface_table = QTableWidget(0, 5)
self.interface_table.setHorizontalHeaderLabels(["Switch", "Schnittstelle (Switch)", "VLANs",
"NetBox-Schnittstelle", "Zuordnung"])
self.interface_rows = []
for switch, plan in plans:
vlans = {item["name"]: item["vlan_label"] for item in plan["interfaces"]}
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in plan["netbox_interfaces"]]
for item in plan["interfaces"]:
if not item["physical"] and item["method"] in ("name", "new"):
continue
row = self.interface_table.rowCount()
self.interface_table.insertRow(row)
combo = QComboBox()
for text, data in choices:
combo.addItem(text, data)
combo.setCurrentIndex(max(0, combo.findData(item["netbox_name"] or self.NEW)))
for column, text in enumerate((switch["name"], item["name"], vlans.get(item["name"], ""))):
self.interface_table.setItem(row, column, QTableWidgetItem(text))
self.interface_table.setCellWidget(row, 3, combo)
method = QTableWidgetItem(MATCH_METHODS.get(item["method"], item["method"]))
if item["method"] in ("number", "order"):
method.setForeground(QColor(theme.color("warning")))
self.interface_table.setItem(row, 4, method)
self.interface_rows.append((row, switch, item, combo))
self._prepare_table(self.interface_table, (140, 170, 110, 220, 150))
interface_layout.addWidget(self.interface_table, 1)
unclear = sum(1 for _row, _switch, item, _combo in self.interface_rows if item["method"] != "name")
tabs.addTab(interface_page, f"Schnittstellen ({unclear} zu prüfen)")
self.only_unclear.toggled.connect(self._filter_interfaces)
self._filter_interfaces(True)
# Neighbors -----------------------------------------------------------
self.neighbor_rows = []
if create_cables:
neighbor_page = QWidget()
neighbor_layout = QVBoxLayout(neighbor_page)
neighbor_layout.setContentsMargins(0, 12, 0, 0)
scopes = sorted({plan["device_scope"] for _switch, plan in plans})
neighbor_layout.addWidget(label(
"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.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
"Nachbar-Port", "NetBox-Gerät"])
for switch, plan in plans:
for neighbor in plan["neighbors"]:
row = self.neighbor_table.rowCount()
self.neighbor_table.insertRow(row)
combo = SearchableComboBox("Gerät suchen …")
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 "")
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))
neighbor_layout.addWidget(self.neighbor_table, 1)
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau")
self.root.addWidget(buttons)
@staticmethod
def _prepare_table(table, widths):
table.verticalHeader().hide()
table.setEditTriggers(QTableWidget.NoEditTriggers)
table.setSelectionMode(QTableWidget.NoSelection)
table.horizontalHeader().setStretchLastSection(True)
for column, width in enumerate(widths):
table.setColumnWidth(column, width)
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 {})}
for switch, _plan in self.plans}
used = {}
for _row, switch, item, combo in self.interface_rows:
chosen = combo.currentData()
target = "" if chosen == self.NEW else chosen
mapping = result[switch["id"]]["interface_map"]
if target and (switch["id"], target) in used:
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
f"({used[(switch['id'], target)]}, {item['name']}).")
return
if target:
used[(switch["id"], target)] = item["name"]
# Plain name matches stay automatic; everything else is remembered.
if item["method"] == "name" and target == item["netbox_name"]:
mapping.pop(item["name"], None)
else:
mapping[item["name"]] = target
for switch, neighbor, combo in self.neighbor_rows:
chosen = combo.valid_data()
chosen = int(chosen or 0)
stored = result[switch["id"]]["neighbor_devices"]
if neighbor["method"] == "auto" and chosen == (neighbor.get("device_id") or 0):
stored.pop(neighbor["local_port"], None)
else:
stored[neighbor["local_port"]] = chosen
self.result = result
super().accept()
class RawDataDialog(_Dialog):
SECTIONS = {
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
}
def __init__(self, parent, items, selected_id=None):
+2 -1
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS
from netbox_sync.core.switches import PLATFORMS, vlan_label
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
@@ -108,6 +108,7 @@ 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(row.get("vlans"))),
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", "")),
+62 -1
View File
@@ -2,7 +2,7 @@ from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record
from netbox_sync.core.switches import build_snapshot, sync_snapshot_to_netbox
from netbox_sync.core.switches import build_snapshot, match_interfaces, plan_switch_sync, sync_snapshot_to_netbox
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
@@ -63,3 +63,64 @@ def test_offline_switch_is_resolved_by_name():
missing = sync_snapshot_to_netbox(nb, {"id": "s", "name": "unbekannt"}, snapshot, dry_run=True)
assert missing["errors"] == ["NetBox-Gerät „unbekannt“ nicht gefunden"]
def _numbered_setup():
"""NetBox device type with ports "1" … "3", switch reports "1/1/x"."""
nb = FakeNetBox()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=7, name="Muster", group=group))
nb.dcim.devices.records += [
Record(nb.dcim.devices, id=1, name="access-01", tenant=SimpleNamespace(id=7), tenant_group=group),
Record(nb.dcim.devices, id=2, name="server-01", tenant=SimpleNamespace(id=7), tenant_group=group),
Record(nb.dcim.devices, id=3, name="fremd", tenant=None, tenant_group=None),
]
for index, name in enumerate(("1", "2", "3"), start=1):
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=1),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
label=""))
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=20, name="eth0", device=SimpleNamespace(id=2),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
interfaces = [
{"name": f"1/1/{number}", "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000,
"ip_addresses": [], "vlans": {"untagged": [10 * number], "tagged": [], "tagged_all": False}}
for number in (1, 2, 3)
]
neighbor = {"local_port": "1/1/2", "system_name": "unbekannt", "remote_port": "eth0", "port_description": "",
"management_ip": "", "protocol": "LLDP"}
snapshot = {"interfaces": interfaces, "neighbors": [neighbor]}
return nb, {"id": "s", "name": "access-01", "device_id": 1}, snapshot
def test_ports_are_mapped_by_number_and_labelled_with_vlans():
nb, switch, snapshot = _numbered_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] and report["interfaces_created"] == 0
assert sorted(nb.dcim.interfaces.updates) == [(1, {"label": "10"}), (2, {"label": "20"}), (3, {"label": "30"})]
def test_ports_are_mapped_by_order_and_manual_choice_wins():
nb, switch, snapshot = _numbered_setup()
for item, name in zip(snapshot["interfaces"], ("1/0/1", "1/0/2", "2/0/1")):
item["name"] = name # "2/0/1" breaks the unique port numbers
matches = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1))
assert {name: (record.name, method) for name, (record, method) in matches.items()} == {
"1/0/1": ("1", "order"), "1/0/2": ("2", "number"), "2/0/1": ("3", "order")}
manual = match_interfaces(snapshot["interfaces"], nb.dcim.interfaces.filter(device_id=1), {"2/0/1": ""})
assert manual["2/0/1"] == (None, "new")
def test_plan_offers_tenant_group_devices_and_manual_neighbor_creates_cable():
nb, switch, snapshot = _numbered_setup()
plan = plan_switch_sync(nb, switch, snapshot)
assert plan["device_scope"] == "Mandantengruppe Kunde"
assert [device["name"] for device in plan["devices"]] == ["server-01"]
assert plan["neighbors"][0]["device_id"] is None
assert {item["name"]: item["method"] for item in plan["interfaces"]}["1/1/1"] == "number"
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
assert report["cables_created"] == 0
switch["neighbor_devices"] = {"1/1/2": 2}
report = sync_snapshot_to_netbox(nb, switch, snapshot)
cable = nb.dcim.cables.created[0]
assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20
+100
View File
@@ -201,3 +201,103 @@ def test_speed_parsing():
assert switches.speed_mbps("1000FDx") == 1000
assert switches.speed_mbps("10GigFD") == 10000
assert switches.speed_mbps("UP 1G(a) F(a)") == 1000
AOS_CONFIG = """
vlan 1
name "DEFAULT_VLAN"
untagged 1,3-4,Trk1
no untagged 2
exit
vlan 10
name "Server"
untagged 2
tagged 49,Trk1
exit
vlan 20
tagged 1/1-1/2,49
exit
"""
CX_CONFIG = """
interface 1/1/1
no shutdown
no routing
vlan access 10
interface 1/1/2
no routing
vlan trunk native 1
vlan trunk allowed 1,20-22
interface 1/1/3
no routing
interface 1/1/49
ip address 10.0.0.1/24
interface lag 1
no routing
vlan trunk native 5 tag
vlan trunk allowed all
"""
COMWARE_CONFIG = """
#
interface GigabitEthernet1/0/1
port link-mode bridge
port access vlan 10
#
interface GigabitEthernet1/0/2
port link-mode bridge
#
interface GigabitEthernet1/0/3
port link-type hybrid
port hybrid vlan 30 40 tagged
port hybrid vlan 1 untagged
#
interface Ten-GigabitEthernet1/0/49
port link-mode bridge
port link-type trunk
undo port trunk permit vlan 1
port trunk permit vlan 10 20 to 22
port trunk pvid vlan 10
#
interface Vlan-interface10
ip address 10.0.0.1 255.255.255.0
#
"""
def test_parse_vlans_aruba_aos():
vlans = switches.parse_vlans(AOS_CONFIG, "aruba_aos")
assert vlans[interface_key("1")] == {"untagged": [1], "tagged": [], "tagged_all": False}
assert vlans[interface_key("2")]["untagged"] == [10]
assert vlans[interface_key("49")] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
assert vlans[interface_key("Trk1")] == {"untagged": [1], "tagged": [10], "tagged_all": False}
assert vlans[interface_key("1/2")]["tagged"] == [20]
def test_parse_vlans_aruba_cx():
vlans = switches.parse_vlans(CX_CONFIG, "aruba_cx")
assert switches.vlan_label(vlans[interface_key("1/1/1")]) == "10"
assert switches.vlan_label(vlans[interface_key("1/1/2")]) == "1,20-22"
assert switches.vlan_label(vlans[interface_key("1/1/3")]) == "1"
assert interface_key("1/1/49") not in vlans
assert switches.vlan_label(vlans[interface_key("lag1")]) == "all"
def test_parse_vlans_comware():
vlans = switches.parse_vlans(COMWARE_CONFIG, "hpe_comware")
assert switches.vlan_label(vlans[interface_key("GE1/0/1")]) == "10"
assert switches.vlan_label(vlans[interface_key("GE1/0/2")]) == "1"
assert vlans[interface_key("GE1/0/3")] == {"untagged": [1], "tagged": [30, 40], "tagged_all": False}
assert vlans[interface_key("XGE1/0/49")] == {"untagged": [10], "tagged": [20, 21, 22], "tagged_all": False}
assert interface_key("Vlan-interface10") not in vlans
def test_vlan_label_is_short_and_snapshot_hides_config():
many = {"untagged": [], "tagged": list(range(100, 400, 2)), "tagged_all": False}
assert len(switches.vlan_label(many)) <= 64 and switches.vlan_label(many).endswith("…")
snapshot = build_snapshot({"interfaces": COMWARE_BRIEF, "neighbors": "",
"config": COMWARE_CONFIG + "\n local-user admin\n password hash $h$secret\n"},
"hpe_comware")
by_name = {item["name"]: item for item in snapshot["interfaces"]}
assert by_name["GigabitEthernet1/0/1"]["vlans"]["untagged"] == [10]
assert "config" not in snapshot["raw"] and "secret" not in snapshot["raw"]["vlan_config"]