Compare commits

...
22 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 1949f03bae chore: release 4.14.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:47:47 +01:00
MrBlakeandClaude Opus 5.5 dfe985bb9e fix: assign only VLANs of the device's site; show notes prominently
- VLANs of another site stay in the label but are not assigned to ports
  (NetBox rejects them); one note per device and VLAN instead of an error
  per port
- Preview shows a notes badge and expands switches with notes; notes are
  also written to the log after the transfer

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:47:33 +01:00
MrBlakeandClaude Opus 5.5 d853f08445 chore: release 4.14.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:56 +01:00
MrBlakeandClaude Opus 5.5 f4c507de6c feat: optional update of existing cables; cable APs reporting their MAC as port
- Cables to neighbors that report their MAC address as port ID (e.g. access
  points) are created via the MAC or the device's single physical port
- Existing cables are compared with LLDP/CDP; differences are reported, and
  only with the optional "Bestehende Kabel anpassen" the cable is moved

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:55 +01:00
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
MrBlakeandClaude Opus 5.5 2dcd0b0855 chore: release 4.10.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:29 +01:00
MrBlakeandClaude Opus 5.5 159a933964 feat: Sophos AP import without upfront tenant, tenant never preselected
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:28 +01:00
MrBlakeandClaude Opus 5.5 c81d9a7edc chore: release 4.10.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:17:22 +01:00
MrBlakeandClaude Opus 5.5 dc8921aaea fix: read switch stacks through their master, group preview by stack member
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:17:22 +01:00
MrBlakeandClaude Opus 5.5 1942d6ecdf chore: release 4.10.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:18:21 +01:00
MrBlakeandClaude Opus 5.5 b402591cdf fix: adaptive empty state, escaped button ampersand, no tenant preselection for APs
- Empty states hide icon and text when space is short instead of being
  squeezed; title and button always stay readable
- "Standorte & Mandanten" button no longer shows a mnemonic underscore
- The tenant on the access point page is always chosen deliberately

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:18:21 +01:00
MrBlakeandClaude Opus 5.5 ba50527ee5 chore: release 4.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:08:30 +01:00
MrBlakeandClaude Opus 5.5 8d2bbafc8d feat: switch stacks per member device, optional AP sites with mandatory tenant
- Detect stacks (Aruba CX VSF, ArubaOS-Switch stacking/VSF, Comware IRF) from
  the configuration; new "Stack" tab assigns a NetBox device per member
  (suggested from virtual chassis positions, stored per switch); ports go to
  their member's device, LAGs and VLAN interfaces stay on the switch device
- Access points: site is optional with a default site for new APs; tenant is
  mandatory and can be chosen per Sophos site; new tenant column
- Empty states no longer get squeezed in small cards

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 13:08:30 +01:00
12 changed files with 1189 additions and 186 deletions

No files matched your search

