Compare commits

..
10 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 3c8bc7879c chore: release 4.13.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:50 +01:00
MrBlakeandClaude Opus 5.5 770edc4a03 feat: optional running-config backup as NetBox attachment
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:49 +01:00
MrBlakeandClaude Opus 5.5 eee60d26ad chore: release 4.12.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:06:11 +01:00
MrBlakeandClaude Opus 5.5 63fd7b987a feat: LAG members get their LAG in the label and NetBox LAG field
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:06:10 +01:00
MrBlakeandClaude Opus 5.5 899b4c58fc chore: release 4.11.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:27:10 +01:00
MrBlakeandClaude Opus 5.5 89fe37ea04 feat: fill in detected stacks in the optional NetBox Utilities plugin
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:27:09 +01:00
MrBlakeandClaude Opus 5.5 34b1391ff0 chore: release 4.10.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 08:41:38 +01:00
MrBlakeandClaude Opus 5.5 340f404f94 fix: allow equal interface names on different stack member devices
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 08:41:24 +01:00
MrBlakeandClaude Opus 5.5 f1af9f8f86 chore: release 4.10.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:22 +01:00
MrBlakeandClaude Opus 5.5 2fb6ac38ec feat: ignore Sophos sites without site and tenant
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:21 +01:00
9 changed files with 383 additions and 29 deletions

No files matched your search

