Compare commits

..
6 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
10 changed files with 530 additions and 16 deletions

No files matched your search

+9
View File
@@ -115,12 +115,21 @@ 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
- 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 - One-off import without SSH ("Backup importieren …"): configuration backups
of D-Link DGS-1210 (`config.bin`) and Linksys LGS (`*.cfg` or the contained of D-Link DGS-1210 (`config.bin`) and Linksys LGS (`*.cfg` or the contained
`SNCSR.conf`) switches are read offline. Hostname, location, management IP, `SNCSR.conf`) switches are read offline. Hostname, location, management IP,
port descriptions, admin state, untagged/tagged VLANs and VLAN names are 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 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) 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) ### 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.15.0" #define AppVersion "4.16.1"
#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.15.0" APP_VERSION = "4.16.1"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+5 -1
View File
@@ -14,6 +14,7 @@ Supported formats:
A plain text ``SNCSR.conf`` is accepted as well. A plain text ``SNCSR.conf`` is accepted as well.
""" """
import base64
import io import io
import ipaddress import ipaddress
import re import re
@@ -44,7 +45,10 @@ def parse_backup(data, filename=""):
data = data.encode("utf-8") data = data.encode("utf-8")
dump = _dlink_dump(data) dump = _dlink_dump(data)
if dump is not None: if dump is not None:
return _dlink_snapshot(dump, data) 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) text = _linksys_text(data)
if text is not None: if text is not None:
return _linksys_snapshot(text) return _linksys_snapshot(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")},
}
+34 -7
View File
@@ -1,5 +1,6 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches.""" """SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import base64
import hashlib import hashlib
import io import io
import ipaddress import ipaddress
@@ -17,6 +18,7 @@ PLATFORMS = {
"aruba_cx": "Aruba CX (AOS-CX)", "aruba_cx": "Aruba CX (AOS-CX)",
"aruba_aos": "ArubaOS-Switch / ProCurve", "aruba_aos": "ArubaOS-Switch / ProCurve",
"hpe_comware": "HPE Comware", "hpe_comware": "HPE Comware",
"lancom_sx3": "LANCOM LCOS SX 3.x (GS-23xx)",
} }
COMMANDS = { COMMANDS = {
@@ -265,6 +267,14 @@ def detect_platform(channel, banner):
return "aruba_cx" return "aruba_cx"
if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version): if re.search(r"(?i)Image stamp|ProCurve|\b[A-Z]{1,2}\.1[456]\.\d+", version):
return "aruba_aos" 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) display = _run_cli_command(channel, "display version", timeout=30)
if re.search(r"(?i)Comware", display): if re.search(r"(?i)Comware", display):
return "hpe_comware" return "hpe_comware"
@@ -285,6 +295,10 @@ def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
if platform == "auto": if platform == "auto":
platform = detect_platform(channel, banner) platform = detect_platform(channel, banner)
log(f"{config.get('name', config['host'])}: Plattform erkannt – {PLATFORMS[platform]}") 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] pager_command, interface_command, neighbor_command = COMMANDS[platform]
_run_cli_command(channel, pager_command) _run_cli_command(channel, pager_command)
@@ -864,6 +878,9 @@ def parse_stack(config, platform, interfaces=()):
def build_snapshot(outputs, platform): 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) interfaces = parse_interfaces(outputs["interfaces"], platform)
vlans = parse_vlans(outputs.get("config", ""), platform) vlans = parse_vlans(outputs.get("config", ""), platform)
lags = parse_lags(outputs.get("config", ""), platform) lags = parse_lags(outputs.get("config", ""), platform)
@@ -931,6 +948,8 @@ def suggest_platform(*texts):
text = " ".join(str(value or "") for value in texts).casefold() text = " ".join(str(value or "") for value in texts).casefold()
if not text.strip(): if not text.strip():
return "auto" 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): 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" 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): 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):
@@ -1730,11 +1749,19 @@ def _backup_config(nb, device, snapshot, dry_run, report):
A new attachment is only added when the configuration of this device changed A new attachment is only added when the configuration of this device changed
since the last backup; the hash in the description identifies it. since the last backup; the hash in the description identifies it.
""" """
config = snapshot.get("config_backup") original = snapshot.get("config_file")
if not config: if original:
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen") # Backup file from the switch's web UI (e.g. D-Link config.bin), attached unchanged.
return content = base64.b64decode(original["data"])
digest = hashlib.sha256(f"{device.id}\n{config}".encode("utf-8")).hexdigest()[:16] 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: try:
app = nb.plugins.netbox_attachments app = nb.plugins.netbox_attachments
known = [item for item in app.netbox_attachments.filter(q=digest) known = [item for item in app.netbox_attachments.filter(q=digest)
@@ -1754,13 +1781,13 @@ def _backup_config(nb, device, snapshot, dry_run, report):
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“") report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
if dry_run: if dry_run:
return return
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + ".txt" filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + extension
try: try:
attachment = app.netbox_attachments.create({ attachment = app.netbox_attachments.create({
"name": name, "description": f"Running-Config, SHA-256 {digest}", "name": name, "description": f"Running-Config, SHA-256 {digest}",
# Older plugin versions keep the parent on the attachment itself. # Older plugin versions keep the parent on the attachment itself.
"object_type": "dcim.device", "object_id": device.id, "object_type": "dcim.device", "object_id": device.id,
"file": (filename, io.BytesIO(config.encode("utf-8")), "text/plain"), "file": (filename, io.BytesIO(content), content_type),
}) })
if hasattr(attachment, "assignments"): if hasattr(attachment, "assignments"):
# Newer plugin versions assign attachments to objects separately. # Newer plugin versions assign attachments to objects separately.
+11 -5
View File
@@ -24,7 +24,7 @@ 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 – D-Link und Linksys " "dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware und LANCOM LCOS SX 3.x – D-Link und Linksys "
"per Backup-Datei.") "per Backup-Datei.")
def __init__(self, window): def __init__(self, window):
@@ -109,15 +109,21 @@ class SwitchesPage(Page):
tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät " tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät "
"(Plugin netbox-attachments). Passwörter, Schlüssel und Communities " "(Plugin netbox-attachments). Passwörter, Schlüssel und Communities "
"werden entfernt; ein neuer Anhang entsteht nur bei Änderungen.") "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.search, 2)
filters.addWidget(self.switch_filter, 1) filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up) filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors) filters.addWidget(self.only_neighbors)
filters.addStretch(1)
filters.addWidget(self.cables_option)
filters.addWidget(self.update_cables_option)
filters.addWidget(self.backup_option)
result_card.add(filters) 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 = [ result_columns = [
Column("switch", "Switch", 140), Column("switch", "Switch", 140),
Column("name", "Schnittstelle", 150), Column("name", "Schnittstelle", 150),
+1 -1
View File
@@ -2,5 +2,5 @@ PySide6-Essentials>=6.7
pynetbox>=7.4 pynetbox>=7.4
pyvmomi>=8.0 pyvmomi>=8.0
requests>=2.31 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" pywin32>=306; sys_platform == "win32"
+19
View File
@@ -130,3 +130,22 @@ def test_linksys_plain_text():
def test_unknown_file(): def test_unknown_file():
with pytest.raises(BackupError): with pytest.raises(BackupError):
parse_backup(b"hello world", "x.bin") 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())