+42 -10
View File
@@ -49,7 +49,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Add several NetBox devices in one step — host taken from the primary IP,
platform suggested from model/manufacturer
platform suggested from model/manufacturer; members of a NetBox virtual
chassis are added once, through the chassis master
- Platform "detect automatically" via SSH
- Parallel SSH queries; SSH host keys are stored on first contact and verified
afterwards
@@ -61,6 +62,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- VLAN membership per port (untagged and tagged, read from the running
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
only VLAN-related lines of the configuration are kept in the raw data
- LAG members (Aruba CX `lag N`, ArubaOS-Switch `trunk … trkN`, Comware
`port link-aggregation group N`) get their LAG in the label, e.g.
`10,20 (LAG 1)`, and are assigned to the LAG interface in NetBox (field
*LAG*; only on the same device). Members without own VLAN configuration take
the VLANs of their LAG. NetBox Utilities 0.25.0 or later ignores the LAG note
when it evaluates VLAN labels
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
`1/1/5`): equal name, then equal port number, then natural order
- **Mapping review** before the preview: non-obvious port mappings and every
@@ -82,7 +89,30 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
to the ports (802.1Q mode, untagged/tagged)
- Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- Stacks are detected (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware
IRF): every member is assigned to its own NetBox device (suggested from the
NetBox virtual chassis positions, stored per switch) and gets its own ports;
LAGs and VLAN interfaces stay on the switch's device
- Optional: with the [NetBox Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
plugin (0.24.0 or later) a detected stack is also entered as its switch stack
(the switch's device as stack switch, the other member devices as members);
members entered by hand are kept. Without the plugin this step is skipped
- Optional configuration backup ("Konfiguration als Anhang sichern"): with the
[netbox-attachments](https://github.com/Kani999/netbox-attachments) plugin the
running configuration is attached to the switch's device as a text file.
Passwords, keys and SNMP communities are removed first; a new attachment is
only added when the configuration changed (SHA-256 in the description).
Older plugin versions (parent on the attachment) and newer ones (separate
assignments) are supported; without the plugin the step is skipped with a note
- Cables from LLDP/CDP, also with FQDN system names or via the management IP.
Neighbors that report their MAC address as port ID (e.g. access points) are
matched by MAC, and a device with a single physical port is cabled there
- Existing cables are checked against LLDP/CDP: a different far end is reported
as a note. Only with the optional "Bestehende Kabel anpassen" (confirmed with
a warning, NetBox is the source of truth) the cable is moved to the reported
neighbor; such changes are marked with ⚠ in the preview. Cables to patch
panels (front/rear ports) and far ends that already have another cable are
never changed
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
@@ -91,16 +121,18 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
Windows encoding) and checks it: missing site, duplicate IP, serial number or
MAC address
- Finds existing APs in NetBox globally by serial number and MAC address and by
name within the tenant group; NetBox APs of the tenant group that are missing
in the export are listed as "only in NetBox"
- Sophos sites are mapped to NetBox sites of the tenant group (suggested by
name, stored per profile); APs without a Sophos site get a site per AP
- No tenant to pick up front: existing APs are found in all of NetBox by serial
number, MAC address and name; Sophos APs in NetBox that are missing in the
export are listed as "only in NetBox" for the tenants the export concerns
- 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
NetBox requires a site for every device. The tenant is mandatory and chosen
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,
firmware, interface with MAC and IP address (primary IPv4); existing ones get
missing serial numbers and tenants, optionally the Sophos name. Tenant comes
from the NetBox site, otherwise the selected tenant; devices of other tenants
are never changed. Preview before writing
missing serial numbers and tenants, optionally the Sophos name. Preview before
writing
### Network scanner (read only)
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.9.0"
#define AppVersion "4.14.1"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.9.0"
APP_VERSION = "4.14.1"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+33 -10
View File
@@ -122,15 +122,28 @@ class APSyncEngine(ClientSyncEngine):
self.tenant_id = None
self.tenant_ids = set()
self.ap_sites = []
self.group_tenants = []
self.netbox_aps = []
# ------------------------------------------------------------------
# Context
# ------------------------------------------------------------------
def load_context(self, tenant_id):
"""Sites and existing Sophos devices of the tenant's tenant group."""
def load_context(self, tenant_id=None):
"""Sites and existing Sophos devices of the tenant's tenant group, or of all of NetBox without a tenant."""
self.tenant_id = tenant_id
if tenant_id is None:
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()}
self.tenant_ids = set(tenants)
self.group_tenants = sorted(({"id": key, "name": name} for key, name in tenants.items()),
key=lambda row: row["name"].casefold())
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
"tenant": tenants.get(related_id(site, "tenant"), "")}
for site in self.nb.dcim.sites.all()), key=lambda row: row["name"].casefold())
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id)) if manufacturer else []
return self.ap_sites
tenant = self.nb.tenancy.tenants.get(tenant_id)
if tenant is None:
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
@@ -140,6 +153,8 @@ class APSyncEngine(ClientSyncEngine):
if group_id:
self.tenant_ids |= {item.id for item in self.nb.tenancy.tenants.filter(group_id=group_id)}
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()} if group_id else {tenant_id: tenant.name}
self.group_tenants = sorted(({"id": key, "name": tenants[key]} for key in self.tenant_ids if key in tenants),
key=lambda row: row["name"].casefold())
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
"tenant": tenants.get(related_id(site, "tenant"), "")}
for site in self.nb.dcim.sites.filter(**scope)), key=lambda row: row["name"].casefold())
@@ -237,21 +252,27 @@ class APSyncEngine(ClientSyncEngine):
site = next((row for row in self.ap_sites if row["id"] == site_id), None)
return (site or {}).get("tenant_id") or self.tenant_id
def sync(self, aps, sites, role_id, rename=True, dry_run=True):
"""``sites`` maps ``ap_key`` to the NetBox site ID for new devices."""
def sync(self, aps, placements, role_id, rename=True, dry_run=True, default_site=None):
"""``placements`` maps ``ap_key`` to ``{"site": ID or None, "tenant": ID}``.
The site is optional; NetBox needs one for every device, so new APs
without a site go to ``default_site``. The tenant is mandatory.
"""
report = self.new_report()
self._planned = set()
for ap in aps:
try:
changes = self._sync_ap(ap, sites.get(ap_key(ap)), role_id, rename, dry_run, report)
changes = self._sync_ap(ap, placements.get(ap_key(ap)) or {}, role_id, rename, dry_run, report,
default_site)
except Exception as error: # noqa: BLE001 - one AP must not stop the others
report["errors"].append(f"{ap['name']}: {error}")
changes = [f"Fehler: {error}"]
report["items"].append((ap["name"], changes))
return report
def _sync_ap(self, ap, site_id, role_id, rename, dry_run, report):
def _sync_ap(self, ap, placement, role_id, rename, dry_run, report, default_site=None):
device = ap.get("device")
site_id = placement.get("site") or default_site
changes = []
description = f"Firmware {ap['firmware']}" if ap["firmware"] else ""
if device is not None:
@@ -265,7 +286,7 @@ class APSyncEngine(ClientSyncEngine):
if ap["serial"] and not getattr(device, "serial", ""):
updates["serial"] = ap["serial"]
if tenant is None:
updates["tenant"] = self._site_tenant(related_id(device, "site"))
updates["tenant"] = placement.get("tenant") or self._site_tenant(related_id(device, "site"))
if description and (getattr(device, "description", "") or "").startswith("Firmware") \
and device.description != description:
updates["description"] = description
@@ -279,16 +300,18 @@ class APSyncEngine(ClientSyncEngine):
else:
report["devices_unchanged"] += 1
changes.append(f"Vorhanden – gefunden über {ap['method']}")
tenant_id = tenant or self._site_tenant(related_id(device, "site"))
tenant_id = tenant or updates.get("tenant")
else:
if not site_id:
raise APImportError("kein NetBox-Standort zugeordnet")
raise APImportError("kein Standort – NetBox verlangt für Geräte einen Standort, bitte einen "
"Standard-Standort wählen")
if not role_id:
raise APImportError("keine Geräterolle gewählt")
manufacturer_id = self._manufacturer(MANUFACTURER, report, dry_run)
type_id = self._device_type(MANUFACTURER, manufacturer_id, ap["model"] or "Access Point", report, dry_run)
platform_id = self._platform(PLATFORM, report, dry_run)
tenant_id = self._site_tenant(site_id)
# An explicitly chosen tenant wins, otherwise the one of the site.
tenant_id = placement.get("tenant") or self._site_tenant(site_id)
payload = {"name": ap["name"], "device_type": type_id, "role": role_id, "site": site_id,
"tenant": tenant_id, "status": "active", "platform": platform_id}
if ap["serial"]:
+401 -29
View File
@@ -1,5 +1,7 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import hashlib
import io
import ipaddress
import re
import threading
@@ -8,7 +10,7 @@ from pathlib import Path
import paramiko
from netbox_sync.core.netbox import assign_mac, related_id
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
PLATFORMS = {
"auto": "Automatisch erkennen",
@@ -608,8 +610,8 @@ def _parse_neighbor_table(output):
# VLAN membership from the running configuration
# --------------------------------------------------------------------------
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$")
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode")
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*[A-Za-z]?)(\d+)-(?:\1)?(\d+)$")
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode|^\s*lag \d|^trunk\s|link-aggregation")
def parse_vlan_list(text):
@@ -776,16 +778,101 @@ def vlan_label(vlans, limit=64):
return text
def port_label(vlans, lag=None, limit=64):
"""NetBox label of a port: its VLANs plus its LAG, e.g. ``10,20 (LAG 1)``."""
number = re.search(r"(\d+)$", lag or "")
suffix = f"(LAG {number.group(1)})" if number else ""
text = vlan_label(vlans, limit - len(suffix) - 1 if suffix else limit)
return f"{text} {suffix}".strip()
def parse_lags(config, platform):
"""LAG of every member port as ``{interface_key(port): LAG name}``."""
lags = {}
if platform == "aruba_aos":
# "trunk 49-50 trk1 lacp" is a global line.
for match in re.finditer(r"(?im)^trunk\s+(\S+)\s+trk(\d+)\b", clean_output(config or "")):
for port in _expand_ports(match.group(1)):
lags[interface_key(port)] = f"Trk{match.group(2)}"
return lags
member = {"aruba_cx": (re.compile(r"(?i)^lag (\d+)$"), "lag{}"),
"hpe_comware": (re.compile(r"(?i)^port link-aggregation group (\d+)$"), "Bridge-Aggregation{}")}
if platform not in member:
return lags
pattern, name = member[platform]
for match, body in _config_blocks(config or "", re.compile(r"^interface\s+(\S+)\s*$", re.I)):
group = next((found.group(1) for found in map(pattern.match, body) if found), None)
if group:
lags[interface_key(match.group(1))] = name.format(group)
return lags
# Values after these words are removed from configuration backups.
_SECRET = re.compile(r"(?i)\b(password|secret|key|community|ciphertext|plaintext|psk|passphrase)\b(\s+).*$")
def mask_config(config):
"""Running configuration without passwords, keys and SNMP communities."""
return "\n".join(_SECRET.sub(r"\1\2<entfernt>", line) for line in clean_output(config).splitlines()).strip()
def _vlan_config_excerpt(config):
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
# --------------------------------------------------------------------------
# Stacks (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware IRF)
# --------------------------------------------------------------------------
_STACK_PORT = {
"aruba_cx": re.compile(r"^(\d+)/\d+/\d+$"),
"aruba_aos": re.compile(r"^(\d+)/[A-Z]?\d+$"),
"hpe_comware": re.compile(r"^[A-Za-z][A-Za-z\-]*(\d+)/\d+/\d+$"),
}
def stack_member(name, platform):
"""Stack member of a port name (``2/1/5`` → 2) or ``None`` for LAGs, VLANs …"""
pattern = _STACK_PORT.get(platform)
match = pattern.match(name or "") if pattern else None
return int(match.group(1)) if match else None
def parse_stack(config, platform, interfaces=()):
"""Stack members as ``[{"member", "model", "mac"}]``; empty for a single switch."""
members = {}
text = clean_output(config or "")
if platform == "aruba_cx" or platform == "aruba_aos":
for match, body in _config_blocks(text, re.compile(r"^vsf member (\d+)\s*$", re.I)):
model = next((re.match(r"(?i)type\s+(\S+)", line).group(1) for line in body
if re.match(r"(?i)type\s+\S+", line)), "")
members[int(match.group(1))] = {"model": model.strip('"'), "mac": ""}
# ArubaOS-Switch: "member 2 type "JL256A" mac-address 9020c2-123456" below "stacking"/"vsf".
for match in re.finditer(r'(?im)^\s+member (\d+) type "?([^"\s]+)"?(?:\s+mac-address (\S+))?', text):
members.setdefault(int(match.group(1)), {"model": match.group(2), "mac": match.group(3) or ""})
elif platform == "hpe_comware":
for match in re.finditer(r"(?im)^\s*irf member (\d+)\b", text):
members.setdefault(int(match.group(1)), {"model": "", "mac": ""})
for interface in interfaces:
member = stack_member(interface["name"], platform) if not interface.get("virtual") else None
if member is not None:
members.setdefault(member, {"model": "", "mac": ""})
if len(members) < 2:
return []
return [dict(members[member], member=member) for member in sorted(members)]
def build_snapshot(outputs, platform):
interfaces = parse_interfaces(outputs["interfaces"], platform)
vlans = parse_vlans(outputs.get("config", ""), platform)
lags = parse_lags(outputs.get("config", ""), platform)
for interface in interfaces:
interface["vlans"] = vlans.get(interface_key(interface["name"]))
interface["lag"] = lags.get(interface_key(interface["name"]))
if interface["lag"] and not interface["vlans"]:
# Aruba CX/Comware: the VLANs are configured on the LAG and apply to its member ports.
interface["vlans"] = vlans.get(interface_key(interface["lag"]))
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
lldp_neighbors = parse_neighbors(outputs["neighbors"])
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
@@ -821,7 +908,9 @@ def build_snapshot(outputs, platform):
"raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")),
"config_backup": mask_config(outputs["config"]) if outputs.get("config") else "",
"vlan_names": parse_vlan_names(outputs.get("config", "")),
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
"lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(),
@@ -1181,6 +1270,61 @@ def _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id):
return vlans, match_vlans(snapshot_vlan_ids(snapshot), names, vlans, tenant_id, site_id, config.get("vlan_map"))
def stack_devices(nb, config, snapshot, device):
"""``{member: NetBox device or None}`` for a stack, ``{}`` for a single switch.
Order: the choice stored in the profile (0 = skip the member), the member's
position in the NetBox virtual chassis of the switch, else the first member
is the switch's own device.
"""
stack = snapshot.get("stack") or []
if not stack:
return {}
chosen = config.get("stack_devices") or {}
by_position = {}
chassis = related_id(device, "virtual_chassis")
if chassis:
for member_device in nb.dcim.devices.filter(virtual_chassis_id=chassis):
position = getattr(member_device, "vc_position", None)
if position is not None:
by_position[int(position)] = member_device
first = stack[0]["member"]
result = {}
for entry in stack:
member = entry["member"]
if str(member) in chosen:
device_id = int(chosen[str(member)] or 0)
result[member] = None if not device_id else (device if device_id == device.id
else nb.dcim.devices.get(device_id))
else:
result[member] = by_position.get(member) or (device if member == first else None)
return result
def _interface_owners(snapshot, members, device):
"""NetBox device per discovered interface; ``None`` = member without device."""
platform = snapshot.get("platform")
owners = {}
for interface in snapshot["interfaces"]:
member = None if interface.get("virtual") or not members else stack_member(interface["name"], platform)
# LAGs, VLAN interfaces and loopbacks belong to the stack as a whole.
owners[interface["name"]] = members[member] if member in members else device
return owners
def _match_by_owner(nb, snapshot, owners, manual):
groups = {}
for interface in snapshot["interfaces"]:
owner = owners[interface["name"]]
if owner is not None:
groups.setdefault(owner.id, (owner, []))[1].append(interface)
matches, records = {}, {}
for owner_id, (_owner, interfaces) in groups.items():
records[owner_id] = list(nb.dcim.interfaces.filter(device_id=owner_id))
matches.update(match_interfaces(interfaces, records[owner_id], manual))
return matches, records
def plan_switch_sync(nb, config, snapshot):
"""Proposals for the review dialog: interface mapping, neighbor devices,
networks (VRF and missing prefixes) and missing VLANs."""
@@ -1189,8 +1333,10 @@ def plan_switch_sync(nb, config, snapshot):
tenant_id, error = _require_tenant(device)
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"))
members = stack_devices(nb, config, snapshot, device)
owners = _interface_owners(snapshot, members, device)
matches, owner_records = _match_by_owner(nb, snapshot, owners, config.get("interface_map"))
records = owner_records.get(device.id) or list(nb.dcim.interfaces.filter(device_id=device.id))
scope, devices = candidate_devices(nb, device)
known = {row["id"] for row in devices}
lookup = _RemoteLookup(nb)
@@ -1208,6 +1354,11 @@ def plan_switch_sync(nb, config, snapshot):
devices.append({"id": remote.id, "name": remote.name})
known.add(remote.id)
neighbors.append(dict(neighbor, device_id=device_id, method=method))
# Stack members may be chosen from the same list (including the switch itself).
for member_device in ([device, *filter(None, members.values())] if members else []):
if member_device.id not in known:
devices.append({"id": member_device.id, "name": member_device.name})
known.add(member_device.id)
devices.sort(key=lambda row: row["name"].casefold())
vrf_records = candidate_vrfs(nb, tenant_id)
@@ -1251,12 +1402,20 @@ def plan_switch_sync(nb, config, snapshot):
"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(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
for item in snapshot["interfaces"]
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id,
"vlan_label": port_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)), item.get("lag"))}
for item in snapshot["interfaces"] if owners[item["name"]] is not None
for record, method in [matches[item["name"]]]
],
"netbox_interfaces": sorted((record.name for record in records), key=_natural_key),
# NetBox interface names per device, for stacks with one device per member.
"owner_interfaces": {str(owner_id): sorted((record.name for record in owner_records[owner_id]),
key=_natural_key) for owner_id in owner_records},
"stack": [dict(entry, device_id=members[entry["member"]].id if members.get(entry["member"]) else None,
ports=sum(1 for item in snapshot["interfaces"]
if stack_member(item["name"], snapshot.get("platform")) == entry["member"]))
for entry in snapshot.get("stack") or []],
"skipped_ports": sum(1 for owner in owners.values() if owner is None),
"neighbors": neighbors,
"device_scope": scope,
"devices": devices,
@@ -1315,7 +1474,17 @@ class _RemoteLookup:
if _physical_record(record) and _port_number(record.name) == number]
if len(found) == 1:
return found[0]
return None
# Access points and phones often report their MAC address as port ID.
mac = normalize_mac(neighbor.get("remote_port"))
if mac:
found = [record for record in records.values()
if normalize_mac(getattr(record, "mac_address", None)) == mac]
if len(found) == 1:
return found[0]
# An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there.
physical = [record for record in records.values()
if _physical_record(record) and not getattr(record, "mgmt_only", False)]
return physical[0] if len(physical) == 1 else None
_NEW = "new" # placeholder ID of objects a dry run would create
@@ -1402,8 +1571,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
report["errors"].append(f"Prefix {network}: {error}")
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report, sites=None):
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved.
``sites`` receives ``{VLAN ID: (site ID or None, name)}`` for the site check of the ports.
"""
sites = {} if sites is None else sites
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"}
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
@@ -1411,6 +1584,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
for vid, (record, method, name) in matches.items():
if record is not None:
present[vid] = record.id
sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid))
continue
if method != "new" or vid not in approved:
continue
@@ -1423,6 +1597,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
if site_id:
payload["site"] = site_id
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
sites[vid] = (site_id, name)
except Exception as error: # noqa: BLE001
report["errors"].append(f"VLAN {vid}: {error}")
return present
@@ -1464,13 +1639,186 @@ def _new_report():
return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0,
"cables_created": 0, "cables_updated": 0, "cables_skipped": 0,
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
"changes": [], "errors": [],
"changes": [], "errors": [], "notes": [],
}
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
def _sync_switch_stack(nb, device, members, dry_run, report):
"""Fill in the switch stack of the optional NetBox Utilities plugin.
The switch's device is the stack switch, the other member devices are
added to it; members entered by hand stay. Without the plugin nothing happens.
"""
others = {member.id: member for member in members.values() if member is not None and member.id != device.id}
if not others:
return
try:
endpoint = nb.plugins.utilities.switch_stacks
stacks = list(endpoint.filter(device_id=device.id))
except AttributeError:
return
except Exception as error: # noqa: BLE001
if getattr(getattr(error, "req", None), "status_code", None) != 404:
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
return
stack = stacks[0] if stacks else None
current = [getattr(item, "id", item) for item in (getattr(stack, "members", None) or [])]
missing = [member_id for member_id in others if member_id not in current]
if not missing:
return
names = ", ".join(others[member_id].name for member_id in missing)
report["changes"].append(f"Switch-Stack {device.name}: Mitglieder {names} eintragen (NetBox Utilities)"
if stack else f"Switch-Stack {device.name} neu mit Mitgliedern {names} (NetBox Utilities)")
if dry_run:
return
try:
if stack:
stack.update({"members": current + missing})
else:
endpoint.create({"device": device.id, "members": missing})
except Exception as error: # noqa: BLE001
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
def _vlans_for_site(vlan_ids, vlan_sites, site_id, owner, reported, report):
"""VLANs a port of ``owner`` may use: NetBox only allows global VLANs or VLANs of the device's site.
Other VLANs stay in the label; each is reported once per device.
"""
allowed = {}
for vid, netbox_id in vlan_ids.items():
vlan_site, name = vlan_sites.get(vid, (None, str(vid)))
if vlan_site in (None, site_id):
allowed[vid] = netbox_id
elif (owner.id, vid) not in reported:
reported.add((owner.id, vid))
report["notes"].append(f"VLAN {vid} „{name}“ gehört zu einem anderen Standort als {owner.name} – "
f"nur im Label vermerkt, nicht am Port zugewiesen (VLAN global machen, "
f"um es zuzuweisen)")
return allowed
def _sync_lag_members(snapshot, owners, records, dry_run, report):
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
for interface in snapshot["interfaces"]:
key, lag_key = interface_key(interface["name"]), interface_key(interface.get("lag") or "")
if not interface.get("lag") or key not in records or lag_key not in records:
continue
record, lag_record = records[key], records[lag_key]
owner, lag_owner = owners[interface["name"]], owners[names[lag_key]]
if owner.id != lag_owner.id:
# NetBox only allows a LAG of the same device (or virtual chassis).
report["notes"].append(f"Interface {interface['name']}: LAG {names[lag_key]} liegt auf {lag_owner.name} "
f"– nur im Label vermerkt")
continue
if record and lag_record and related_id(record, "lag") == lag_record.id:
continue
report["changes"].append(f"Interface {record.name if record else interface['name']}: LAG {names[lag_key]}")
if not dry_run and record and lag_record:
try:
record.update({"lag": lag_record.id})
except Exception as error: # noqa: BLE001
report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}")
def _backup_config(nb, device, snapshot, dry_run, report):
"""Attach the running configuration to the device (optional netbox-attachments plugin).
A new attachment is only added when the configuration of this device changed
since the last backup; the hash in the description identifies it.
"""
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 _term(value, key):
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
def _termination_text(termination):
item = _term(termination, "object") or {}
owner = _term(_term(item, "device") or {}, "name")
return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id"))
def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
"""Compare an existing cable of a switch port with its LLDP/CDP neighbor.
NetBox is the source of truth: a different far end is only reported unless
``update_cables`` is set. Cables to patch panels (front/rear ports) or with
several terminations are never touched.
"""
cable = nb.dcim.cables.get(related_id(local, "cable"))
if cable is None:
report["cables_skipped"] += 1
return
sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])]
local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None)
far = sides[1] if local_side is sides[0] else sides[0]
if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface":
report["cables_skipped"] += 1
return
if _term(far[0], "object_id") == remote.id:
report["cables_skipped"] += 1
return
old = _termination_text(far[0])
remote_cable = related_id(remote, "cable")
if not update_cables or (remote_cable and remote_cable != cable.id):
reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables
else "„Bestehende Kabel anpassen“ ist aus")
report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})")
return
report["cables_updated"] += 1
report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}")
if not dry_run:
cable.update({
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
})
remote.cable = cable
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
backup_config=False, update_cables=False):
"""Write a discovery snapshot to NetBox.
With ``dry_run`` nothing is written; the returned report lists what would
@@ -1487,17 +1835,31 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
device_id = device.id
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
vlan_sites = {}
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report, vlan_sites)
ignored = ignored_vlans(config.get("vlan_map"))
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map"))
records = {}
members = stack_devices(nb, config, snapshot, device)
owners = _interface_owners(snapshot, members, device)
matches, _owner_records = _match_by_owner(nb, snapshot, owners, config.get("interface_map"))
own_devices = {device_id} | {member.id for member in members.values() if member is not None}
for member, member_device in members.items():
if member_device is None:
skipped = sum(1 for name, owner in owners.items() if owner is None
and stack_member(name, snapshot.get("platform")) == member)
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
_sync_switch_stack(nb, device, members, dry_run, report)
records, foreign = {}, set()
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
owner = owners[interface["name"]]
if owner is None:
continue
record, method = matches[interface["name"]]
where = f" auf {owner.name}" if owner.id != device_id else ""
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"])
label = port_label(port["vlans"], interface.get("lag"))
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
try:
if record:
changes = {}
@@ -1507,7 +1869,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
# routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label
changes.update(_vlan_assignment(port, vlan_ids, record))
changes.update(_vlan_assignment(port, owner_vlans, record))
if changes:
report["interfaces_updated"] += 1
texts = []
@@ -1518,25 +1880,25 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if "mode" in changes:
texts.append(f"VLAN-Modus {changes['mode']}")
target = record.name if method == "name" else f"{record.name} ({interface['name']})"
report["changes"].append(f"Interface {target}: {', '.join(texts)}")
report["changes"].append(f"Interface {target}{where}: {', '.join(texts)}")
if not dry_run:
record.update(changes)
else:
report["interfaces_unchanged"] += 1
else:
payload = {
"device": device_id,
"device": owner.id,
"name": interface["name"],
"type": netbox_interface_type(interface),
"enabled": bool(interface.get("enabled", True)),
}
if label:
payload["label"] = label
payload.update(_vlan_assignment(port, vlan_ids))
payload.update(_vlan_assignment(port, owner_vlans))
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
report["changes"].append(f"Interface {interface['name']} neu ({payload['type']})"
report["changes"].append(f"Interface {interface['name']}{where} neu ({payload['type']})"
+ (f", Label „{label}“" if label else ""))
if not dry_run:
record = nb.dcim.interfaces.create(payload)
@@ -1546,6 +1908,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
except Exception as error: # noqa: BLE001
report["errors"].append(f"Interface {interface['name']}: {error}")
_sync_lag_members(snapshot, owners, records, dry_run, report)
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
if key not in records:
@@ -1598,9 +1962,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if key not in records:
continue
local = records[key]
if local is not None and getattr(local, "cable", None):
report["cables_skipped"] += 1
continue
existing = getattr(local, "cable", None) if local is not None else None
if neighbor["local_port"] in manual_devices:
# 0 means "no device" was chosen in the review dialog.
chosen = int(manual_devices[neighbor["local_port"]] or 0)
@@ -1610,9 +1972,15 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if not remote_device:
report["cables_skipped"] += 1
continue
if remote_device.id == device_id:
if remote_device.id in own_devices:
continue
remote = lookup.interface(remote_device, neighbor)
if existing:
if remote:
_check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report)
else:
report["cables_skipped"] += 1
continue
if not remote or getattr(remote, "cable", None):
report["cables_skipped"] += 1
continue
@@ -1628,12 +1996,16 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001
report["errors"].append(f"Nachbar {label}: {error}")
if backup_config:
_backup_config(nb, device, snapshot, dry_run, report)
return report
def describe_snapshot(snapshot):
stack = snapshot.get("stack") or []
return (
f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
(f"Stack mit {len(stack)} Mitgliedern, " if stack else "")
+ f"{len(snapshot['interfaces'])} Schnittstellen, {len(snapshot.get('ip_addresses', []))} IP-Adressen, "
f"{len(snapshot.get('lldp_neighbors', []))} LLDP- und {len(snapshot.get('cdp_neighbors', []))} CDP-Nachbarn"
)
+43 -8
View File
@@ -12,7 +12,7 @@ from netbox_sync.core import exchange, netbox
from netbox_sync.core.client_sync import ClientSyncEngine
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.netbox import NetBoxError, related_name
from netbox_sync.core.netbox import NetBoxError, related_id, related_name
from netbox_sync.core.switches import (
PLATFORMS,
describe_snapshot,
@@ -42,8 +42,13 @@ def _device_row(device):
tenant = related_name(device, "tenant")
role = related_name(device, "role") or related_name(device, "device_role")
name = str(device.name)
chassis = getattr(device, "virtual_chassis", None)
return {
"id": device.id,
"chassis": related_id(device, "virtual_chassis"),
"chassis_master": related_id(chassis, "master") if chassis is not None else None,
"vc_position": getattr(device, "vc_position", None),
"stack_of": "",
"name": name,
"site": site,
"tenant": tenant,
@@ -56,6 +61,23 @@ def _device_row(device):
}
def _merge_stacks(rows):
"""Stack members are read through one SSH session: point them at the chassis master and its address."""
chassis = {}
for row in rows:
if row["chassis"]:
chassis.setdefault(row["chassis"], []).append(row)
for members in chassis.values():
master = next((row for row in members if row["id"] == row["chassis_master"]), None)
master = master or min(members, key=lambda row: (not row["host"], row["vc_position"] or 0, row["name"]))
host = master["host"] or next((row["host"] for row in members if row["host"]), "")
master["host"] = host
for row in members:
if row is not master:
row.update(host=host, stack_of=master["name"], stack_master=master["id"])
return rows
class Actions:
def __init__(self, window):
self.window = window
@@ -319,7 +341,7 @@ class Actions:
nb = connect(ctx)
ctx.log("Lade NetBox-Geräte …")
devices = list(nb.dcim.devices.all())
rows = [_device_row(device) for device in devices if getattr(device, "name", None)]
rows = _merge_stacks([_device_row(device) for device in devices if getattr(device, "name", None)])
skipped = len(devices) - len(rows)
ctx.log(f"{len(rows)} Geräte geladen" + (f" ({skipped} ohne Namen übersprungen)" if skipped else ""),
"success")
@@ -367,8 +389,13 @@ class Actions:
ctx.log(f"{switch['name']}: keine Schnittstellen erkannt – bitte SSH-Rohdaten prüfen",
"warning")
except Exception as error: # noqa: BLE001
failures[switch["id"]] = str(error)
ctx.log(f"{switch['name']}: {error}", "error")
problem = str(error)
if "getaddrinfo" in problem:
problem = (f"Host „{switch['host']}“ ist nicht auflösbar (keine Primär-IP in NetBox?). "
"Stack-Mitglieder werden über den Stack-Master ausgelesen und können aus "
"dem Profil entfernt werden.")
failures[switch["id"]] = problem
ctx.log(f"{switch['name']}: {problem}", "error")
ctx.progress(done, len(switches), switch["name"])
if ctx.cancelled:
for pending in futures:
@@ -405,6 +432,8 @@ class Actions:
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
backup = self.state.settings.get("backup_config")
update_cables = create_cables and bool(self.state.settings.get("update_cables"))
# VLAN and network decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {})
network_map = self.state.profile.setdefault("network_map", {})
@@ -433,6 +462,7 @@ class Actions:
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"])
or any(not member["device_id"] for member in item.get("stack", []))
or any(not network["stored"] and not network["existing"] for network in item["networks"])
or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
for _switch, item in reviewable)
@@ -470,7 +500,8 @@ class Actions:
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: berechne Änderungen …")
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True,
backup_config=backup, update_cables=update_cables)))
return nb, reports
def show_preview(result):
@@ -481,22 +512,26 @@ class Actions:
# follow-up task is not rejected as "still busy".
dialog = SyncPreviewDialog(self.window, reports, create_cables)
if dialog.exec():
self._apply_switch_sync(nb, items, create_cables, log)
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
QTimer.singleShot(0, ask)
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
on_error=self._netbox_failed)
def _apply_switch_sync(self, nb, items, create_cables, log):
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
def work(ctx):
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.check_cancelled()
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False,
backup_config=self.state.settings.get("backup_config"),
update_cables=update_cables)
for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error")
for note in report.get("notes", []):
ctx.log(f"{switch['name']}: {note}", "warning")
reports.append((switch, report))
return reports
+93 -10
View File
@@ -1,5 +1,6 @@
"""Modal dialogs for editing connections and reviewing changes."""
import re
import uuid
from PySide6.QtCore import QThreadPool, Qt
@@ -368,7 +369,9 @@ class AddSwitchesDialog(_Dialog):
width=980)
self.resize(1080, 720)
self.result = []
self.rows = [dict(device, added=device["id"] in existing_device_ids) for device in devices]
self.rows = [dict(device, added=device.get("stack_master", device["id"]) in existing_device_ids)
for device in devices]
self.by_id = {row["id"]: row for row in self.rows}
filters = QHBoxLayout()
filters.setSpacing(8)
@@ -402,8 +405,8 @@ class AddSwitchesDialog(_Dialog):
Column("host", "SSH-Host", 130),
Column("platform", "Plattform", 160, value=lambda row: PLATFORMS[row["platform"]],
color=lambda row: "text_faint" if row["platform"] == "auto" else None),
Column("added", "", 110, value=lambda row: "bereits im Profil" if row["added"] else "",
color=lambda row: "text_faint"),
Column("added", "", 170, value=lambda row: "bereits im Profil" if row["added"] else (
f"Stack von {row['stack_of']}" if row.get("stack_of") else ""), color=lambda row: "text_faint"),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.model.set_rows(self.rows)
@@ -491,6 +494,16 @@ class AddSwitchesDialog(_Dialog):
self.show_error("Bitte Benutzer und Passwort für den SSH-Zugang angeben.")
return
platform = self.platform.currentData()
# a stack is read once through its master; every member is mapped in the review
masters = {}
for row in chosen:
master = self.by_id.get(row.get("stack_master"), row)
if not master["added"]:
masters.setdefault(master["id"], master)
chosen = list(masters.values())
if not chosen:
self.show_error("Die ausgewählten Stack-Mitglieder sind über ihren Stack bereits im Profil.")
return
self.result = [{
"id": uuid.uuid4().hex,
"name": row["name"],
@@ -533,9 +546,14 @@ class SyncPreviewDialog(_Dialog):
items.append((f"{totals[key]} {text}", "info"))
if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
if totals.get("cables_updated"):
items.append((f"{totals['cables_updated']} Kabel angepasst", "error"))
errors = sum(len(report["errors"]) for _switch, report in reports)
if errors:
items.append((f"{errors} Probleme", "error"))
notes = sum(len(report.get("notes", [])) for _switch, report in reports)
if notes:
items.append((f"{notes} Hinweis(e)", "warning"))
for text, kind in items:
summary.addWidget(Badge(text, kind))
summary.addStretch(1)
@@ -551,7 +569,9 @@ class SyncPreviewDialog(_Dialog):
changes = report["changes"]
total_changes += len(changes)
unchanged = report["interfaces_unchanged"]
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
hints = len(report.get("notes", []))
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"
+ (f", {hints} Hinweis(e)" if hints else "")])
top.setIcon(0, icon("network", theme.color("accent")))
font = top.font(0)
font.setBold(True)
@@ -560,10 +580,27 @@ class SyncPreviewDialog(_Dialog):
child = QTreeWidgetItem([error])
child.setIcon(0, icon("warning", theme.color("danger")))
top.addChild(child)
for note in report.get("notes", []):
child = QTreeWidgetItem([note])
child.setIcon(0, icon("info", theme.color("warning")))
top.addChild(child)
members = {}
for change in changes[:2000]:
top.addChild(QTreeWidgetItem([change]))
# stack member ports read "Interface X (Y) auf <member>: …" – group them under the member
found = re.match(r"(Interface .+?) auf ([^:]+): (.*)$", change)
if not found:
top.addChild(QTreeWidgetItem([change]))
continue
if found.group(2) not in members:
members[found.group(2)] = QTreeWidgetItem([found.group(2)])
members[found.group(2)].setIcon(0, icon("network", theme.color("text_muted")))
members[found.group(2)].addChild(QTreeWidgetItem([f"{found.group(1)}: {found.group(3)}"]))
for member in members.values():
member.setText(0, f"{member.text(0)} — {member.childCount()} Änderung(en)")
top.addChild(member)
member.setExpanded(True)
tree.addTopLevelItem(top)
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
top.setExpanded(len(reports) == 1 or bool(report["errors"]) or bool(hints))
self.root.addWidget(tree, 1)
if total_changes == 0:
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
@@ -598,6 +635,37 @@ class SwitchMappingDialog(_Dialog):
self._new_vrf_names = []
tabs = QTabWidget()
# Stack ---------------------------------------------------------------
self.stack_rows = []
stacks = [(switch, plan) for switch, plan in plans if plan.get("stack")]
if stacks:
stack_page = QWidget()
stack_layout = QVBoxLayout(stack_page)
stack_layout.setContentsMargins(0, 12, 0, 0)
stack_layout.addWidget(label(
"Der Switch ist ein Stack. Jedes Mitglied wird einem eigenen NetBox-Gerät zugeordnet, die Ports "
"kommen an das Gerät ihres Mitglieds (2/1/5 an das Gerät von Mitglied 2). LAGs und VLAN-Interfaces "
"bleiben am Gerät des Switch-Eintrags. Vorschlag: Positionen im Virtual Chassis von NetBox.",
muted=True, wrap=True))
self.stack_table = QTableWidget(0, 5)
self.stack_table.setHorizontalHeaderLabels(["Switch", "Mitglied", "Modell", "Ports", "NetBox-Gerät"])
for switch, plan in stacks:
items = [("– Ports überspringen –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]]
for entry in plan["stack"]:
row = self.stack_table.rowCount()
self.stack_table.insertRow(row)
texts = (switch["name"], str(entry["member"]), entry["model"], str(entry["ports"]))
for column, text in enumerate(texts):
self.stack_table.setItem(row, column, QTableWidgetItem(text))
combo = SearchableComboBox("Gerät suchen …")
combo.set_items(items, entry["device_id"] or 0)
self.stack_table.setCellWidget(row, 4, combo)
self.stack_rows.append((switch, entry, combo))
self._prepare_table(self.stack_table, (160, 80, 120, 70, 320))
stack_layout.addWidget(self.stack_table, 1)
open_members = sum(1 for _switch, entry, _combo in self.stack_rows if not entry["device_id"])
tabs.addTab(stack_page, f"Stack ({open_members} ohne Gerät)" if open_members else "Stack")
# Interfaces --------------------------------------------------------
interface_page = QWidget()
interface_layout = QVBoxLayout(interface_page)
@@ -610,10 +678,12 @@ class SwitchMappingDialog(_Dialog):
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
# In a stack every member has its own NetBox device and interfaces.
names = plan.get("owner_interfaces", {}).get(str(item.get("owner_id")), plan["netbox_interfaces"])
choices = [("+ neu anlegen", self.NEW)] + [(name, name) for name in names]
row = self.interface_table.rowCount()
self.interface_table.insertRow(row)
combo = QComboBox()
@@ -897,17 +967,30 @@ class SwitchMappingDialog(_Dialog):
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}
# Members moved to another device: their port choices refer to the old
# device and are dropped, so the ports are matched again automatically.
moved = set()
for switch, entry, combo in self.stack_rows:
chosen = int(combo.valid_data() or 0)
result[switch["id"]].setdefault("stack_devices", {})[str(entry["member"])] = chosen
if chosen != (entry["device_id"] or 0) and entry["device_id"]:
moved.add((switch["id"], entry["device_id"]))
used = {}
for _row, switch, item, combo in self.interface_rows:
if (switch["id"], item.get("owner_id")) in moved:
result[switch["id"]]["interface_map"].pop(item["name"], None)
continue
chosen = combo.currentData()
target = "" if chosen == self.NEW else chosen
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 "
f"({used[(switch['id'], target)]}, {item['name']}).")
f"({used[key]}, {item['name']}).")
return
if target:
used[(switch["id"], target)] = item["name"]
used[key] = 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)
+158 -109
View File
@@ -30,73 +30,86 @@ from netbox_sync.ui.widgets import (
label,
)
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"}
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox",
"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")
class SiteMappingDialog(_Dialog):
"""Assign NetBox sites to Sophos sites and to APs without a Sophos site."""
def placement_value(value):
"""Stored choice as ``{"site": ID or None, "tenant": ID or None}`` (4.9.0 stored only a site ID)."""
if isinstance(value, dict):
return {"site": value.get("site") or None, "tenant": value.get("tenant") or None}
return {"site": value or None, "tenant": None}
def __init__(self, parent, hints, homeless, sites, site_map, ap_sites):
super().__init__(parent, "Standorte zuordnen",
"Neue Access Points werden am zugeordneten NetBox-Standort angelegt und erhalten dessen "
"Mandanten. Zur Auswahl stehen die Standorte der Mandantengruppe.", width=760)
self.resize(860, 620)
items = [("– nicht zugeordnet –", 0)] + [
(f"{site['name']}" + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
self.table = QTableWidget(0, 3)
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort"])
class SiteMappingDialog(_Dialog):
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
and to APs without a Sophos site."""
def __init__(self, parent, rows, sites, tenants):
super().__init__(parent, "Standorte & Mandanten zuordnen",
"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. Zeilen ohne "
"Standort und ohne Mandant werden ignoriert.",
width=860)
self.resize(980, 620)
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
"Mandant *"])
self.rows = []
for hint, count, suggestion in hints:
self._row(hint, str(count), items, site_map.get(hint) or suggestion or 0, ("site", hint))
for ap in homeless:
self._row(f"{ap['name']} (ohne Sophos-Standort)", "1", items, ap_sites.get(ap_key(ap)) or 0,
("ap", ap_key(ap)))
for text, count, key, current in rows:
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(text))
self.table.setItem(row, 1, QTableWidgetItem(str(count)))
site = SearchableComboBox("Standort suchen …")
site.set_items(site_items, current["site"] or 0)
tenant = SearchableComboBox("Mandant wählen …")
# only a stored choice is shown – never a suggestion
tenant.set_items(tenant_items, current["tenant"])
self.table.setCellWidget(row, 2, site)
self.table.setCellWidget(row, 3, tenant)
self.rows.append((key, site, tenant))
self.table.verticalHeader().hide()
self.table.verticalHeader().setDefaultSectionSize(42)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
self.table.setSelectionMode(QTableWidget.NoSelection)
self.table.horizontalHeader().setStretchLastSection(True)
for column, width in enumerate((330, 50, 360)):
for column, width in enumerate((300, 50, 330, 240)):
self.table.setColumnWidth(column, width)
self.root.addWidget(self.table, 1)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
self.root.addWidget(buttons)
self.site_map, self.ap_sites = dict(site_map), dict(ap_sites)
def _row(self, text, count, items, current, key):
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QTableWidgetItem(text))
self.table.setItem(row, 1, QTableWidgetItem(count))
combo = SearchableComboBox("Standort suchen …")
combo.set_items(items, current)
self.table.setCellWidget(row, 2, combo)
self.rows.append((key, combo))
self.result = {}
def accept(self):
for (kind, key), combo in self.rows:
target = self.site_map if kind == "site" else self.ap_sites
value = combo.valid_data()
if value:
target[key] = value
else:
target.pop(key, None)
result = {}
for key, site, tenant in self.rows:
if tenant.valid_data() is None and site.valid_data():
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
return
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
self.result = result
super().accept()
class AccessPointsPage(Page):
title = "Access Points"
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
"Seriennummer und MAC, im Mandanten über den Namen) und fehlende anlegen.")
"Seriennummer, MAC und Name) und fehlende anlegen.")
def __init__(self, window):
super().__init__(window)
self.aps = []
self.only_netbox = []
self.engine = None
self.tenants = []
self.roles = []
self.file_name = ""
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
@@ -105,23 +118,23 @@ class AccessPointsPage(Page):
on_click=self.sync))
form = QFormLayout()
form.setHorizontalSpacing(18)
tenant_row = QHBoxLayout()
self.tenant = SearchableComboBox("Mandant wählen …")
self.tenant.setMinimumWidth(320)
tenant_row.addWidget(self.tenant)
self.tenant_hint = label("Standorte und vorhandene APs werden in seiner Mandantengruppe gesucht.", muted=True)
tenant_row.addWidget(self.tenant_hint, 1)
form.addRow("Mandant *", tenant_row)
self.role = SearchableComboBox("Geräterolle wählen …")
self.role.setMinimumWidth(320)
form.addRow("Geräterolle", self.role)
site_row = QHBoxLayout()
self.default_site = SearchableComboBox("Standort wählen …")
self.default_site.setMinimumWidth(320)
site_row.addWidget(self.default_site)
site_row.addWidget(label("Für neue APs ohne zugeordneten Standort – NetBox verlangt für jedes Gerät einen.",
muted=True), 1)
form.addRow("Standard-Standort", site_row)
self.rename = checkbox("Namen vorhandener Geräte aus Sophos übernehmen", True)
form.addRow("", self.rename)
source.add(form)
self.body.addWidget(source)
result = Card("Abgleich")
self.sites_button = result.add_action(button("Standorte zuordnen …", "globe", on_click=self.map_sites))
self.sites_button = result.add_action(button("Standorte && Mandanten …", "globe", on_click=self.map_sites))
self.refresh_button = result.add_action(button("Neu abgleichen", "refresh", on_click=self.compare))
filters = QHBoxLayout()
self.search = SearchField("Name, S/N, MAC, IP, Standort …")
@@ -141,7 +154,9 @@ class AccessPointsPage(Page):
Column("ip", "IP-Adresse", 110),
Column("site_hint", "Sophos-Standort", 170),
Column("netbox_site", "NetBox-Standort", 190,
color=lambda row: "warning" if row["state"] == "new" and not row.get("site_id") else None),
color=lambda row: "warning" if row["state"] == "new" and not row.get("site_id")
else ("text_muted" if str(row.get("netbox_site", "")).startswith("Standard:") else None)),
Column("tenant", "Mandant", 150),
Column("netbox_device", "NetBox-Gerät", 170),
Column("method", "Gefunden über", 110, color=lambda row: "text_muted"),
Column("issues", "Hinweise", 260, value=lambda row: "; ".join(row.get("issues", [])),
@@ -167,8 +182,9 @@ class AccessPointsPage(Page):
self.search.textChanged.connect(self.proxy.set_text)
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
self.tenant.activated.connect(lambda _index: self._tenant_chosen())
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
self._refresh()))
self.rename.toggled.connect(lambda value: self._store(rename=value))
self.state.profile_switched.connect(self._profile_switched)
self._profile_switched()
@@ -187,16 +203,16 @@ class AccessPointsPage(Page):
self.state.touch()
def _profile_switched(self):
self.aps, self.only_netbox, self.engine, self.tenants = [], [], None, []
self.tenant.set_items([])
self.aps, self.only_netbox, self.engine, self.roles = [], [], None, []
self.role.set_items([])
self.default_site.set_items([])
self.rename.blockSignals(True)
self.rename.setChecked(self._settings().get("rename", True))
self.rename.blockSignals(False)
self._refresh()
def on_show(self):
if not self.tenants and self._netbox_ready() and not self.tasks.busy:
if not self.roles and self._netbox_ready() and not self.tasks.busy:
self._load_lists()
def set_busy(self, busy):
@@ -233,35 +249,24 @@ class AccessPointsPage(Page):
def work(ctx):
nb = connect(ctx)
ctx.log("Lade Mandanten und Geräterollen …")
tenants = sorted(((item.name, item.id) for item in nb.tenancy.tenants.all()), key=lambda x: x[0].casefold())
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
return tenants, roles
ctx.log("Lade Geräterollen …")
return sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
def done(result):
self.tenants, roles = result
def done(roles):
self.roles = roles
settings = self._settings()
self.tenant.set_items(self.tenants, settings.get("tenant_id"))
role_id = settings.get("role_id") or next(
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
or "access point" in name.casefold()), None)
self.role.set_items(roles, role_id)
if then_compare and self.tenant.valid_data():
if then_compare:
QTimer.singleShot(0, self.compare)
self.tasks.run(work, title="Mandanten laden", area="app", on_success=done,
self.tasks.run(work, title="Geräterollen laden", area="app", on_success=done,
on_error=self.actions._netbox_failed)
def _tenant_chosen(self):
self._store(tenant_id=self.tenant.valid_data())
if self.aps and self.tenant.valid_data():
self.compare()
def compare(self):
tenant_id = self.tenant.valid_data()
if not self.aps or not tenant_id or self.tasks.busy:
if not tenant_id and self.aps:
self.window.toast("Bitte zuerst den Mandanten wählen.", "info")
if not self.aps or self.tasks.busy:
return
connect = self.actions._connector()
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
@@ -270,14 +275,17 @@ class AccessPointsPage(Page):
def work(ctx):
engine = APSyncEngine(connect(ctx), ctx.log)
ctx.log("Lade Standorte und vorhandene Access Points der Mandantengruppe …")
engine.load_context(tenant_id)
ctx.log("Lade Standorte, Mandanten und vorhandene Sophos-Geräte …")
engine.load_context()
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
only_netbox = engine.match(aps)
return engine, aps, only_netbox
def done(result):
self.engine, self.aps, self.only_netbox = result
self.default_site.set_items([(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""),
site["id"]) for site in self.engine.ap_sites],
self._settings().get("default_site"))
found = sum(1 for ap in self.aps if ap.get("device"))
logger("app").log(25, "Abgleich: %s von %s APs in NetBox, %s nur in NetBox", found, len(self.aps),
len(self.only_netbox))
@@ -290,41 +298,66 @@ class AccessPointsPage(Page):
# Table
# ------------------------------------------------------------------
def _site_for(self, ap):
def _placement(self, ap):
"""Site (optional) and tenant for a new AP: stored choice, else the suggestion."""
settings = self._settings()
chosen = (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"])
if chosen:
return chosen
return self.engine.suggest_site(ap["site_hint"]) if self.engine else None
if stored:
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
return {"site": site, "tenant": None, "stored": False, "ignored": False}
def _tenant_for(self, placement):
return placement.get("tenant")
def _site_name(self, site_id):
sites = self.engine.ap_sites if self.engine else []
return next((site["name"] for site in sites if site["id"] == site_id), "")
def _tenant_name(self, tenant_id):
tenants = self.engine.group_tenants if self.engine else []
return next((tenant["name"] for tenant in tenants if tenant["id"] == tenant_id), "")
def _refresh(self):
rows = []
default_site = self.default_site.valid_data()
for ap in self.aps:
device = ap.get("device")
site_id = None if device else self._site_for(ap)
site_id = tenant_name = None
if device:
site = getattr(device, "site", None)
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(
related_id(device, "tenant"))
elif self.engine and self._placement(ap)["ignored"]:
site_name = ""
elif self.engine:
site_name = self._site_name(site_id) if site_id else "– zuordnen –"
placement = self._placement(ap)
site_id = placement["site"] or default_site
site_name = (self._site_name(placement["site"]) if placement["site"] else
f"Standard: {self._site_name(default_site)}" if default_site else "– Standard-Standort fehlt –")
tenant_name = self._tenant_name(self._tenant_for(placement))
else:
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,
netbox_site=site_name, netbox_device=device.name if device else "",
method=ap.get("method", "")))
for device in self.only_netbox:
netbox_site=site_name, tenant=tenant_name or "",
netbox_device=device.name if device else "", method=ap.get("method", "")))
# NetBox APs missing in the export – only for tenants this export is about
tenants = {related_id(ap["device"], "tenant") for ap in self.aps if ap.get("device")}
tenants |= {self._tenant_for(self._placement(ap)) for ap in self.aps if not ap.get("device")}
tenants.discard(None)
for device in (device for device in self.only_netbox if related_id(device, "tenant") in tenants):
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
"serial": getattr(device, "serial", "") or "", "mac": "",
"ip": str(getattr(getattr(device, "primary_ip4", None), "address", "") or "").split("/")[0],
"site_hint": "", "netbox_site": getattr(getattr(device, "site", None), "name", "")
or self._site_name(related_id(device, "site")),
"tenant": self._tenant_name(related_id(device, "tenant")),
"netbox_device": device.name, "method": "",
"issues": ["In NetBox, aber nicht im Sophos-Export"]})
self.model.set_rows(rows)
@@ -334,11 +367,13 @@ class AccessPointsPage(Page):
if self.engine:
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
f"{counts['netbox_only']} nur in NetBox"]
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"))
if missing_sites:
parts.append(f"{missing_sites} ohne NetBox-Standort")
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
elif self.aps:
parts.append("Mandant wählen, um mit NetBox abzugleichen" if self._netbox_ready()
parts.append("Abgleich mit NetBox läuft …" if self._netbox_ready()
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
self._update_buttons()
@@ -346,7 +381,7 @@ class AccessPointsPage(Page):
def _update_buttons(self):
busy = self.tasks.busy
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
"Bitte Export laden und Mandanten wählen." if not self.engine else "Bitte warten …")
"Bitte einen Export laden." if not self.engine else "Bitte warten …")
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
@@ -361,49 +396,63 @@ class AccessPointsPage(Page):
if not self.engine:
return False
new = self._new_aps()
hints = {}
groups = {}
for ap in new:
if ap["site_hint"]:
hints[ap["site_hint"]] = hints.get(ap["site_hint"], 0) + 1
settings = self._settings()
dialog = SiteMappingDialog(
self.window, [(hint, count, self.engine.suggest_site(hint)) for hint, count in sorted(hints.items())],
[ap for ap in new if not ap["site_hint"]], self.engine.ap_sites,
settings.get("site_map") or {}, settings.get("ap_sites") or {})
groups.setdefault(ap["site_hint"], []).append(ap)
rows = [(hint, len(members), ("site", hint), self._placement(members[0]))
for hint, members in sorted(groups.items(), key=lambda pair: pair[0].casefold())]
rows += [(f"{ap['name']} (ohne Sophos-Standort)", 1, ("ap", ap_key(ap)), self._placement(ap))
for ap in new if not ap["site_hint"]]
if not rows:
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
return False
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants)
if not dialog.exec():
return False
self._store(site_map=dialog.site_map, ap_sites=dialog.ap_sites)
settings = self._settings()
site_map, ap_sites = dict(settings.get("site_map") or {}), dict(settings.get("ap_sites") or {})
for (kind, key), value in dialog.result.items():
(site_map if kind == "site" else ap_sites)[key] = value
self._store(site_map=site_map, ap_sites=ap_sites)
self._refresh()
return True
def sync(self):
if not self.engine or self.tasks.busy:
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()
if new and not role_id:
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
"info")
return
if any(not self._site_for(ap) for ap in new) and not self.map_sites():
if any(not self._placement(ap)["stored"] for ap in new):
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()
placements = {}
for ap in new:
placement = self._placement(ap)
placements[ap_key(ap)] = {"site": placement["site"], "tenant": self._tenant_for(placement)}
homeless = [ap["name"] for ap in new if not placements[ap_key(ap)]["site"]]
if homeless and not default_site:
widgets.message(self.window, "Standard-Standort fehlt",
f"{len(homeless)} neue Access Points haben keinen Standort. NetBox verlangt für jedes "
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
"\n".join(homeless))
return
sites = {ap_key(ap): self._site_for(ap) for ap in new}
missing = [ap["name"] for ap in new if not sites.get(ap_key(ap))]
if missing and not widgets.confirm(
self.window, "Standorte fehlen", f"{len(missing)} neue Access Points haben keinen NetBox-Standort und "
"werden übersprungen.", ok_text="Trotzdem fortfahren", details="\n".join(missing)):
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 preview(ctx):
ctx.log("Berechne Änderungen …")
return engine.sync(aps, sites, role_id, rename, dry_run=True)
def run(dry_run):
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
def show(report):
def ask():
if ClientPreviewDialog(self.window, report).exec():
self.tasks.run(lambda ctx: engine.sync(aps, sites, role_id, rename, dry_run=False),
title="Access Points übertragen", area="app", on_success=applied,
self.tasks.run(run(False), title="Access Points übertragen", area="app", on_success=applied,
on_error=self.actions._netbox_failed)
QTimer.singleShot(0, ask)
@@ -416,5 +465,5 @@ class AccessPointsPage(Page):
self.window.toast(text, "warning" if report["errors"] else "success")
QTimer.singleShot(0, self.compare)
self.tasks.run(preview, title="Änderungen berechnen", area="app", on_success=show,
self.tasks.run(run(True), title="Änderungen berechnen", area="app", on_success=show,
on_error=self.actions._netbox_failed)
+33 -4
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, 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.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
@@ -93,12 +93,23 @@ class SwitchesPage(Page):
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
self.update_cables_option = checkbox(
"Bestehende Kabel anpassen",
tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, "
"wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie "
"verändert. Ohne diese Option werden Abweichungen nur gemeldet.")
self.backup_option = checkbox("Konfiguration als Anhang sichern",
tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät "
"(Plugin netbox-attachments). Passwörter, Schlüssel und Communities "
"werden entfernt; ein neuer Anhang entsteht nur bei Änderungen.")
filters.addWidget(self.search, 2)
filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors)
filters.addStretch(1)
filters.addWidget(self.cables_option)
filters.addWidget(self.update_cables_option)
filters.addWidget(self.backup_option)
result_card.add(filters)
result_columns = [
Column("switch", "Switch", 140),
@@ -108,8 +119,8 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
Column("vlans", "VLANs", 110, value=lambda row: port_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))), row.get("lag"))),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
@@ -144,6 +155,9 @@ class SwitchesPage(Page):
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
self.update_cables_option.toggled.connect(self._toggle_update_cables)
self.cables_option.toggled.connect(self.update_cables_option.setEnabled)
self.state.switches_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.state.profile_edited.connect(self.refresh_switches)
@@ -155,10 +169,25 @@ class SwitchesPage(Page):
# ------------------------------------------------------------------
def _load_settings(self):
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"),
(self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")):
widget.blockSignals(True)
widget.setChecked(bool(self.state.settings.get(key)))
widget.blockSignals(False)
self.update_cables_option.setEnabled(self.cables_option.isChecked())
def _toggle_update_cables(self, value):
if value and not widgets.confirm(
self.window, "Bestehende Kabel anpassen?",
"NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht "
"zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox "
"verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.",
ok_text="Einschalten", destructive=True):
self.update_cables_option.blockSignals(True)
self.update_cables_option.setChecked(False)
self.update_cables_option.blockSignals(False)
return
self.state.update_settings(update_cables=value)
def _status_text(self, row):
status = self.state.switch_status.get(row["id"])
+22
View File
@@ -255,6 +255,28 @@ class EmptyState(QWidget):
layout.addSpacing(6)
layout.addLayout(buttons)
layout.addStretch(2)
layout.setContentsMargins(24, 16, 24, 16)
def _heights(self, width):
width = max(width, 320) - 48
core = 32 + self.title_label.heightForWidth(width) + 10
if self.action is not None:
core += 16 + self.action.sizeHint().height()
return core, self.text_label.heightForWidth(min(width, 520)) + 10, 56 + 10
def minimumSizeHint(self):
# Title and button always fit; icon and text are dropped when space is short.
core, _text, _icon = self._heights(self.width())
return QSize(260, core)
def resizeEvent(self, event):
super().resizeEvent(event)
# Word-wrapped labels report almost no minimum height, so a small card
# would squeeze icon, title, text and button on top of each other.
core, text, icon_height = self._heights(event.size().width())
available = event.size().height()
self.text_label.setVisible(available >= core + text)
self.icon_label.setVisible(available >= core + text + icon_height)
def set_text(self, title=None, text=None):
if title is not None:
+28 -2
View File
@@ -74,7 +74,7 @@ def test_sync_creates_new_aps_with_site_tenant_and_updates_existing():
engine.load_context(7)
aps = parse_csv(CSV)
engine.match(aps)
sites = {ap_key(aps[2]): 21}
sites = {ap_key(aps[2]): {"site": 21}}
preview = engine.sync(aps, sites, role_id=30, dry_run=True)
assert preview["errors"] == [] and preview["devices_created"] == 1 and preview["devices_updated"] == 2
@@ -101,4 +101,30 @@ def test_new_ap_without_site_is_an_error_not_a_guess():
aps = parse_csv(CSV)
engine.match(aps)
report = engine.sync(aps, {}, role_id=30, dry_run=True)
assert report["errors"] == ["Büro ohne Standort: kein NetBox-Standort zugeordnet"]
assert report["errors"][0].startswith("Büro ohne Standort: kein Standort")
def test_site_is_optional_with_default_site_and_tenant_can_be_chosen():
nb = _netbox()
engine = APSyncEngine(nb)
engine.load_context(7)
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
aps = parse_csv(CSV)
engine.match(aps)
# No site for the new AP: it goes to the default site, with an own tenant.
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
created = nb.dcim.devices.created[-1]
assert (created["site"], created["tenant"]) == (21, 8)
def test_without_tenant_the_whole_netbox_is_searched_and_tenant_comes_from_the_choice():
nb = _netbox()
engine = APSyncEngine(nb)
engine.load_context()
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
assert len(engine.ap_sites) == 2 and len(engine.netbox_aps) == 3
aps = parse_csv(CSV)
engine.match(aps)
assert [ap["device"].id if ap["device"] else None for ap in aps] == [102, 101, None]
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21, "tenant": 7}}, role_id=30, dry_run=False)
assert report["errors"] == [] and nb.dcim.devices.created[-1]["tenant"] == 7
+334 -2
View File
@@ -1,8 +1,18 @@
from types import SimpleNamespace
from fake_netbox import FakeNetBox, Record
from fake_netbox import Endpoint, FakeNetBox, Record
from netbox_sync.core.switches import build_snapshot, match_interfaces, plan_switch_sync, sync_snapshot_to_netbox
from netbox_sync.core.switches import (
build_snapshot,
mask_config,
match_interfaces,
parse_lags,
parse_stack,
plan_switch_sync,
port_label,
stack_member,
sync_snapshot_to_netbox,
)
from test_switches import COMWARE_BRIEF, COMWARE_LLDP
@@ -280,3 +290,325 @@ def test_legacy_network_choices_still_work_and_migrate(tmp_path):
loaded = store.load()[0]["Kunde"]
assert loaded["network_map"] == {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "", "create": True}}
assert "network_vrfs" not in loaded["switches"][0]
CX_STACK_CONFIG = """
hostname Switch36
vsf member 1
type jl661a
link 1 1/1/49
link 2 1/1/50
vsf member 2
type jl661a
link 1 2/1/49
link 2 2/1/51
interface lag 1
no shutdown
no routing
vlan trunk native 1
vlan trunk allowed 10,200-204
interface 1/1/1
no routing
vlan access 10
interface 1/1/52
lag 1
interface 2/1/1
no routing
vlan access 10
interface 2/1/52
lag 1
interface vlan 201
ip address 172.16.201.2/24
"""
def _stack_snapshot():
interfaces = [
{"name": name, "enabled": True, "connected": True, "media": "1GbT", "speed_mbps": 1000, "ip_addresses": [],
"vlans": {"untagged": [10], "tagged": [], "tagged_all": False}}
for name in ("1/1/1", "1/1/2", "2/1/1", "2/1/2")
] + [{"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [], "vlans": None}]
return {"platform": "aruba_cx", "interfaces": interfaces, "neighbors": [],
"stack": parse_stack(CX_STACK_CONFIG, "aruba_cx", interfaces)}
def test_aruba_cx_vsf_stack_is_detected():
stack = parse_stack(CX_STACK_CONFIG, "aruba_cx")
assert stack == [{"member": 1, "model": "jl661a", "mac": ""}, {"member": 2, "model": "jl661a", "mac": ""}]
assert stack_member("2/1/5", "aruba_cx") == 2 and stack_member("lag1", "aruba_cx") is None
assert stack_member("GigabitEthernet2/0/5", "hpe_comware") == 2 and stack_member("2/A3", "aruba_aos") == 2
assert parse_stack("vsf member 1\n type jl661a\n", "aruba_cx") == [], "one member is no stack"
aos = 'stacking\n member 1 type "JL256A" mac-address 9020c2-000001\n member 2 type "JL256A"\n exit\n'
assert [(item["member"], item["model"]) for item in parse_stack(aos, "aruba_aos")] == [(1, "JL256A"), (2, "JL256A")]
def test_stack_members_go_to_their_own_netbox_devices():
nb, switch, _snapshot = _numbered_setup()
snapshot = _stack_snapshot()
# Member 2 is its own NetBox device whose device type named the ports "1/1/x".
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
for index, name in enumerate(("1/1/1", "1/1/2"), start=60):
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=index, name=name, device=SimpleNamespace(id=4),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None,
label=""))
plan = plan_switch_sync(nb, switch, snapshot)
assert [(entry["member"], entry["device_id"], entry["ports"]) for entry in plan["stack"]] == [(1, 1, 2), (2, None, 2)]
assert plan["skipped_ports"] == 2
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert report["notes"] == ["Stack-Mitglied 2: kein NetBox-Gerät gewählt – 2 Ports übersprungen"]
switch["stack_devices"] = {"1": 1, "2": 4}
plan = plan_switch_sync(nb, switch, snapshot)
by_name = {item["name"]: item for item in plan["interfaces"]}
assert by_name["2/1/1"]["owner_id"] == 4 and by_name["2/1/1"]["netbox_name"] == "1/1/1"
assert by_name["1/1/1"]["owner_id"] == 1 and by_name["1/1/1"]["netbox_name"] == "1"
assert plan["owner_interfaces"]["4"] == ["1/1/1", "1/1/2"]
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.dcim.interfaces.get(60).label == "10" and nb.dcim.interfaces.get(1).label == "10"
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
def test_stack_is_filled_in_netbox_utilities_when_the_plugin_exists():
nb, switch, _snapshot = _numbered_setup()
snapshot = _stack_snapshot()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
switch["stack_devices"] = {"1": 1, "2": 4}
# Without the plugin the stack is simply not written.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert not report["errors"] and not any("Switch-Stack" in change for change in report["changes"])
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(switch_stacks=Endpoint()))
stacks = nb.plugins.utilities.switch_stacks
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert "Switch-Stack access-01 neu mit Mitgliedern access-01-2 (NetBox Utilities)" in report["changes"]
assert stacks.created == []
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert stacks.created == [{"device": 1, "members": [4]}]
stacks.records[0].device = SimpleNamespace(id=1)
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert not any("Switch-Stack" in change for change in report["changes"]), "already complete"
# Members entered by hand stay, missing ones are added.
stacks.records[0].members = [9]
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert stacks.updates[-1] == (stacks.records[0].id, {"members": [9, 4]})
def test_virtual_chassis_positions_are_suggested():
nb, switch, _snapshot = _numbered_setup()
snapshot = _stack_snapshot()
nb.dcim.devices.get(1).virtual_chassis = SimpleNamespace(id=9)
nb.dcim.devices.get(1).vc_position = 1
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7),
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
plan = plan_switch_sync(nb, switch, snapshot)
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
CX_LAG_BRIEF = """
Port Native Mode Type Enabled Status Reason Speed Description
1/1/1 1 trunk 10G-SR yes up 10000 SOEM-E1
1/1/2 1 trunk 10G-SR yes up 10000 SOEM-E1
1/1/23 120 access 1G-BT yes up 1000 FritzBox
lag1 1 trunk -- yes up -- 20000 Etage 1 Uplink
"""
CX_LAG_CONFIG = """vlan 1
vlan 100
interface lag 1
no routing
vlan trunk native 1
vlan trunk allowed 100,110,120,201,209-213
interface 1/1/1
no shutdown
lag 1
interface 1/1/2
no shutdown
lag 1
interface 1/1/23
no routing
vlan access 120
"""
def test_lags_are_parsed_for_all_platforms():
assert parse_lags(CX_LAG_CONFIG, "aruba_cx") == {"1/1/1": "lag1", "1/1/2": "lag1"}
assert parse_lags("trunk 49-50 trk1 lacp\ntrunk 1/A1-1/A2 Trk2 trunk\n", "aruba_aos") == {
"49": "Trk1", "50": "Trk1", "1/a1": "Trk2", "1/a2": "Trk2"}
comware = "interface GigabitEthernet1/0/49\n port link-aggregation group 3\n#\n"
assert parse_lags(comware, "hpe_comware") == {"ge1/0/49": "Bridge-Aggregation3"}
def test_lag_members_take_the_lag_vlans_and_name_the_lag_in_the_label():
snapshot = build_snapshot({"interfaces": CX_LAG_BRIEF, "neighbors": "", "config": CX_LAG_CONFIG}, "aruba_cx")
ports = {item["name"]: item for item in snapshot["interfaces"]}
assert ports["1/1/1"]["lag"] == "lag1" and ports["1/1/23"]["lag"] is None
assert port_label(ports["1/1/1"]["vlans"], ports["1/1/1"]["lag"]) == "1,100,110,120,201,209-213 (LAG 1)"
assert port_label(ports["1/1/23"]["vlans"], ports["1/1/23"]["lag"]) == "120"
assert port_label(None, "Trk2") == "(LAG 2)"
assert len(port_label({"untagged": [], "tagged": list(range(2, 400, 2)), "tagged_all": False}, "lag1")) <= 64
assert " lag 1" in snapshot["raw"]["vlan_config"]
def test_lag_members_are_assigned_to_their_lag_in_netbox():
nb, switch, snapshot = _numbered_setup()
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=30, name="lag1", device=SimpleNamespace(id=1),
type=SimpleNamespace(value="lag"), enabled=True, cable=None, label=""))
snapshot["interfaces"].append({"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [],
"vlans": None})
for item in snapshot["interfaces"][:2]:
item["lag"] = "lag1"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert "Interface 1: LAG lag1" in report["changes"] and nb.dcim.interfaces.updates == []
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.dcim.interfaces.get(1).lag == 30 and nb.dcim.interfaces.get(1).label == "10 (LAG 1)"
assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert not any("LAG lag1" in change for change in report["changes"]), "already assigned"
class _AttachmentEndpoint(Endpoint):
def create(self, payload):
record = super().create(payload)
if self.assignments is not None:
record.assignments = []
return record
def filter(self, **kwargs):
query = kwargs.pop("q", "")
return [item for item in super().filter(**kwargs) if query in (getattr(item, "description", "") or "")]
def _attachments(newer=True):
attachments = _AttachmentEndpoint()
attachments.assignments = [] if newer else None
return SimpleNamespace(netbox_attachments=attachments, netbox_attachment_assignments=Endpoint())
def test_config_backup_masks_secrets():
config = ('hostname core\nuser admin group administrators password ciphertext AQBapW==\n'
'snmp-server community geheim\nradius-server host 10.0.0.1 key plaintext topsecret\n')
masked = mask_config(config)
assert "AQBapW" not in masked and "geheim" not in masked and "topsecret" not in masked
assert "hostname core" in masked and "password <entfernt>" in masked
def test_config_is_attached_only_when_it_changed():
nb, switch, snapshot = _numbered_setup()
snapshot["config_backup"] = "hostname access-01"
# Without the plugin nothing happens.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
assert not report["errors"]
nb.plugins = SimpleNamespace(netbox_attachments=_attachments())
app = nb.plugins.netbox_attachments
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
assert any(change.startswith("Konfigurations-Backup: Anhang „Running-Config access-01")
for change in report["changes"]) and app.netbox_attachments.created == []
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
payload = app.netbox_attachments.created[0]
assert payload["file"][1].getvalue() == b"hostname access-01" and payload["file"][0].endswith(".txt")
assert app.netbox_attachment_assignments.created == [
{"attachment": app.netbox_attachments.records[0].id, "object_type": "dcim.device", "object_id": 1}]
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
assert not any("Konfigurations-Backup" in change for change in report["changes"]), "unchanged"
snapshot["config_backup"] = "hostname access-01\nvlan 10"
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
assert len(app.netbox_attachments.created) == 2
def test_config_backup_with_older_attachment_plugin():
nb, switch, snapshot = _numbered_setup()
snapshot["config_backup"] = "hostname access-01"
nb.plugins = SimpleNamespace(netbox_attachments=_attachments(newer=False))
app = nb.plugins.netbox_attachments
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
payload = app.netbox_attachments.created[0]
assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1)
assert app.netbox_attachment_assignments.created == []
def test_cable_to_access_point_that_reports_its_mac_as_port():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E",
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e")
switch["neighbor_devices"] = {"1/1/2": 5}
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
# A device with a single port is cabled there even if neither name nor MAC match.
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc")
switch["neighbor_devices"] = {"1/1/2": 5}
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
def _cabled_setup(far_type="dcim.interface"):
"""Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0."""
nb, switch, snapshot = _numbered_setup()
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
far = {"object_type": far_type, "object_id": 99,
"object": {"name": "eth9", "device": {"name": "old-device"}}}
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far],
b_terminations=[{"object_type": "dcim.interface", "object_id": 2}]))
switch["neighbor_devices"] = {"1/1/2": 2}
return nb, switch, snapshot
def test_differing_cable_is_only_reported_by_default():
nb, switch, snapshot = _cabled_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == []
assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"])
def test_differing_cable_is_moved_when_allowed():
nb, switch, snapshot = _cabled_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True)
assert report["cables_updated"] == 1 and nb.dcim.cables.updates == []
assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"])
sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert nb.dcim.cables.updates == [(70, {
"a_terminations": [{"object_type": "dcim.interface", "object_id": 2}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})]
assert nb.dcim.cables.created == []
def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport")
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"]
nb, switch, snapshot = _cabled_setup()
nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71)
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert nb.dcim.cables.updates == []
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])
def test_vlans_of_another_site_are_only_labelled():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.get(1).site = SimpleNamespace(id=2)
nb.ipam.vlans.records += [
Record(nb.ipam.vlans, id=110, vid=10, name="MOBILE", tenant=SimpleNamespace(id=7), site=SimpleNamespace(id=1)),
Record(nb.ipam.vlans, id=120, vid=20, name="CLIENTS", tenant=SimpleNamespace(id=7), site=None),
]
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.dcim.interfaces.get(1).label == "10" and getattr(nb.dcim.interfaces.get(1), "untagged_vlan", None) is None
assert nb.dcim.interfaces.get(2).untagged_vlan == 120, "global VLANs are always assigned"
assert [note for note in report["notes"] if "VLAN 10" in note] == [
"VLAN 10 „MOBILE“ gehört zu einem anderen Standort als access-01 – nur im Label vermerkt, nicht am Port "
"zugewiesen (VLAN global machen, um es zuzuweisen)"]