Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 781ed7d17b chore: release 4.15.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:35:52 +01:00
MrBlakeandClaude Opus 5.5 05695a8471 feat: one-off switch import from D-Link and Linksys configuration backups
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:35:51 +01:00
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
10 changed files with 593 additions and 14 deletions

No files matched your search

+6
View File
@@ -115,6 +115,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
never changed never changed
- The switch configuration is only changed when "Enable LLDP if needed" is - The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on explicitly switched on
- One-off import without SSH ("Backup importieren …"): configuration backups
of D-Link DGS-1210 (`config.bin`) and Linksys LGS (`*.cfg` or the contained
`SNCSR.conf`) switches are read offline. Hostname, location, management IP,
port descriptions, admin state, untagged/tagged VLANs and VLAN names are
taken over; the switch is matched to the NetBox device by its hostname and
then synchronized like an SSH result (no LLDP neighbors, hence no cables)
### Sophos access points (CSV from Sophos Central) ### Sophos access points (CSV from Sophos Central)
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.14.0" #define AppVersion "4.15.0"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.14.0" APP_VERSION = "4.15.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+338
View File
@@ -0,0 +1,338 @@
"""One-off import of switch configuration backups (no SSH).
Some small switches cannot be read over SSH in a useful way, but their web UI
exports a configuration backup. These parsers turn such a backup into the
same snapshot that :func:`netbox_sync.core.switches.build_snapshot` produces,
so the normal review and synchronization run unchanged.
Supported formats:
* D-Link DGS-1210 series (``config.bin``): a short header with the model name
followed by a zlib-compressed dump of SNMP objects (``OID<TAB>type<TAB>value``).
* Linksys LGS series (``*.cfg``): a firmware header followed by a tar archive
whose ``current_config/SNCSR.conf`` holds an ISS-style CLI configuration.
A plain text ``SNCSR.conf`` is accepted as well.
"""
import io
import ipaddress
import re
import tarfile
import time
import zlib
from netbox_sync.core.switches import _interface, _membership, mask_config
BACKUP_PLATFORMS = {
"dlink_backup": "D-Link (Backup-Datei)",
"linksys_backup": "Linksys LGS (Backup-Datei)",
}
FILE_FILTER = "Switch-Backups (*.bin *.cfg *.conf *.txt);;Alle Dateien (*)"
class BackupError(ValueError):
"""The file is no supported switch backup."""
def parse_backup(data, filename=""):
"""Snapshot of a backup file plus ``name``, ``host`` and ``model`` from its configuration.
Returns ``(switch, snapshot)`` where ``switch`` is a profile entry without credentials.
"""
if isinstance(data, str):
data = data.encode("utf-8")
dump = _dlink_dump(data)
if dump is not None:
return _dlink_snapshot(dump, data)
text = _linksys_text(data)
if text is not None:
return _linksys_snapshot(text)
raise BackupError(f"„{filename or 'Datei'}“ ist kein unterstütztes Backup (D-Link DGS-1210 oder Linksys LGS).")
def _snapshot(platform, interfaces, vlan_names, config_backup=""):
ips = [{"interface": item["name"], "address": address}
for item in interfaces for address in item["ip_addresses"]]
return {
"platform": platform,
"interfaces": interfaces,
"ip_addresses": ips,
"neighbors": [],
"lldp_neighbors": [],
"cdp_neighbors": [],
"raw": {},
"vlans_read": True,
"config_backup": config_backup,
"vlan_names": vlan_names,
"stack": [],
"lldp_disabled": False,
"lldp_enabled_automatically": False,
"discovered_at": time.time(),
"source": "backup",
}
def _address(address, mask):
try:
value = ipaddress.ip_interface(f"{address}/{mask}")
except ValueError:
return None
return None if value.ip.is_unspecified else str(value)
# --------------------------------------------------------------------------
# D-Link DGS-1210
# --------------------------------------------------------------------------
_DLINK_OID = re.compile(rb"^1\.3\.6\.1\.")
def _dlink_dump(data):
"""Decompressed SNMP dump of a D-Link backup, or ``None``."""
if _DLINK_OID.match(data):
return data
if not data[:4] in (b"DGS-", b"DES-", b"DXS-"):
return None
for match in re.finditer(rb"\x78[\x01\x5e\x9c\xda]", data[:512]):
try:
dump = zlib.decompressobj().decompress(data[match.start():])
except zlib.error:
continue
if _DLINK_OID.match(dump):
return dump
raise BackupError("D-Link-Backup erkannt, aber die Konfiguration lässt sich nicht entpacken.")
def parse_snmp_dump(dump):
"""``{OID: value}``; octet strings are ``bytes`` (they may contain line breaks), the rest ``str``."""
values, position, size = {}, 0, len(dump)
while position < size:
if dump[position] in b"\x00\r\n":
position += 1
continue
tab = dump.find(b"\t", position)
if tab < 0:
break
oid = dump[position:tab].decode("ascii", "replace").strip()
type_end = dump.find(b"\t", tab + 1)
line_end = dump.find(b"\n", tab + 1)
if line_end < 0:
line_end = size
if type_end < 0 or type_end > line_end:
position = line_end + 1 # unknown line format
continue
kind = dump[tab + 1:type_end].strip()
if kind == b"4":
length_end = dump.find(b"\t", type_end + 1)
try:
length = int(dump[type_end + 1:length_end])
except ValueError:
position = line_end + 1
continue
start = length_end + 1
values[oid] = dump[start:start + length]
position = start + length + 1
else:
values[oid] = dump[type_end + 1:line_end].decode("ascii", "replace").strip()
position = line_end + 1
return values
def _text(value):
if isinstance(value, bytes):
return value.decode("utf-8", "replace").strip("\x00").strip()
return (value or "").strip()
def _bitmap_ports(value):
"""Ports set in an SNMP PortList (byte 0, bit 7 = port 1)."""
ports = set()
for index, byte in enumerate(value or b""):
for bit in range(8):
if byte & (0x80 >> bit):
ports.add(index * 8 + bit + 1)
return ports
def _table(values, prefix):
"""``{last index: value}`` of all OIDs ``<prefix>.<index>``."""
result = {}
for oid, value in values.items():
if oid.startswith(prefix + ".") and oid[len(prefix) + 1:].isdigit():
result[int(oid[len(prefix) + 1:])] = value
return result
def _dlink_snapshot(dump, data):
values = parse_snmp_dump(dump)
# The enterprise subtree of the model, e.g. 1.3.6.1.4.1.171.10.76.21.1 for DGS-1210-28P.
base = next((match.group(1) for match in
(re.match(r"^(1\.3\.6\.1\.4\.1\.171\.10(?:\.\d+)+?)\.7\.6\.1\.1\.\d+$", oid) for oid in values)
if match), None)
names, egress, untagged, pvids = {}, {}, {}, {}
if base:
names = _table(values, f"{base}.7.6.1.1")
egress = _table(values, f"{base}.7.6.1.2")
untagged = _table(values, f"{base}.7.6.1.4")
pvids = _table(values, f"{base}.7.7.1.1")
if not egress: # standard Q-BRIDGE-MIB
names = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.1")
egress = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.2")
untagged = _table(values, "1.3.6.1.2.1.17.7.1.4.3.1.4")
pvids = _table(values, "1.3.6.1.2.1.17.7.1.4.5.1.1")
admin = _table(values, "1.3.6.1.2.1.2.2.1.7")
descriptions = _table(values, f"{base}.1.16.1.2") if base else {}
if not descriptions:
descriptions = _table(values, "1.3.6.1.2.1.31.1.1.1.18")
port_numbers = sorted(set(pvids) | set(admin) | set(descriptions))
if not port_numbers:
raise BackupError("Im D-Link-Backup wurden keine Ports gefunden.")
members = {port: {"untagged": set(), "tagged": set()} for port in port_numbers}
for vid, bitmap in egress.items():
untagged_ports = _bitmap_ports(untagged.get(vid))
for port in _bitmap_ports(bitmap):
if port in members:
members[port]["untagged" if port in untagged_ports else "tagged"].add(vid)
interfaces = []
for port in port_numbers:
entry = members[port]
interfaces.append(_interface(
str(port),
enabled=str(admin.get(port, "1")) != "2",
description=_text(descriptions.get(port)),
vlans=_membership(entry["untagged"], entry["tagged"]) if entry["untagged"] or entry["tagged"] else None,
lag=None,
))
if base:
address = _address(_text(values.get(f"{base}.2.5.2.0")), _text(values.get(f"{base}.2.5.3.0")))
if address:
interfaces.append(_interface(_text(values.get(f"{base}.2.5.5.0")) or "System", connected=True,
description="Management-Interface", virtual=True,
ip_addresses=[address], vlans=None, lag=None))
vlan_names = {vid: _text(name) for vid, name in names.items() if _text(name)}
model = data[:16].split(b"\x00", 1)[0].decode("ascii", "replace") if not _DLINK_OID.match(data) else ""
name = _text(values.get("1.3.6.1.2.1.1.5.0")) or (_text(values.get(f"{base}.2.7.0")) if base else "")
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
switch = {"name": name, "host": host, "model": model, "platform": "dlink_backup",
"location": _text(values.get("1.3.6.1.2.1.1.6.0"))}
return switch, _snapshot("dlink_backup", interfaces, vlan_names)
# --------------------------------------------------------------------------
# Linksys LGS (ISS CLI configuration)
# --------------------------------------------------------------------------
_LINKSYS_MEMBER = "current_config/SNCSR.conf"
def _linksys_text(data):
"""``SNCSR.conf`` of a Linksys backup, or ``None``."""
offset = data.find(_LINKSYS_MEMBER.encode())
if offset >= 0:
try:
with tarfile.open(fileobj=io.BytesIO(data[offset:]), mode="r:") as archive:
stream = archive.extractfile(_LINKSYS_MEMBER)
if stream is not None:
return stream.read().decode("utf-8", "replace")
except (tarfile.TarError, KeyError) as error:
raise BackupError(f"Linksys-Backup erkannt, aber nicht lesbar: {error}") from error
head = data[:200_000].decode("utf-8", "replace")
if re.search(r"(?m)^interface gigabitethernet \d+/\d+\s*$", head) and re.search(r"(?m)^vlan \d+\s*$", head):
return data.decode("utf-8", "replace")
return None
_GI_PORT = re.compile(r"(?:gigabitethernet|gi)\s*(\d+)/(\d+)(?:-(\d+))?", re.I)
def _linksys_ports(text):
"""Port numbers in ``gigabitethernet 0/1``, ``gi 0/1-4`` or comma lists."""
ports = []
for match in _GI_PORT.finditer(text):
start, end = int(match.group(2)), int(match.group(3) or match.group(2))
ports += range(start, end + 1)
return ports
def _linksys_blocks(text):
"""``(header, lines)`` for every top-level block; ISS repeats blocks per feature."""
header, body = None, []
for raw in text.replace("\r", "").splitlines():
line = raw.strip()
if line == "!":
if header:
yield header, body
header, body = None, []
elif header is None and re.match(r"^(?:interface|vlan)\s+", line, re.I):
header, body = line, []
elif header is not None:
body.append(line)
if header:
yield header, body
def _linksys_snapshot(text):
ports, vlan_names, vlan_members, lags = {}, {}, {}, {}
ips = {}
for header, body in _linksys_blocks(text):
port = re.match(r"(?i)^interface gigabitethernet (\d+)/(\d+)$", header)
vlan_interface = re.match(r"(?i)^interface vlan (\d+)$", header)
vlan = re.match(r"(?i)^vlan (\d+)$", header)
if port:
entry = ports.setdefault(int(port.group(2)), {"enabled": True, "description": ""})
for line in body:
if line == "shutdown":
entry["enabled"] = False
elif line == "no shutdown":
entry["enabled"] = True
description = re.match(r'^description\s+"?(.*?)"?$', line)
if description:
entry["description"] = description.group(1)
group = re.match(r"^channel-group (\d+)\b", line)
if group:
lags[int(port.group(2))] = f"Po{group.group(1)}"
elif vlan_interface:
for line in body:
address = re.match(r"^ip address (\S+) (\S+)$", line)
if address:
value = _address(address.group(1), address.group(2))
if value:
ips.setdefault(int(vlan_interface.group(1)), []).append(value)
elif vlan:
vid = int(vlan.group(1))
members = vlan_members.setdefault(vid, {"untagged": set(), "tagged": set()})
for line in body:
name = re.match(r'^(?:ports\s+)?name\s+"?(.+?)"?$', line)
if name:
vlan_names[vid] = name.group(1)
added = re.match(r"(?i)^ports add (.+?)(?:\s+untagged\s+(.+))?$", line)
if added:
untagged = set(_linksys_ports(added.group(2) or ""))
for number in _linksys_ports(added.group(1)):
members["untagged" if number in untagged else "tagged"].add(number)
if not ports:
raise BackupError("In der Linksys-Konfiguration wurden keine Ports gefunden.")
interfaces = []
for number in sorted(ports):
untagged = {vid for vid, item in vlan_members.items() if number in item["untagged"]}
tagged = {vid for vid, item in vlan_members.items() if number in item["tagged"]}
interfaces.append(_interface(
f"GE{number}",
enabled=ports[number]["enabled"],
description=ports[number]["description"],
vlans=_membership(untagged, tagged) if untagged or tagged else None,
lag=lags.get(number),
))
for vid in sorted(ips):
interfaces.append(_interface(f"vlan{vid}", connected=True, description="Management-Interface",
virtual=True, ip_addresses=ips[vid], vlans=None, lag=None))
system = {key: (re.search(rf'(?m)^system {key} "?(.*?)"?\s*$', text) or [None, ""])[1]
for key in ("name", "location")}
model = (re.search(r'(?m)^set switch-name "?(.*?)"?\s*$', text) or [None, ""])[1]
host = next((item["ip_addresses"][0].split("/")[0] for item in interfaces if item["ip_addresses"]), "")
switch = {"name": system["name"], "host": host, "model": model, "platform": "linksys_backup",
"location": system["location"]}
return switch, _snapshot("linksys_backup", interfaces, vlan_names, mask_config(text))
+32 -6
View File
@@ -1571,8 +1571,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
report["errors"].append(f"Prefix {network}: {error}") report["errors"].append(f"Prefix {network}: {error}")
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report): 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.""" """``{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) _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, 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 approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
@@ -1580,6 +1584,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
for vid, (record, method, name) in matches.items(): for vid, (record, method, name) in matches.items():
if record is not None: if record is not None:
present[vid] = record.id present[vid] = record.id
sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid))
continue continue
if method != "new" or vid not in approved: if method != "new" or vid not in approved:
continue continue
@@ -1592,6 +1597,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
if site_id: if site_id:
payload["site"] = site_id payload["site"] = site_id
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).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 except Exception as error: # noqa: BLE001
report["errors"].append(f"VLAN {vid}: {error}") report["errors"].append(f"VLAN {vid}: {error}")
return present return present
@@ -1676,6 +1682,24 @@ def _sync_switch_stack(nb, device, members, dry_run, report):
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}") 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): def _sync_lag_members(snapshot, owners, records, dry_run, report):
"""Assign member ports to their LAG interface (NetBox field ``lag``).""" """Assign member ports to their LAG interface (NetBox field ``lag``)."""
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]} names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
@@ -1811,7 +1835,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
device_id = device.id device_id = device.id
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report) vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, 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")) ignored = ignored_vlans(config.get("vlan_map"))
members = stack_devices(nb, config, snapshot, device) members = stack_devices(nb, config, snapshot, device)
owners = _interface_owners(snapshot, members, device) owners = _interface_owners(snapshot, members, device)
@@ -1823,7 +1848,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
and stack_member(name, snapshot.get("platform")) == member) and stack_member(name, snapshot.get("platform")) == member)
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen") report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
_sync_switch_stack(nb, device, members, dry_run, report) _sync_switch_stack(nb, device, members, dry_run, report)
records = {} records, foreign = {}, set()
for interface in snapshot["interfaces"]: for interface in snapshot["interfaces"]:
key = interface_key(interface["name"]) key = interface_key(interface["name"])
@@ -1834,6 +1859,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
where = f" auf {owner.name}" if owner.id != device_id else "" where = f" auf {owner.name}" if owner.id != device_id else ""
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored)) port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = port_label(port["vlans"], interface.get("lag")) 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: try:
if record: if record:
changes = {} changes = {}
@@ -1843,7 +1869,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
# routed ports and snapshots without configuration. # routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label: if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label changes["label"] = label
changes.update(_vlan_assignment(port, vlan_ids, record)) changes.update(_vlan_assignment(port, owner_vlans, record))
if changes: if changes:
report["interfaces_updated"] += 1 report["interfaces_updated"] += 1
texts = [] texts = []
@@ -1868,7 +1894,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
} }
if label: if label:
payload["label"] = label payload["label"] = label
payload.update(_vlan_assignment(port, vlan_ids)) payload.update(_vlan_assignment(port, owner_vlans))
if interface.get("description"): if interface.get("description"):
payload["description"] = interface["description"][:200] payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1 report["interfaces_created"] += 1
+50 -2
View File
@@ -1,6 +1,7 @@
"""Long-running operations started from the UI. Everything here runs in background tasks.""" """Long-running operations started from the UI. Everything here runs in background tasks."""
import threading import threading
from pathlib import Path
import time import time
import uuid import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -8,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from PySide6.QtCore import QTimer from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QFileDialog from PySide6.QtWidgets import QFileDialog
from netbox_sync.core import exchange, netbox from netbox_sync.core import backups, exchange, netbox
from netbox_sync.core.client_sync import ClientSyncEngine 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.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
from netbox_sync.core.config import known_hosts_path from netbox_sync.core.config import known_hosts_path
@@ -328,6 +329,50 @@ class Actions:
logger("switch").log(25, "%s", text) logger("switch").log(25, "%s", text)
self.window.toast(text) self.window.toast(text)
def import_switch_backups(self):
"""One-off import of D-Link/Linksys configuration backups instead of SSH."""
if self.state.profile is None:
return
paths, _filter = QFileDialog.getOpenFileNames(self.window, "Switch-Backup importieren", "",
backups.FILE_FILTER)
if not paths:
return
devices = {row["name"].casefold(): row for row in self.state.netbox_devices or []}
items, failures = [], []
for path in paths:
name = Path(path).name
try:
switch, snapshot = backups.parse_backup(Path(path).read_bytes(), name)
except (OSError, backups.BackupError) as error:
failures.append(f"{name}: {error}")
continue
switch["name"] = switch["name"] or Path(path).stem
device = devices.get(switch["name"].casefold())
items.append({"switch": {"name": device["name"] if device else switch["name"],
"device_id": device["id"] if device else None,
"platform": switch["platform"], "host": switch["host"], "port": 22},
"snapshot": snapshot, "file": name})
if items:
snapshots, added = exchange.merge_switches(self.state.switches, items, lambda: uuid.uuid4().hex)
by_id = {switch["id"]: switch for switch in self.state.switches}
for switch_id, snapshot in snapshots.items():
self.state.switch_snapshots[switch_id] = snapshot
self.state.switch_status[switch_id] = ("ok", "aus Backup · " + describe_snapshot(snapshot))
stored = by_id.get(switch_id)
if stored and stored.get("platform", "auto") == "auto":
stored["platform"] = snapshot["platform"]
self.state.touch()
if added:
self.state.touch()
self.state.switches_changed.emit()
names = ", ".join(item["switch"]["name"] for item in items)
logger("switch").log(25, "Backup importiert: %s", names)
self.window.toast(f"{len(items)} Switch-Backup(s) geladen" + (f", {added} neu im Profil" if added else "")
+ " – jetzt „Nach NetBox übertragen“ wählen")
if failures:
widgets.message(self.window, "Nicht alle Backups gelesen",
f"{len(items)} von {len(paths)} Datei(en) importiert.", "warning", "\n".join(failures))
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Switches # Switches
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@@ -358,7 +403,8 @@ class Actions:
on_error=self._netbox_failed) on_error=self._netbox_failed)
def discover_switches(self, switches): def discover_switches(self, switches):
switches = [dict(switch) for switch in switches if switch.get("enabled", True)] switches = [dict(switch) for switch in switches if switch.get("enabled", True)
and switch.get("platform") not in backups.BACKUP_PLATFORMS]
if not switches: if not switches:
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info") widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
return return
@@ -530,6 +576,8 @@ class Actions:
update_cables=update_cables) update_cables=update_cables)
for error in report["errors"]: for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error") ctx.log(f"{switch['name']}: {error}", "error")
for note in report.get("notes", []):
ctx.log(f"{switch['name']}: {note}", "warning")
reports.append((switch, report)) reports.append((switch, report))
return reports return reports
+7 -2
View File
@@ -551,6 +551,9 @@ class SyncPreviewDialog(_Dialog):
errors = sum(len(report["errors"]) for _switch, report in reports) errors = sum(len(report["errors"]) for _switch, report in reports)
if errors: if errors:
items.append((f"{errors} Probleme", "error")) 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: for text, kind in items:
summary.addWidget(Badge(text, kind)) summary.addWidget(Badge(text, kind))
summary.addStretch(1) summary.addStretch(1)
@@ -566,7 +569,9 @@ class SyncPreviewDialog(_Dialog):
changes = report["changes"] changes = report["changes"]
total_changes += len(changes) total_changes += len(changes)
unchanged = report["interfaces_unchanged"] 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"))) top.setIcon(0, icon("network", theme.color("accent")))
font = top.font(0) font = top.font(0)
font.setBold(True) font.setBold(True)
@@ -595,7 +600,7 @@ class SyncPreviewDialog(_Dialog):
top.addChild(member) top.addChild(member)
member.setExpanded(True) member.setExpanded(True)
tree.addTopLevelItem(top) 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) self.root.addWidget(tree, 1)
if total_changes == 0: if total_changes == 0:
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success")) self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
+10 -2
View File
@@ -4,6 +4,7 @@ import uuid
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.backups import BACKUP_PLATFORMS
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, port_label, without_vlans from netbox_sync.core.switches import PLATFORMS, ignored_vlans, port_label, without_vlans
from netbox_sync.ui import widgets from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
@@ -23,7 +24,8 @@ def _speed(value):
class SwitchesPage(Page): class SwitchesPage(Page):
title = "Switche" title = "Switche"
subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung " subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung "
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware.") "dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware – D-Link und Linksys "
"per Backup-Datei.")
def __init__(self, window): def __init__(self, window):
super().__init__(window) super().__init__(window)
@@ -36,7 +38,7 @@ class SwitchesPage(Page):
self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover)) self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover))
columns = [ columns = [
Column("name", "NetBox-Gerät", 200), Column("name", "NetBox-Gerät", 200),
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform"), row.get("platform"))), Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform")) or BACKUP_PLATFORMS.get(row.get("platform"), row.get("platform"))),
Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"), Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"),
Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein", Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein",
color=lambda row: None if row.get("enabled", True) else "text_faint"), color=lambda row: None if row.get("enabled", True) else "text_faint"),
@@ -81,6 +83,11 @@ class SwitchesPage(Page):
self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file, self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
tooltip="Ausleseergebnisse aus einer im Offline-Modus " tooltip="Ausleseergebnisse aus einer im Offline-Modus "
"erstellten Exportdatei (JSON) laden.")) "erstellten Exportdatei (JSON) laden."))
self.backup_button = result_card.add_action(button(
"Backup importieren …", "folder", on_click=self.actions.import_switch_backups,
tooltip="Einmal-Import ohne SSH: Konfigurations-Backup eines D-Link- (DGS-1210, config.bin) oder "
"Linksys-Switches (LGS, *.cfg) laden. Der Switch wird über seinen Hostnamen dem NetBox-Gerät "
"zugeordnet."))
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw)) self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary", self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync)) on_click=self.sync))
@@ -282,6 +289,7 @@ class SwitchesPage(Page):
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.") widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
self.add_button.setEnabled(not busy) self.add_button.setEnabled(not busy)
self.file_button.setEnabled(not busy) self.file_button.setEnabled(not busy)
self.backup_button.setEnabled(not busy)
def set_busy(self, busy): def set_busy(self, busy):
self._update_buttons() self._update_buttons()
+132
View File
@@ -0,0 +1,132 @@
import io
import tarfile
import zlib
import pytest
from netbox_sync.core.backups import BackupError, parse_backup, parse_snmp_dump
BASE = "1.3.6.1.4.1.171.10.76.21.1"
def _octets(oid, value):
value = value if isinstance(value, bytes) else value.encode()
return f"{oid}\t 4\t{len(value):4d}\t".encode() + value + b"\n"
def _scalar(oid, kind, value):
return f"{oid}\t{kind:>2}\t{value}\n".encode()
def dlink_backup():
dump = b"".join([
_octets("1.3.6.1.2.1.1.5.0", "SW-01"),
_octets("1.3.6.1.2.1.1.6.0", "Keller"),
_octets(f"{BASE}.1.16.1.2.1", "Uplink"),
_octets(f"{BASE}.1.16.1.2.2", ""),
_octets(f"{BASE}.1.16.1.2.3", ""),
_octets(f"{BASE}.7.6.1.1.10", "LAN"),
_octets(f"{BASE}.7.6.1.1.20", "VOICE"),
# Bitmaps may contain a line break (0x0a) – the parser must honour the length.
_octets(f"{BASE}.7.6.1.2.10", b"\xe0\x00\x00\x00"),
_octets(f"{BASE}.7.6.1.4.10", b"\x60\x00\x00\x00"),
_octets(f"{BASE}.7.6.1.2.20", b"\x80\x0a\x00\x00"),
_octets(f"{BASE}.7.6.1.4.20", b"\x00\x00\x00\x00"),
_scalar(f"{BASE}.7.7.1.1.1", 66, 10),
_scalar(f"{BASE}.7.7.1.1.2", 66, 10),
_scalar(f"{BASE}.7.7.1.1.3", 66, 10),
_scalar("1.3.6.1.2.1.2.2.1.7.1", 2, 1),
_scalar("1.3.6.1.2.1.2.2.1.7.2", 2, 1),
_scalar("1.3.6.1.2.1.2.2.1.7.3", 2, 2),
_scalar(f"{BASE}.2.5.2.0", 64, "10.0.0.5"),
_scalar(f"{BASE}.2.5.3.0", 64, "255.255.255.0"),
_octets(f"{BASE}.2.5.5.0", "System"),
])
header = b"DGS-1210-28P".ljust(32, b"\x00") + b"\x00" * 16
return header + zlib.compress(dump)
LINKSYS_CONF = """
system name "SW-02"
system location "Büro"
interface gigabitethernet 0/1
shutdown
description "AP"
!
interface gigabitethernet 0/2
shutdown
description ""
!
interface gigabitethernet 0/3
description ""
!
interface gigabitethernet 0/1
no shutdown
!
vlan 1
ports name default
!
vlan 10
ports add gigabitethernet 0/1 untagged gigabitethernet 0/1
ports add gigabitethernet 0/2
!
vlan 20
ports add gigabitethernet 0/2
!
interface vlan 1
ip address 10.0.0.6 255.255.255.0
!
snmp community name SECRET security noAuthUser
set switch-name LGS328MPC
"""
def linksys_backup():
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w") as archive:
data = LINKSYS_CONF.encode()
info = tarfile.TarInfo("current_config/SNCSR.conf")
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
return b"`A \x00 IMG-3.01.252 header".ljust(64, b"\x00") + buffer.getvalue()
def test_snmp_dump_keeps_binary_octets():
values = parse_snmp_dump(_octets("1.2", b"a\nb") + _scalar("1.3", 2, 7))
assert values == {"1.2": b"a\nb", "1.3": "7"}
def test_dlink_backup():
switch, snapshot = parse_backup(dlink_backup(), "config.bin")
assert switch["name"] == "SW-01" and switch["host"] == "10.0.0.5" and switch["model"] == "DGS-1210-28P"
ports = {item["name"]: item for item in snapshot["interfaces"]}
assert ports["1"]["description"] == "Uplink"
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
assert ports["2"]["vlans"]["untagged"] == [10]
assert ports["3"]["enabled"] is False
assert ports["System"]["ip_addresses"] == ["10.0.0.5/24"] and ports["System"]["virtual"]
assert snapshot["vlan_names"] == {10: "LAN", 20: "VOICE"}
def test_linksys_backup():
switch, snapshot = parse_backup(linksys_backup(), "x.cfg")
assert switch == {"name": "SW-02", "host": "10.0.0.6", "model": "LGS328MPC", "platform": "linksys_backup",
"location": "Büro"}
ports = {item["name"]: item for item in snapshot["interfaces"]}
assert ports["GE1"]["enabled"] is True and ports["GE1"]["description"] == "AP"
assert ports["GE1"]["vlans"]["untagged"] == [10]
assert ports["GE2"]["enabled"] is False
assert ports["GE2"]["vlans"] == {"untagged": [], "tagged": [10, 20], "tagged_all": False}
assert ports["GE3"]["vlans"] is None
assert ports["vlan1"]["ip_addresses"] == ["10.0.0.6/24"]
assert "SECRET" not in snapshot["config_backup"]
def test_linksys_plain_text():
switch, _snapshot = parse_backup(LINKSYS_CONF, "SNCSR.conf")
assert switch["name"] == "SW-02"
def test_unknown_file():
with pytest.raises(BackupError):
parse_backup(b"hello world", "x.bin")
+16
View File
@@ -596,3 +596,19 @@ def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True) report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert nb.dcim.cables.updates == [] assert nb.dcim.cables.updates == []
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"]) 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)"]