Compare commits

..
16 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 1bd2d42b5d chore: release 4.16.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:05:26 +01:00
MrBlakeandClaude Opus 5.5 2092f41624 fix: SSH to older switches offering only ssh-rsa/ssh-dss host keys; split switch result filters into two rows
Paramiko 4+ removed ssh-rsa (SHA-1) and ssh-dss; pin to 3.x so switches like
the LANCOM GS-2326P+ can be reached again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:04:59 +01:00
MrBlakeandClaude Opus 5.5 e9e1783360 chore: release 4.16.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 14:48:43 +01:00
MrBlakeandClaude Opus 5.5 576f245b7d feat: LANCOM LCOS SX 3.x switches over SSH (e.g. GS-2326P+)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 14:48:43 +01:00
MrBlakeandClaude Opus 5.5 0e04dae354 chore: release 4.15.1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:50:50 +01:00
MrBlakeandClaude Opus 5.5 63ed535a37 fix: attach the original D-Link config.bin as configuration backup
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:50:19 +01:00
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
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
13 changed files with 1564 additions and 37 deletions

No files matched your search

+37 -1
View File
@@ -62,6 +62,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- VLAN membership per port (untagged and tagged, read from the running
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
@@ -91,9 +97,39 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
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
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- 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
- LANCOM switches with the mode-based LCOS SX 3.x CLI (e.g. GS-2326P+) are read
over SSH: `system`, `port`, `vlan`, `ip` and `lldp` modes with their `show`
commands. Untagged/tagged VLANs follow the egress rule (Access, Hybrid = PVID
untagged, Trunk). There is no running-config; the collected outputs are
attached as backup. "Enable LLDP if needed" switches ports whose LLDP mode is
Disabled/Tx only to `enable` (not saved) and waits one LLDP interval
- 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)
The D-Link `config.bin` is attached to the device unchanged (it contains the
switch's secrets as stored by the switch); the Linksys configuration is
attached as text with secrets removed
### Sophos access points (CSV from Sophos Central)
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.11.0"
#define AppVersion "4.16.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.11.0"
APP_VERSION = "4.16.1"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+342
View File
@@ -0,0 +1,342 @@
"""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 base64
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:
switch, snapshot = _dlink_snapshot(dump, data)
# The original file is attached 1:1 so it can be restored on the switch.
snapshot["config_file"] = {"name": filename or "config.bin", "data": base64.b64encode(data).decode("ascii")}
return switch, snapshot
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))
+269
View File
@@ -0,0 +1,269 @@
"""LANCOM switches with the LCOS SX 3.x mode-based CLI (e.g. GS-2326P+, GS-2310P+).
There is no ``show running-config``: every area is a mode (``port``, ``vlan``,
``lldp``, ``system``, ``ip``) with its own ``show`` command, left with ``exit``.
The outputs are converted into the snapshot of :mod:`netbox_sync.core.switches`.
"""
import ipaddress
import re
import time
from netbox_sync.core.switches import (
CLI_ERROR,
_interface,
_compress_vlans,
_membership,
_run_cli_command,
clean_output,
parse_vlan_list,
)
PLATFORM = "lancom_sx3"
# (mode, command, output key)
COMMANDS = (
("system", "show", "system"),
("port", "show status", "status"),
("port", "show configuration", "port_config"),
("vlan", "show vlan", "vlans"),
("vlan", "show port-config", "vlan_ports"),
("ip", "show", "ip"),
("lldp", "show config", "lldp_config"),
# "{ports}" becomes the port list from "show status", e.g. "1-26".
("lldp", "show info {ports}", "neighbors"),
)
def is_lancom(text):
return bool(re.search(r"(?i)Model Name\s*:\s*LANCOM", text or ""))
# Neighbors usually send LLDP every 30 seconds; after enabling reception we wait for one round.
LLDP_WAIT_SECONDS = 35
def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, wait=LLDP_WAIT_SECONDS):
"""Run :data:`COMMANDS` in their modes; a missing command only leaves its output empty.
With ``enable_lldp`` ports that do not receive LLDP are switched to ``enable``
(running configuration only, nothing is saved).
"""
outputs, mode = {"lldp_enabled_automatically": False}, None
for wanted, command, key in COMMANDS:
if mode != wanted:
if mode:
_run_cli_command(channel, "exit")
_run_cli_command(channel, wanted)
mode = wanted
if "{ports}" in command:
numbers = sorted(parse_status(outputs.get("status", "")))
if not numbers:
outputs[key] = ""
continue
command = command.format(ports=_compress_vlans(numbers))
output = _run_cli_command(channel, command, timeout=60)
if CLI_ERROR.search(output):
log(f"{name}: „{wanted} → {command}“ wird nicht unterstützt")
output = ""
outputs[key] = output
if key == "lldp_config" and enable_lldp:
ports = not_receiving(output)
if ports:
result = _run_cli_command(channel, f"mode {_compress_vlans(ports)} enable")
if CLI_ERROR.search(result) or re.search(r"(?i)permission|denied|privilege", result):
raise RuntimeError(f"LLDP konnte nicht aktiviert werden: {clean_output(result).strip()[:200]}")
outputs["lldp_enabled_automatically"] = True
log(f"{name}: LLDP auf Port(s) {_compress_vlans(ports)} aktiviert – warte {wait} s auf Nachbarn …")
time.sleep(wait)
outputs[key] = _run_cli_command(channel, "show config", timeout=60)
if mode:
_run_cli_command(channel, "exit")
return outputs
def _field(text, label):
match = re.search(rf"(?im)^{re.escape(label)}\s*:\s*(.*?)\s*$", text or "")
return match.group(1) if match else ""
def _speed(text):
match = re.match(r"(?i)^(\d+(?:\.\d+)?)(G|M)?$", text or "")
if not match:
return None
return int(float(match.group(1)) * (1000 if (match.group(2) or "").upper() == "G" else 1))
def parse_status(output):
"""``show status``: ``2/UTP Enabled Up Enabled 1G Full ...``."""
ports = {}
for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)/(\w+)\s+(Enabled|Disabled)\s+(Up|Down)\s+\S+\s+(\S+)", line, re.I)
if match:
up = match.group(4).lower() == "up"
ports[int(match.group(1))] = {
"enabled": match.group(3).lower() == "enabled", "connected": up,
"speed_mbps": _speed(match.group(5)) if up else None,
# Copper ports of these switches are Gigabit; the combo ports report SFP while a module is active.
"media": "SFP" if match.group(2).upper() == "SFP" else "1000T",
}
return ports
def parse_port_config(output):
"""``show configuration``: a port line followed by its description line."""
ports, current = {}, None
for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)\s+(Enabled|Disabled)\s", line, re.I)
if match:
current = int(match.group(1))
ports[current] = {"enabled": match.group(2).lower() == "enabled", "description": ""}
elif current is not None and line.strip() and not set(line.strip()) <= {"-"}:
ports[current]["description"] = line.strip()
current = None
elif current is not None and set(line.strip()) <= {"-"} and line.strip():
current = None
return ports
def parse_vlans(output):
"""``show vlan``: ``({vid: name}, {vid: {ports}})``."""
names, members, current = {}, {}, None
for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)\s+(.*?)\s+(Static|Combined|GVRP|MSTP|MVR|NAS|VCL|Voice)\b\s*(.*)$", line, re.I)
if match:
current = int(match.group(1))
if match.group(2).strip():
names[current] = match.group(2).strip()
members[current] = parse_vlan_list(match.group(4))
elif current is not None and re.match(r"^\s+[\d,\-\s]+$", line):
members[current] |= parse_vlan_list(line) # wrapped port list
else:
current = None
return names, members
def parse_vlan_ports(output):
"""``show port-config``: ``{port: (pvid, egress rule)}``."""
ports = {}
for line in clean_output(output).splitlines():
match = re.match(r"^\s*(\d+)\s+(\d+)\s+\S+\s+\S+\s+(Access|Hybrid|Trunk)\b", line, re.I)
if match:
ports[int(match.group(1))] = (int(match.group(2)), match.group(3).lower())
return ports
def port_membership(vids, pvid, rule):
"""Access: untagged; Trunk: all tagged; Hybrid: the PVID untagged, the rest tagged."""
if not vids:
return None
if rule == "access":
return _membership(vids)
if rule == "trunk":
return _membership((), vids)
return _membership({pvid} & vids, vids - {pvid})
def parse_ip(output):
"""``ip → show``: management address with its VLAN, using the "Current" column."""
def current(label):
values = _field(output, label).split()
return values[-1] if values else ""
try:
address = ipaddress.ip_interface(f"{current('IP Address')}/{current('IP Mask')}")
except ValueError:
return None, None
vlan = current("VLAN ID")
return (None if address.ip.is_unspecified else str(address)), (int(vlan) if vlan.isdigit() else None)
def _lldp_modes(output):
"""``lldp → show config``: ``{port: mode}``."""
return {int(port): mode.lower() for port, mode in re.findall(
r"(?im)^\s*(\d+)\s+(Enabled|Disabled|Rx[ _-]?only|Tx[ _-]?only)\b", clean_output(output or ""))}
def not_receiving(output):
"""Ports that drop received LLDP (mode Disabled or Tx only)."""
return sorted(port for port, mode in _lldp_modes(output).items() if mode == "disabled" or mode.startswith("tx"))
def lldp_receiving(output):
"""``False`` when no port receives LLDP; ``True`` when unknown (no warning)."""
modes = _lldp_modes(output)
return not modes or len(not_receiving(output)) < len(modes)
def parse_neighbors(output):
"""``lldp → show info``: one block per neighbor, ``Label : value`` lines."""
neighbors = []
blocks = re.split(r"(?im)^(?=\s*Local Port\s*:)", clean_output(output or ""))
for block in blocks:
local = _field(block, "Local Port")
if not local:
continue
port = re.match(r"(\d+)", local)
neighbors.append({
"local_port": port.group(1) if port else local,
"system_name": _field(block, "System Name"),
"remote_port": _field(block, "Port ID") or _field(block, "Port Description"),
"port_description": _field(block, "Port Description"),
"management_ip": (re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", _field(block, "Management Address"))
or [""])[0],
"chassis_id": _field(block, "Chassis ID"),
"protocol": "LLDP",
})
return neighbors
def build_snapshot(outputs):
status = parse_status(outputs.get("status", ""))
config = parse_port_config(outputs.get("port_config", ""))
names, members = parse_vlans(outputs.get("vlans", ""))
vlan_ports = parse_vlan_ports(outputs.get("vlan_ports", ""))
vlans_read = bool(members and vlan_ports)
interfaces = []
for number in sorted(set(status) | set(config)):
vids = {vid for vid, ports in members.items() if number in ports}
pvid, rule = vlan_ports.get(number, (1, "hybrid"))
values = dict(status.get(number, {}))
values["enabled"] = config.get(number, {}).get("enabled", values.get("enabled", True))
interfaces.append(_interface(str(number), description=config.get(number, {}).get("description", ""),
vlans=port_membership(vids, pvid, rule) if vlans_read else None,
lag=None, **values))
address, vlan = parse_ip(outputs.get("ip", ""))
ip_addresses = []
if address:
name = f"vlan{vlan}" if vlan else "System"
interfaces.append(_interface(name, connected=True, description="Management-Interface", virtual=True,
ip_addresses=[address], vlans=None, lag=None))
ip_addresses.append({"interface": name, "address": address})
neighbors = parse_neighbors(outputs.get("neighbors", ""))
by_name = {item["name"]: item for item in interfaces}
for neighbor in neighbors:
if neighbor["local_port"] in by_name:
by_name[neighbor["local_port"]]["neighbor"] = neighbor
system = outputs.get("system", "")
mac = _field(system, "Host MAC Address")
raw = {key: value for key, value in outputs.items() if key != "platform" and isinstance(value, str)}
return {
"platform": PLATFORM,
"interfaces": interfaces,
"ip_addresses": ip_addresses,
"neighbors": neighbors,
"lldp_neighbors": neighbors,
"cdp_neighbors": [],
"raw": raw,
"vlans_read": vlans_read,
# No configuration file over the CLI; the readable state serves as backup.
"config_backup": "\n\n".join(f"### {mode} → {command}\n{clean_output(outputs.get(key, '')).strip()}"
for mode, command, key in COMMANDS if outputs.get(key)),
"vlan_names": names,
"stack": [],
"lldp_disabled": not lldp_receiving(outputs.get("lldp_config", "")),
"lldp_enabled_automatically": bool(outputs.get("lldp_enabled_automatically")),
"discovered_at": time.time(),
"system": {"name": _field(system, "Device Name"), "model": _field(system, "Model Name"),
"location": _field(system, "Location"), "mac": mac,
"serial": _field(system, "Serial Number"), "firmware": _field(system, "Firmware Version")},
}
+252 -17
View File
@@ -1,5 +1,8 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import base64
import hashlib
import io
import ipaddress
import re
import threading
@@ -8,13 +11,14 @@ 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",
"aruba_cx": "Aruba CX (AOS-CX)",
"aruba_aos": "ArubaOS-Switch / ProCurve",
"hpe_comware": "HPE Comware",
"lancom_sx3": "LANCOM LCOS SX 3.x (GS-23xx)",
}
COMMANDS = {
@@ -263,6 +267,14 @@ def detect_platform(channel, banner):
return "aruba_cx"
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
return "aruba_aos"
if CLI_ERROR.search(version):
# LANCOM LCOS SX 3.x has no "show version"; its system information is in the "system" mode.
from netbox_sync.core import lancom
_run_cli_command(channel, "system")
system = _run_cli_command(channel, "show", timeout=30)
_run_cli_command(channel, "exit")
if lancom.is_lancom(system):
return lancom.PLATFORM
display = _run_cli_command(channel, "display version", timeout=30)
if re.search(r"(?i)Comware", display):
return "hpe_comware"
@@ -283,6 +295,10 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
if platform == "auto":
platform = detect_platform(channel, banner)
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}")
if platform == "lancom_sx3":
from netbox_sync.core import lancom
return dict(lancom.run_commands(channel, log, config.get("name", config["host"]), enable_lldp),
platform=platform)
pager_command, interface_command, neighbor_command = COMMANDS[platform]
_run_cli_command(channel, pager_command)
@@ -608,8 +624,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,6 +792,44 @@ 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))
@@ -824,10 +878,18 @@ def parse_stack(config, platform, interfaces=()):
def build_snapshot(outputs, platform):
if platform == "lancom_sx3":
from netbox_sync.core import lancom
return lancom.build_snapshot(outputs)
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", ""))
@@ -863,6 +925,7 @@ 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),
@@ -885,6 +948,8 @@ def suggest_platform(*texts):
text = " ".join(str(value or "") for value in texts).casefold()
if not text.strip():
return "auto"
if re.search(r"lancom|\bgs-23\d\d", text):
return "lancom_sx3"
if re.search(r"comware|h3c|\b(?:19[0-9]0|51[234]0|55[01]0|57[01]0|59[0-9]0|75\d\d|10500|12500|12900)\b", text):
return "hpe_comware"
if re.search(r"aos-?cx|arubaos-?cx|\bcx\b|\b(?:4100i|6000|6100|6200[fm]?|6300[fm]?|6400|8100|8320|8325|8360|8400|9300|10000)\b", text):
@@ -1357,7 +1422,7 @@ def plan_switch_sync(nb, config, snapshot):
"interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id,
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
"vlan_label": port_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)), item.get("lag"))}
for item in snapshot["interfaces"] if owners[item["name"]] is not None
for record, method in [matches[item["name"]]]
],
@@ -1428,7 +1493,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
@@ -1515,8 +1590,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
@@ -1524,6 +1603,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
@@ -1536,6 +1616,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
@@ -1577,7 +1658,7 @@ 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": [], "notes": [],
}
@@ -1620,7 +1701,151 @@ def _sync_switch_stack(nb, device, members, dry_run, report):
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
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.
"""
original = snapshot.get("config_file")
if original:
# Backup file from the switch's web UI (e.g. D-Link config.bin), attached unchanged.
content = base64.b64decode(original["data"])
extension = Path(original.get("name") or "config.bin").suffix or ".bin"
content_type = "application/octet-stream"
else:
config = snapshot.get("config_backup")
if not config:
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
return
content, extension, content_type = config.encode("utf-8"), ".txt", "text/plain"
digest = hashlib.sha256(f"{device.id}\n".encode("utf-8") + content).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}") + extension
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(content), content_type),
})
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
@@ -1637,7 +1862,8 @@ 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"))
members = stack_devices(nb, config, snapshot, device)
owners = _interface_owners(snapshot, members, device)
@@ -1649,7 +1875,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
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 = {}
records, foreign = {}, set()
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
@@ -1659,7 +1885,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
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 = {}
@@ -1669,7 +1896,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 = []
@@ -1694,7 +1921,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
}
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
@@ -1708,6 +1935,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:
@@ -1760,9 +1989,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)
@@ -1775,6 +2002,12 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
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
@@ -1790,6 +2023,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
remote.cable = True # avoid a second cable from the reverse direction
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
+59 -6
View File
@@ -1,6 +1,7 @@
"""Long-running operations started from the UI. Everything here runs in background tasks."""
import threading
from pathlib import Path
import time
import uuid
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.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.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
from netbox_sync.core.config import known_hosts_path
@@ -328,6 +329,50 @@ class Actions:
logger("switch").log(25, "%s", 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
# ------------------------------------------------------------------
@@ -358,7 +403,8 @@ class Actions:
on_error=self._netbox_failed)
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:
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
return
@@ -432,6 +478,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", {})
@@ -498,7 +546,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):
@@ -509,22 +558,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
+9 -2
View File
@@ -546,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)
@@ -564,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)
@@ -593,7 +600,7 @@ class SyncPreviewDialog(_Dialog):
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"))
+51 -8
View File
@@ -4,7 +4,8 @@ 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.backups import BACKUP_PLATFORMS
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
@@ -23,7 +24,8 @@ def _speed(value):
class SwitchesPage(Page):
title = "Switche"
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, HPE Comware und LANCOM LCOS SX 3.x – D-Link und Linksys "
"per Backup-Datei.")
def __init__(self, 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))
columns = [
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("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"),
@@ -81,6 +83,11 @@ class SwitchesPage(Page):
self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
tooltip="Ausleseergebnisse aus einer im Offline-Modus "
"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.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync))
@@ -93,13 +100,30 @@ 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.")
# Two rows: filters for the table, then the options of the NetBox transfer.
filters.setSpacing(12)
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)
result_card.add(filters)
options = QHBoxLayout()
options.setSpacing(16)
options.addWidget(label("Übertragen:", muted=True))
options.addWidget(self.cables_option)
options.addWidget(self.update_cables_option)
options.addWidget(self.backup_option)
options.addStretch(1)
result_card.add(options)
result_columns = [
Column("switch", "Switch", 140),
Column("name", "Schnittstelle", 150),
@@ -108,8 +132,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 +168,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 +182,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"])
@@ -253,6 +295,7 @@ class SwitchesPage(Page):
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
self.add_button.setEnabled(not busy)
self.file_button.setEnabled(not busy)
self.backup_button.setEnabled(not busy)
def set_busy(self, busy):
self._update_buttons()
+1 -1
View File
@@ -2,5 +2,5 @@ PySide6-Essentials>=6.7
pynetbox>=7.4
pyvmomi>=8.0
requests>=2.31
paramiko>=3.4
paramiko>=3.4,<4 # 4.x+ dropped ssh-rsa (SHA-1) and ssh-dss host keys used by older switches (e.g. LANCOM GS-23xx)
pywin32>=306; sys_platform == "win32"
+151
View File
@@ -0,0 +1,151 @@
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")
def test_dlink_original_file_is_attached():
import base64
from types import SimpleNamespace
from netbox_sync.core.switches import _backup_config
data = dlink_backup()
_switch, snapshot = parse_backup(data, "config.bin")
created = []
attachments = SimpleNamespace(filter=lambda **_kw: [], create=lambda payload: created.append(payload)
or SimpleNamespace())
nb = SimpleNamespace(plugins=SimpleNamespace(netbox_attachments=SimpleNamespace(netbox_attachments=attachments)))
report = {"notes": [], "errors": [], "changes": []}
_backup_config(nb, SimpleNamespace(id=1, name="SW-01"), snapshot, False, report)
filename, stream, content_type = created[0]["file"]
assert filename.endswith(".bin") and content_type == "application/octet-stream"
assert stream.read() == data == base64.b64decode(snapshot["config_file"]["data"])
+180
View File
@@ -0,0 +1,180 @@
from netbox_sync.core import lancom
from netbox_sync.core.switches import build_snapshot, netbox_interface_type, suggest_platform
SYSTEM = """
Model Name : LANCOM GS-2326P+
Location : Keller
Device Name : SW-08
Firmware Version : v3.34.0205RU4
Serial Number : 4006846720000000
Host MAC Address : 00-a0-57-00-00-01
SW-08(system)#"""
STATUS = """
Port/Media State Link Auto Nego Speed Duplex Rx Pause Tx Pause
---------- -------- -------------- --------- ------------ -------- --------
1/UTP Enabled Down Enabled Down Disabled Disabled
2/UTP Enabled Up Enabled 1G Full Disabled Disabled
3/UTP Disabled Down Enabled Down Disabled Disabled
4/UTP Enabled Up Enabled 100 Full Disabled Disabled
25/SFP Enabled Up Enabled 1G Full Disabled Disabled
SW-08(port)#"""
PORT_CONFIG = """
Port State Speed Duplex Flow Control Max. Frame Excessive Power
Description
--------------------------------------------------------------------------------
1 Enabled Auto Disabled 9600 Discard Disabled
Uplink
--------------------------------------------------------------------------------
2 Enabled Auto Disabled 9600 Discard Disabled
AP005
--------------------------------------------------------------------------------
3 Disabled Auto Disabled 9600 Discard Disabled
--------------------------------------------------------------------------------
4 Enabled Auto Disabled 9600 Discard Disabled
--------------------------------------------------------------------------------
25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled
SW-08(port)#"""
VLANS = """
VID VLAN Name User Ports
---- -------------------------------- ---------- -----------------
36 LAN Static 1-4,25
136 MOBILE Static 1-2
236 GUEST Static 1,3
SW-08(vlan)#"""
VLAN_PORTS = """
Port PVID Frame Type Ingress Filter Egress Rule Port Type
---- ---- ---------- -------------- ----------- -------------
1 1 All Disabled Trunk C-Port
2 36 All Disabled Hybrid C-Port
3 36 All Disabled Hybrid C-Port
4 36 All Disabled Access C-Port
25 1 All Disabled Hybrid C-Port
SW-08(vlan)#"""
IP = """
Configured Current
--------------- ---------------
DHCP Client : Disabled
IP Address : 10.0.0.8 10.0.0.8
IP Mask : 255.255.255.0 255.255.255.0
VLAN ID : 36 36
SW-08(ip)#"""
def outputs():
return {"system": SYSTEM, "status": STATUS, "port_config": PORT_CONFIG, "vlans": VLANS,
"vlan_ports": VLAN_PORTS, "ip": IP, "neighbors": ""}
def test_snapshot():
snapshot = build_snapshot(outputs(), "lancom_sx3")
ports = {item["name"]: item for item in snapshot["interfaces"]}
assert ports["1"]["description"] == "Uplink" and not ports["1"]["connected"]
assert ports["2"]["connected"] and ports["2"]["speed_mbps"] == 1000
assert ports["4"]["speed_mbps"] == 100
assert ports["3"]["enabled"] is False
assert ports["1"]["vlans"] == {"untagged": [], "tagged": [36, 136, 236], "tagged_all": False}
assert ports["2"]["vlans"] == {"untagged": [36], "tagged": [136], "tagged_all": False}
assert ports["4"]["vlans"]["untagged"] == [36]
assert ports["25"]["vlans"] == {"untagged": [], "tagged": [36], "tagged_all": False}
assert netbox_interface_type(ports["25"]) == "1000base-x-sfp"
assert netbox_interface_type(ports["1"]) == "1000base-t"
assert ports["vlan36"]["ip_addresses"] == ["10.0.0.8/24"]
assert snapshot["vlan_names"] == {36: "LAN", 136: "MOBILE", 236: "GUEST"}
assert snapshot["system"]["model"] == "LANCOM GS-2326P+"
assert "show port-config" in snapshot["config_backup"]
def test_detection_helpers():
assert lancom.is_lancom(SYSTEM)
assert suggest_platform("LANCOM Systems", "GS-2326P+") == "lancom_sx3"
class FakeChannel:
"""Answers like the mode-based CLI and records what was sent."""
def __init__(self):
self.sent, self.mode, self.buffer = [], "", ""
def send(self, data):
command = data.strip()
self.sent.append(command)
answers = {("system", "show"): SYSTEM, ("port", "show status"): STATUS,
("port", "show configuration"): PORT_CONFIG, ("vlan", "show vlan"): VLANS,
("vlan", "show port-config"): VLAN_PORTS, ("ip", "show"): IP}
if command == "exit":
self.mode = ""
output = ""
elif not self.mode and command in ("system", "port", "vlan", "ip", "lldp"):
self.mode = command
output = ""
else:
output = answers.get((self.mode, command), "% Unrecognized command")
self.buffer += output + f"\nSW-08{'(' + self.mode + ')' if self.mode else ''}# "
def recv_ready(self):
return bool(self.buffer)
def recv(self, _size):
data, self.buffer = self.buffer, ""
return data.encode()
def test_run_commands_switches_modes():
channel = FakeChannel()
result = lancom.run_commands(channel)
assert result["vlans"].strip().startswith("VID") and result["neighbors"] == ""
assert channel.sent[:3] == ["system", "show", "exit"]
assert channel.mode == ""
assert "show info 1-4,25" in channel.sent
LLDP_CONFIG = """
Interval : 30
Port System System System Management CDP
Port Mode Description Name Description Capability Address awareness
---- -------- ----------- -------- ----------- ----------- ---------- ---------
1 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
2 Disabled Enabled Enabled Enabled Enabled Enabled Enabled
SW-08(lldp)#"""
def test_lldp_disabled_is_reported():
snapshot = build_snapshot(dict(outputs(), lldp_config=LLDP_CONFIG, neighbors="No LLDP entries found"),
"lancom_sx3")
assert snapshot["lldp_disabled"] is True and snapshot["neighbors"] == []
enabled = LLDP_CONFIG.replace("1 Disabled", "1 Enabled ")
assert build_snapshot(dict(outputs(), lldp_config=enabled), "lancom_sx3")["lldp_disabled"] is False
def test_enable_lldp_on_disabled_ports():
channel = FakeChannel()
state = {"config": LLDP_CONFIG}
original = channel.send
def send(data):
command = data.strip()
if channel.mode == "lldp" and command == "show config":
channel.sent.append(command)
channel.buffer += state["config"] + "\nSW-08(lldp)# "
elif channel.mode == "lldp" and command.startswith("mode "):
channel.sent.append(command)
state["config"] = LLDP_CONFIG.replace("Disabled Enabled", "Enabled Enabled")
channel.buffer += "\nSW-08(lldp)# "
else:
original(data)
channel.send = send
result = lancom.run_commands(channel, enable_lldp=True, wait=0)
assert "mode 1-2 enable" in channel.sent
assert result["lldp_enabled_automatically"] is True
snapshot = build_snapshot(dict(outputs(), **result), "lancom_sx3")
assert snapshot["lldp_enabled_automatically"] and not snapshot["lldp_disabled"]
assert all(isinstance(value, str) for value in snapshot["raw"].values())
+211
View File
@@ -4,9 +4,12 @@ from fake_netbox import Endpoint, FakeNetBox, Record
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,
)
@@ -401,3 +404,211 @@ def test_virtual_chassis_positions_are_suggested():
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)"]