+19 -1
View File
@@ -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 - 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`; 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 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` ↔ - 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 `1/1/5`): equal name, then equal port number, then natural order
- **Mapping review** before the preview: non-obvious port mappings and every - **Mapping review** before the preview: non-obvious port mappings and every
@@ -87,6 +93,17 @@ 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 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; NetBox virtual chassis positions, stored per switch) and gets its own ports;
LAGs and VLAN interfaces stay on the switch's device LAGs and VLAN interfaces stay on the switch's device
- 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 - 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 - The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on explicitly switched on
@@ -102,7 +119,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Sophos sites are mapped to NetBox sites (suggested by name, stored per - Sophos sites are mapped to NetBox sites (suggested by name, stored per
profile); the site is optional – APs without one go to a default site, since profile); the site is optional – APs without one go to a default site, since
NetBox requires a site for every device. The tenant is mandatory and chosen NetBox requires a site for every device. The tenant is mandatory and chosen
deliberately per Sophos site – it is never preselected deliberately per Sophos site – it is never preselected. Sophos sites left without site and tenant are
ignored (stored per profile) and not transferred
- New APs are created with Sophos device type, role, site, serial number, - New APs are created with Sophos device type, role, site, serial number,
firmware, interface with MAC and IP address (primary IPv4); existing ones get firmware, interface with MAC and IP address (primary IPv4); existing ones get
missing serial numbers and tenants, optionally the Sophos name. Preview before missing serial numbers and tenants, optionally the Sophos name. Preview before
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.10.3" #define AppVersion "4.13.0"
#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.10.3" APP_VERSION = "4.13.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+164 -5
View File
@@ -1,5 +1,7 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches.""" """SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import hashlib
import io
import ipaddress import ipaddress
import re import re
import threading import threading
@@ -608,8 +610,8 @@ def _parse_neighbor_table(output):
# VLAN membership from the running configuration # VLAN membership from the running configuration
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$") _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") _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): def parse_vlan_list(text):
@@ -776,6 +778,44 @@ def vlan_label(vlans, limit=64):
return text 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): def _vlan_config_excerpt(config):
"""Keep only VLAN-related lines – the full configuration may contain secrets.""" """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)) return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
@@ -826,8 +866,13 @@ def parse_stack(config, platform, interfaces=()):
def build_snapshot(outputs, platform): def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform) interfaces = parse_interfaces(outputs["interfaces"], platform)
vlans = parse_vlans(outputs.get("config", ""), platform) vlans = parse_vlans(outputs.get("config", ""), platform)
lags = parse_lags(outputs.get("config", ""), platform)
for interface in interfaces: for interface in interfaces:
interface["vlans"] = vlans.get(interface_key(interface["name"])) 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) interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
lldp_neighbors = parse_neighbors(outputs["neighbors"]) lldp_neighbors = parse_neighbors(outputs["neighbors"])
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", "")) cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
@@ -863,6 +908,7 @@ def build_snapshot(outputs, platform):
"raw": {**{key: value for key, value in outputs.items() if key != "config"}, "raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})}, **({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")), "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", "")), "vlan_names": parse_vlan_names(outputs.get("config", "")),
"stack": parse_stack(outputs.get("config", ""), platform, interfaces), "stack": parse_stack(outputs.get("config", ""), platform, interfaces),
"lldp_disabled": outputs.get("lldp_disabled", False), "lldp_disabled": outputs.get("lldp_disabled", False),
@@ -1357,7 +1403,7 @@ def plan_switch_sync(nb, config, snapshot):
"interfaces": [ "interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method, {"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id, "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 item in snapshot["interfaces"] if owners[item["name"]] is not None
for record, method in [matches[item["name"]]] for record, method in [matches[item["name"]]]
], ],
@@ -1583,7 +1629,115 @@ def _new_report():
} }
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 _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.
"""
config = snapshot.get("config_backup")
if not config:
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
return
digest = hashlib.sha256(f"{device.id}\n{config}".encode("utf-8")).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}") + ".txt"
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(config.encode("utf-8")), "text/plain"),
})
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 sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
backup_config=False):
"""Write a discovery snapshot to NetBox. """Write a discovery snapshot to NetBox.
With ``dry_run`` nothing is written; the returned report lists what would With ``dry_run`` nothing is written; the returned report lists what would
@@ -1611,6 +1765,7 @@ 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 skipped = sum(1 for name, owner in owners.items() if owner is None
and stack_member(name, snapshot.get("platform")) == member) and stack_member(name, snapshot.get("platform")) == member)
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen") report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
_sync_switch_stack(nb, device, members, dry_run, report)
records = {} records = {}
for interface in snapshot["interfaces"]: for interface in snapshot["interfaces"]:
@@ -1621,7 +1776,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
record, method = matches[interface["name"]] record, method = matches[interface["name"]]
where = f" auf {owner.name}" if owner.id != device_id else "" where = f" auf {owner.name}" if owner.id != device_id else ""
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored)) port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"]) label = port_label(port["vlans"], interface.get("lag"))
try: try:
if record: if record:
changes = {} changes = {}
@@ -1670,6 +1825,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
report["errors"].append(f"Interface {interface['name']}: {error}") report["errors"].append(f"Interface {interface['name']}: {error}")
_sync_lag_members(snapshot, owners, records, dry_run, report)
for interface in snapshot["interfaces"]: for interface in snapshot["interfaces"]:
key = interface_key(interface["name"]) key = interface_key(interface["name"])
if key not in records: if key not in records:
@@ -1752,6 +1909,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 remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
report["errors"].append(f"Nachbar {label}: {error}") report["errors"].append(f"Nachbar {label}: {error}")
if backup_config:
_backup_config(nb, device, snapshot, dry_run, report)
return report return report
+5 -2
View File
@@ -432,6 +432,7 @@ class Actions:
if not self.require_netbox_config(): if not self.require_netbox_config():
return return
by_id = {switch["id"]: switch for switch in self.state.switches} by_id = {switch["id"]: switch for switch in self.state.switches}
backup = self.state.settings.get("backup_config")
# VLAN and network decisions are shared by all switches of the profile. # VLAN and network decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {}) vlan_map = self.state.profile.setdefault("vlan_map", {})
network_map = self.state.profile.setdefault("network_map", {}) network_map = self.state.profile.setdefault("network_map", {})
@@ -498,7 +499,8 @@ class Actions:
for index, (switch, snapshot) in enumerate(items): for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"]) ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: berechne Änderungen …") 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)))
return nb, reports return nb, reports
def show_preview(result): def show_preview(result):
@@ -522,7 +524,8 @@ class Actions:
ctx.check_cancelled() ctx.check_cancelled()
ctx.progress(index, len(items), switch["name"]) ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: übertrage nach NetBox …") 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"))
for error in report["errors"]: for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error") ctx.log(f"{switch['name']}: {error}", "error")
reports.append((switch, report)) reports.append((switch, report))
+5 -3
View File
@@ -976,12 +976,14 @@ class SwitchMappingDialog(_Dialog):
chosen = combo.currentData() chosen = combo.currentData()
target = "" if chosen == self.NEW else chosen target = "" if chosen == self.NEW else chosen
mapping = result[switch["id"]]["interface_map"] mapping = result[switch["id"]]["interface_map"]
if target and (switch["id"], target) in used: # Stack members have their own devices, so equal names are only a clash on the same device.
key = (switch["id"], item.get("owner_id"), target)
if target and key in used:
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet " self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
f"({used[(switch['id'], target)]}, {item['name']}).") f"({used[key]}, {item['name']}).")
return return
if target: if target:
used[(switch["id"], target)] = item["name"] used[key] = item["name"]
# Plain name matches stay automatic; everything else is remembered. # Plain name matches stay automatic; everything else is remembered.
if item["method"] == "name" and target == item["netbox_name"]: if item["method"] == "name" and target == item["netbox_name"]:
mapping.pop(item["name"], None) mapping.pop(item["name"], None)
+23 -11
View File
@@ -30,8 +30,10 @@ from netbox_sync.ui.widgets import (
label, label,
) )
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox"} STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox",
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint"} "ignored": "ignoriert"}
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint",
"ignored": "text_faint"}
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap") ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
@@ -49,7 +51,8 @@ class SiteMappingDialog(_Dialog):
def __init__(self, parent, rows, sites, tenants): def __init__(self, parent, rows, sites, tenants):
super().__init__(parent, "Standorte & Mandanten zuordnen", super().__init__(parent, "Standorte & Mandanten zuordnen",
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox " "Der Standort ist optional – APs 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.", "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) width=860)
self.resize(980, 620) self.resize(980, 620)
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [ site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
@@ -88,7 +91,7 @@ class SiteMappingDialog(_Dialog):
def accept(self): def accept(self):
result = {} result = {}
for key, site, tenant in self.rows: for key, site, tenant in self.rows:
if tenant.valid_data() is None: if tenant.valid_data() is None and site.valid_data():
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.") self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
return return
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()} result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
@@ -301,9 +304,11 @@ class AccessPointsPage(Page):
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get( stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
ap["site_hint"]) ap["site_hint"])
if stored: if stored:
return dict(placement_value(stored), stored=True) value = placement_value(stored)
# neither site nor tenant: the user chose to leave these APs out
return dict(value, stored=True, ignored=not value["site"] and not value["tenant"])
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
return {"site": site, "tenant": None, "stored": False} return {"site": site, "tenant": None, "stored": False, "ignored": False}
def _tenant_for(self, placement): def _tenant_for(self, placement):
return placement.get("tenant") return placement.get("tenant")
@@ -327,6 +332,8 @@ class AccessPointsPage(Page):
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site)) site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name( tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
related_id(device, "tenant")) related_id(device, "tenant"))
elif self.engine and self._placement(ap)["ignored"]:
site_name = ""
elif self.engine: elif self.engine:
placement = self._placement(ap) placement = self._placement(ap)
site_id = placement["site"] or default_site site_id = placement["site"] or default_site
@@ -335,7 +342,7 @@ class AccessPointsPage(Page):
tenant_name = self._tenant_name(self._tenant_for(placement)) tenant_name = self._tenant_name(self._tenant_for(placement))
else: else:
site_name = "" site_name = ""
state = "new" if not device else ("check" if ap["issues"] else "known") 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, rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
netbox_site=site_name, tenant=tenant_name or "", netbox_site=site_name, tenant=tenant_name or "",
netbox_device=device.name if device else "", method=ap.get("method", ""))) netbox_device=device.name if device else "", method=ap.get("method", "")))
@@ -360,6 +367,8 @@ class AccessPointsPage(Page):
if self.engine: if self.engine:
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen", parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
f"{counts['netbox_only']} nur in NetBox"] f"{counts['netbox_only']} nur in NetBox"]
if counts["ignored"]:
parts.append(f"{counts['ignored']} ignoriert")
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id")) missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
if missing_sites: if missing_sites:
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen") parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
@@ -412,14 +421,16 @@ class AccessPointsPage(Page):
def sync(self): def sync(self):
if not self.engine or self.tasks.busy: if not self.engine or self.tasks.busy:
return return
new = self._new_aps() new = [ap for ap in self._new_aps() if not self._placement(ap)["ignored"]]
role_id = self.role.valid_data() role_id = self.role.valid_data()
if new and not role_id: 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ür neue Access Points bitte eine Geräterolle wählen.",
"info") "info")
return return
if any(not self._placement(ap)["stored"] for ap in new) and not self.map_sites(): if any(not self._placement(ap)["stored"] for ap in new):
return if not self.map_sites():
return
new = [ap for ap in new if not self._placement(ap)["ignored"]]
default_site = self.default_site.valid_data() default_site = self.default_site.valid_data()
placements = {} placements = {}
for ap in new: for ap in new:
@@ -432,7 +443,8 @@ class AccessPointsPage(Page):
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info", "Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
"\n".join(homeless)) "\n".join(homeless))
return return
engine, aps, rename = self.engine, list(self.aps), self.rename.isChecked() engine, rename = self.engine, self.rename.isChecked()
aps = [ap for ap in self.aps if ap.get("device") or ap_key(ap) in placements]
def run(dry_run): def run(dry_run):
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site) return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
+11 -4
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget 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.switches import PLATFORMS, ignored_vlans, port_label, without_vlans
from netbox_sync.ui import widgets from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon from netbox_sync.ui.icons import icon
@@ -93,12 +93,17 @@ class SwitchesPage(Page):
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen", self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox " tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.") "eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
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.")
filters.addWidget(self.search, 2) filters.addWidget(self.search, 2)
filters.addWidget(self.switch_filter, 1) filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up) filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors) filters.addWidget(self.only_neighbors)
filters.addStretch(1) filters.addStretch(1)
filters.addWidget(self.cables_option) filters.addWidget(self.cables_option)
filters.addWidget(self.backup_option)
result_card.add(filters) result_card.add(filters)
result_columns = [ result_columns = [
Column("switch", "Switch", 140), Column("switch", "Switch", 140),
@@ -108,8 +113,8 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")), 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")), Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0), sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans( 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("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("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("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", "")), Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
@@ -144,6 +149,7 @@ class SwitchesPage(Page):
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons) self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value)) 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.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.state.switches_changed.connect(self.refresh) self.state.switches_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh) self.state.profile_switched.connect(self.refresh)
self.state.profile_edited.connect(self.refresh_switches) self.state.profile_edited.connect(self.refresh_switches)
@@ -155,7 +161,8 @@ class SwitchesPage(Page):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _load_settings(self): 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")):
widget.blockSignals(True) widget.blockSignals(True)
widget.setChecked(bool(self.state.settings.get(key))) widget.setChecked(bool(self.state.settings.get(key)))
widget.blockSignals(False) widget.blockSignals(False)
+154 -1
View File
@@ -1,12 +1,15 @@
from types import SimpleNamespace from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record from fake_netbox import Endpoint, FakeNetBox, Record
from netbox_sync.core.switches import ( from netbox_sync.core.switches import (
build_snapshot, build_snapshot,
mask_config,
match_interfaces, match_interfaces,
parse_lags,
parse_stack, parse_stack,
plan_switch_sync, plan_switch_sync,
port_label,
stack_member, stack_member,
sync_snapshot_to_netbox, 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")] 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(): def test_virtual_chassis_positions_are_suggested():
nb, switch, _snapshot = _numbered_setup() nb, switch, _snapshot = _numbered_setup()
snapshot = _stack_snapshot() snapshot = _stack_snapshot()
@@ -375,3 +404,127 @@ def test_virtual_chassis_positions_are_suggested():
virtual_chassis=SimpleNamespace(id=9), vc_position=2)) virtual_chassis=SimpleNamespace(id=9), vc_position=2))
plan = plan_switch_sync(nb, switch, snapshot) plan = plan_switch_sync(nb, switch, snapshot)
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4] 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 == []