Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1352514577 | ||
|
|
fc503bd7d3 | ||
|
|
144e5f9eb8 | ||
|
|
823d968b33 | ||
|
|
0241509845 | ||
|
|
b89a364bf0 | ||
|
|
97ee72e610 | ||
|
|
c85df7402d | ||
|
|
5427cc015e | ||
|
|
1aa1c15aa8 | ||
|
|
51f3fc70cd | ||
|
|
411c5446fe | ||
|
|
1bd2d42b5d | ||
|
|
2092f41624 | ||
|
|
e9e1783360 | ||
|
|
576f245b7d | ||
|
|
0e04dae354 | ||
|
|
63ed535a37 |
No files matched your search
@@ -106,7 +106,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
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
|
||||
matched by MAC, and a device with a single physical port is cabled there.
|
||||
Wireless interfaces (Wi-Fi, LTE …) are never cable targets. In the review
|
||||
dialog the far-end interface can be chosen per neighbor ("automatisch" shows
|
||||
the interface that would be used); the choice is stored in the profile.
|
||||
Every skipped cable is listed as a note with its reason
|
||||
- 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
|
||||
@@ -115,12 +119,21 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
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)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.15.0"
|
||||
#define AppVersion "4.17.0"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.15.0"
|
||||
APP_VERSION = "4.17.0"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ Supported formats:
|
||||
A plain text ``SNCSR.conf`` is accepted as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
@@ -44,7 +45,10 @@ def parse_backup(data, filename=""):
|
||||
data = data.encode("utf-8")
|
||||
dump = _dlink_dump(data)
|
||||
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)
|
||||
if text is not None:
|
||||
return _linksys_snapshot(text)
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""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,
|
||||
CLI_PROMPT,
|
||||
MAC_PATTERN,
|
||||
_compress_vlans,
|
||||
_interface,
|
||||
_membership,
|
||||
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"),
|
||||
)
|
||||
|
||||
|
||||
# The CLI pages long outputs ("-- more --, next page: Space, ..., q to quit") and cannot be told not to.
|
||||
PAGER = re.compile(r"(?im)^[^\n]*(?:q to quit|-+\s*more\s*-+)[^\n]*\Z")
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
"""Run a command; this CLI executes it only on "\r" ("\n" is just echoed).
|
||||
|
||||
Paging prompts are answered with Space and removed from the output.
|
||||
"""
|
||||
channel.send(command + "\r")
|
||||
chunks, started = [], time.monotonic()
|
||||
while time.monotonic() - started < timeout:
|
||||
if channel.recv_ready():
|
||||
chunks.append(channel.recv(65535).decode("utf-8", errors="replace"))
|
||||
text = clean_output("".join(chunks))
|
||||
if PAGER.search(text):
|
||||
chunks = [PAGER.sub("", text)]
|
||||
channel.send(" ")
|
||||
started = time.monotonic() # every page gets the full timeout
|
||||
continue
|
||||
if CLI_PROMPT.search(text):
|
||||
return text
|
||||
time.sleep(0.05)
|
||||
text = clean_output("".join(chunks))
|
||||
tail = " | ".join(line.strip() for line in text.splitlines()[-3:] if line.strip())
|
||||
raise TimeoutError(f"CLI-Befehl nicht vollständig abgeschlossen: {command}. Der Switch hat die CLI-Ausgabe nicht "
|
||||
f"mit einem vollständigen Prompt abgeschlossen. Letzte Ausgabe: {tail[-300:] or '–'}")
|
||||
|
||||
|
||||
def probe(channel):
|
||||
"""``True`` when the "system" mode shows a LANCOM model; leaves the mode again."""
|
||||
_run_cli_command(channel, "system")
|
||||
system = _run_cli_command(channel, "show", timeout=30)
|
||||
_run_cli_command(channel, "exit")
|
||||
return is_lancom(system)
|
||||
|
||||
|
||||
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):
|
||||
# Only spaces/tabs around the colon: an empty value must not swallow the next line. Lines after a
|
||||
# paging prompt are indented, hence the optional leading blanks.
|
||||
match = re.search(rf"(?im)^[ \t]*{re.escape(label)}[ \t]*:[ \t]*(.*?)[ \t]*$", 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, directly followed by its (possibly empty) 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:
|
||||
text = line.strip()
|
||||
if text and not set(text) <= {"-"} and not CLI_PROMPT.search(text):
|
||||
ports[current]["description"] = text
|
||||
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.search(r"(\d+)", local) # "Port 2" → "2", the name of the switch port
|
||||
chassis = _field(block, "Chassis ID")
|
||||
name = _field(block, "System Name")
|
||||
if not name and chassis and not MAC_PATTERN.fullmatch(chassis) and not re.fullmatch(r"[\d.]+", chassis):
|
||||
name = chassis # e.g. Windows hosts send their name only as chassis ID
|
||||
neighbors.append({
|
||||
"local_port": port.group(1) if port else local,
|
||||
"system_name": 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": chassis,
|
||||
"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")},
|
||||
}
|
||||
|
||||
|
||||
def reparse(snapshot):
|
||||
"""Rebuild a stored snapshot from its raw outputs with the current parsers.
|
||||
|
||||
Exchange files keep all LANCOM outputs, so parser fixes also apply to older exports.
|
||||
"""
|
||||
raw = snapshot.get("raw") or {}
|
||||
if snapshot.get("platform") != PLATFORM or not raw.get("status"):
|
||||
return snapshot
|
||||
rebuilt = build_snapshot(dict(raw, lldp_enabled_automatically=snapshot.get("lldp_enabled_automatically")))
|
||||
rebuilt["discovered_at"] = snapshot.get("discovered_at", rebuilt["discovered_at"])
|
||||
return rebuilt
|
||||
+150
-24
@@ -1,5 +1,6 @@
|
||||
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -17,6 +18,7 @@ PLATFORMS = {
|
||||
"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 = {
|
||||
@@ -173,8 +175,9 @@ def _read_available(channel, timeout=20, initialize_session=False):
|
||||
return output
|
||||
|
||||
|
||||
def _run_cli_command(channel, command, timeout=20):
|
||||
channel.send(command + "\n")
|
||||
def _run_cli_command(channel, command, timeout=20, newline="\n"):
|
||||
# LANCOM LCOS SX 3.x only executes a command on "\r" (like PuTTY's Enter); "\n" is just echoed.
|
||||
channel.send(command + newline)
|
||||
try:
|
||||
return _read_available(channel, timeout=timeout)
|
||||
except TimeoutError as error:
|
||||
@@ -259,25 +262,80 @@ def detect_platform(channel, banner):
|
||||
"""Identify the switch OS from prompt and ``show version`` output."""
|
||||
if COMWARE_PROMPT.search(banner):
|
||||
return "hpe_comware"
|
||||
_run_cli_command(channel, "no page")
|
||||
try:
|
||||
_run_cli_command(channel, "no page")
|
||||
except TimeoutError:
|
||||
# The command was only echoed: a CLI that needs "\r" as Enter (LANCOM LCOS SX 3.x).
|
||||
from netbox_sync.core import lancom
|
||||
channel.send("\r")
|
||||
_read_available(channel, timeout=20)
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
raise
|
||||
version = _run_cli_command(channel, "show version", timeout=30)
|
||||
if re.search(r"(?i)ArubaOS-CX|AOS-CX|\b[A-Z]{2}\.10\.\d+", version):
|
||||
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
|
||||
if lancom.probe(channel):
|
||||
return lancom.PLATFORM
|
||||
display = _run_cli_command(channel, "display version", timeout=30)
|
||||
if re.search(r"(?i)Comware", display):
|
||||
return "hpe_comware"
|
||||
raise RuntimeError("Plattform konnte nicht automatisch erkannt werden – bitte im Switch-Dialog manuell wählen.")
|
||||
|
||||
|
||||
class _SessionRecorder:
|
||||
"""Channel wrapper that records everything sent and received for the raw data view."""
|
||||
|
||||
def __init__(self, channel, session):
|
||||
self._channel = channel
|
||||
self._session = session
|
||||
|
||||
def send(self, data):
|
||||
self._session.append(f"»» {data.strip()}\n" if data.strip() else "»» <Enter>\n")
|
||||
return self._channel.send(data)
|
||||
|
||||
def recv(self, size):
|
||||
data = self._channel.recv(size)
|
||||
self._session.append(data.decode("utf-8", errors="replace"))
|
||||
return data
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._channel, name)
|
||||
|
||||
|
||||
def session_text(session):
|
||||
"""The recorded CLI session without passwords, keys and communities."""
|
||||
return mask_config("".join(session))
|
||||
|
||||
|
||||
def run_switch_commands(config, enable_lldp=False, known_hosts=None, log=_noop):
|
||||
"""CLI outputs of a switch; ``outputs["session"]`` is the full recorded session.
|
||||
|
||||
On errors the session up to the failure is attached to the exception as
|
||||
``error.transcript`` so it can be shown as raw data.
|
||||
"""
|
||||
session = []
|
||||
try:
|
||||
outputs = _run_switch_commands(config, enable_lldp, known_hosts, log, session)
|
||||
except Exception as error:
|
||||
error.transcript = session_text(session)
|
||||
raise
|
||||
outputs["session"] = session_text(session)
|
||||
return outputs
|
||||
|
||||
|
||||
def _run_switch_commands(config, enable_lldp, known_hosts, log, session):
|
||||
platform = config.get("platform", "auto")
|
||||
if platform not in PLATFORMS:
|
||||
raise ValueError(f"Nicht unterstützte Switch-Plattform: {platform}")
|
||||
client = _open_client(config, known_hosts, log)
|
||||
try:
|
||||
channel = client.invoke_shell(width=240, height=1000)
|
||||
channel = _SessionRecorder(client.invoke_shell(width=240, height=1000), session)
|
||||
try:
|
||||
banner = _read_available(channel, timeout=45, initialize_session=True)
|
||||
except TimeoutError as error:
|
||||
@@ -285,6 +343,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)
|
||||
|
||||
@@ -864,6 +926,9 @@ 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)
|
||||
@@ -931,6 +996,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):
|
||||
@@ -1028,6 +1095,14 @@ def _physical_record(record):
|
||||
and not re.match(r"^(?:vlan|lo|mgmt|oobm)", interface_key(record.name)))
|
||||
|
||||
|
||||
# NetBox does not allow cables on wireless interfaces (Wi-Fi, LTE/5G, Bluetooth …).
|
||||
_WIRELESS_TYPE = re.compile(r"^(?:ieee802\.1[15]|other-wireless|gsm|cdma|lte|4g|5g)")
|
||||
|
||||
|
||||
def _cableable_record(record):
|
||||
return _physical_record(record) and not _WIRELESS_TYPE.match(_record_type(record))
|
||||
|
||||
|
||||
def _physical_interface(interface):
|
||||
return netbox_interface_type(interface) not in ("virtual", "lag")
|
||||
|
||||
@@ -1353,7 +1428,15 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
if remote and remote.id not in known and remote.id != device.id:
|
||||
devices.append({"id": remote.id, "name": remote.name})
|
||||
known.add(remote.id)
|
||||
neighbors.append(dict(neighbor, device_id=device_id, method=method))
|
||||
interfaces, suggested, chosen = [], None, None
|
||||
if remote:
|
||||
interfaces = cable_targets(nb, remote.id, lookup)
|
||||
found = lookup.interface(remote, neighbor)
|
||||
suggested = found.name if found else None
|
||||
stored = (config.get("neighbor_interfaces") or {}).get(local)
|
||||
chosen = stored if any(item["id"] == stored for item in interfaces) else None
|
||||
neighbors.append(dict(neighbor, device_id=device_id, method=method, interfaces=interfaces,
|
||||
suggested_interface=suggested, interface_id=chosen))
|
||||
# Stack members may be chosen from the same list (including the switch itself).
|
||||
for member_device in ([device, *filter(None, members.values())] if members else []):
|
||||
if member_device.id not in known:
|
||||
@@ -1456,10 +1539,13 @@ class _RemoteLookup:
|
||||
self.devices[cache_key] = found
|
||||
return found
|
||||
|
||||
def records(self, device_id):
|
||||
if device_id not in self.interfaces:
|
||||
self.interfaces[device_id] = _device_interfaces(self.nb, device_id)
|
||||
return self.interfaces[device_id]
|
||||
|
||||
def interface(self, device, neighbor):
|
||||
if device.id not in self.interfaces:
|
||||
self.interfaces[device.id] = _device_interfaces(self.nb, device.id)
|
||||
records = self.interfaces[device.id]
|
||||
records = self.records(device.id)
|
||||
candidates = [neighbor.get("remote_port"), neighbor.get("port_description")]
|
||||
if neighbor.get("port_description"):
|
||||
candidates.append(neighbor["port_description"].split()[0])
|
||||
@@ -1471,7 +1557,7 @@ class _RemoteLookup:
|
||||
number = _port_number(neighbor.get("remote_port"))
|
||||
if number is not None:
|
||||
found = [record for record in records.values()
|
||||
if _physical_record(record) and _port_number(record.name) == number]
|
||||
if _cableable_record(record) and _port_number(record.name) == number]
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
# Access points and phones often report their MAC address as port ID.
|
||||
@@ -1483,10 +1569,18 @@ class _RemoteLookup:
|
||||
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)]
|
||||
if _cableable_record(record) and not getattr(record, "mgmt_only", False)]
|
||||
return physical[0] if len(physical) == 1 else None
|
||||
|
||||
|
||||
def cable_targets(nb, device_id, lookup=None):
|
||||
"""Interfaces of a device a cable can end on, as ``[{"id", "name", "cabled"}]`` in natural order."""
|
||||
records = (lookup or _RemoteLookup(nb)).records(device_id)
|
||||
return [{"id": record.id, "name": record.name, "cabled": bool(getattr(record, "cable", None))}
|
||||
for record in sorted(records.values(), key=lambda item: _natural_key(item.name))
|
||||
if _cableable_record(record)]
|
||||
|
||||
|
||||
_NEW = "new" # placeholder ID of objects a dry run would create
|
||||
|
||||
|
||||
@@ -1730,11 +1824,19 @@ def _backup_config(nb, device, snapshot, dry_run, report):
|
||||
A new attachment is only added when the configuration of this device changed
|
||||
since the last backup; the hash in the description identifies it.
|
||||
"""
|
||||
config = snapshot.get("config_backup")
|
||||
if not config:
|
||||
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
|
||||
return
|
||||
digest = hashlib.sha256(f"{device.id}\n{config}".encode("utf-8")).hexdigest()[:16]
|
||||
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)
|
||||
@@ -1754,13 +1856,13 @@ def _backup_config(nb, device, snapshot, dry_run, report):
|
||||
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
|
||||
if dry_run:
|
||||
return
|
||||
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + ".txt"
|
||||
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(config.encode("utf-8")), "text/plain"),
|
||||
"file": (filename, io.BytesIO(content), content_type),
|
||||
})
|
||||
if hasattr(attachment, "assignments"):
|
||||
# Newer plugin versions assign attachments to objects separately.
|
||||
@@ -1955,34 +2057,58 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
if create_cables:
|
||||
lookup = _RemoteLookup(nb)
|
||||
manual_devices = config.get("neighbor_devices") or {}
|
||||
manual_interfaces = config.get("neighbor_interfaces") or {}
|
||||
for neighbor in snapshot["neighbors"]:
|
||||
label = f"{neighbor.get('local_port')} → {neighbor.get('system_name')} {neighbor.get('remote_port')}"
|
||||
name = neighbor.get("system_name") or neighbor.get("management_ip") or neighbor.get("chassis_id") or "?"
|
||||
label = f"{neighbor.get('local_port')} → {name} {neighbor.get('remote_port') or ''}".strip()
|
||||
|
||||
def skip(reason):
|
||||
report["cables_skipped"] += 1
|
||||
report["notes"].append(f"Kabel {device.name} {label} übersprungen: {reason}")
|
||||
|
||||
try:
|
||||
key = interface_key(neighbor["local_port"])
|
||||
if key not in records:
|
||||
skip(f"lokaler Port „{neighbor['local_port']}“ gehört zu keiner Schnittstelle")
|
||||
continue
|
||||
local = records[key]
|
||||
if local is None: # interface only created by this (dry) run
|
||||
if not dry_run:
|
||||
skip("lokale Schnittstelle wurde nicht angelegt")
|
||||
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)
|
||||
remote_device = nb.dcim.devices.get(chosen) if chosen else None
|
||||
if not chosen:
|
||||
report["cables_skipped"] += 1 # deliberately "no cable"
|
||||
continue
|
||||
remote_device = nb.dcim.devices.get(chosen)
|
||||
else:
|
||||
remote_device = lookup.device(neighbor)
|
||||
if not remote_device:
|
||||
report["cables_skipped"] += 1
|
||||
skip("Nachbargerät nicht in NetBox gefunden – bei Bedarf im Reiter „Nachbarn“ zuordnen")
|
||||
continue
|
||||
if remote_device.id in own_devices:
|
||||
continue
|
||||
remote = lookup.interface(remote_device, neighbor)
|
||||
# A far-end interface chosen in the review dialog wins – as long as it belongs to the device.
|
||||
chosen_interface = manual_interfaces.get(neighbor["local_port"])
|
||||
remote = next((record for record in lookup.records(remote_device.id).values()
|
||||
if chosen_interface and record.id == chosen_interface), None)
|
||||
remote = remote or 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
|
||||
skip(f"lokaler Port hat bereits ein Kabel, Schnittstelle „{neighbor.get('remote_port')}“ "
|
||||
f"auf {remote_device.name} nicht gefunden")
|
||||
continue
|
||||
if not remote or getattr(remote, "cable", None):
|
||||
report["cables_skipped"] += 1
|
||||
if not remote:
|
||||
skip(f"keine passende Schnittstelle „{neighbor.get('remote_port')}“ auf {remote_device.name} "
|
||||
"(Name, Portnummer, MAC oder einziger physischer Port)")
|
||||
continue
|
||||
if getattr(remote, "cable", None):
|
||||
skip(f"{remote_device.name} {remote.name} hat bereits ein Kabel")
|
||||
continue
|
||||
report["cables_created"] += 1
|
||||
report["changes"].append(f"Kabel {device.name} {label}")
|
||||
|
||||
@@ -9,13 +9,14 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from netbox_sync.core import backups, exchange, netbox
|
||||
from netbox_sync.core import backups, exchange, lancom, netbox
|
||||
from netbox_sync.core.client_sync import ClientSyncEngine
|
||||
from netbox_sync.core.clients import ClientScanError, expand_targets, new_row, query_ad, scan_clients
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
from netbox_sync.core.netbox import NetBoxError, related_id, related_name
|
||||
from netbox_sync.core.switches import (
|
||||
PLATFORMS,
|
||||
cable_targets,
|
||||
describe_snapshot,
|
||||
discover_switch,
|
||||
plan_switch_sync,
|
||||
@@ -320,6 +321,7 @@ class Actions:
|
||||
return
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, data["switches"], lambda: uuid.uuid4().hex)
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
snapshot = lancom.reparse(snapshot)
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Datei · " + describe_snapshot(snapshot))
|
||||
if added:
|
||||
@@ -413,7 +415,7 @@ class Actions:
|
||||
known_hosts = known_hosts_path()
|
||||
|
||||
def work(ctx):
|
||||
snapshots, failures = {}, {}
|
||||
snapshots, failures, transcripts = {}, {}, {}
|
||||
ctx.progress(0, len(switches), "Verbinde …")
|
||||
with ThreadPoolExecutor(max_workers=min(parallel, len(switches))) as pool:
|
||||
futures = {}
|
||||
@@ -441,15 +443,22 @@ class Actions:
|
||||
"Stack-Mitglieder werden über den Stack-Master ausgelesen und können aus "
|
||||
"dem Profil entfernt werden.")
|
||||
failures[switch["id"]] = problem
|
||||
if getattr(error, "transcript", ""):
|
||||
transcripts[switch["id"]] = error.transcript
|
||||
ctx.log(f"{switch['name']}: {problem}", "error")
|
||||
ctx.progress(done, len(switches), switch["name"])
|
||||
if ctx.cancelled:
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
return snapshots, failures
|
||||
return snapshots, failures, transcripts
|
||||
|
||||
def success(result):
|
||||
snapshots, failures = result
|
||||
snapshots, failures, transcripts = result
|
||||
for switch_id in snapshots:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
for switch_id in failures:
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.update(transcripts)
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
platform_updates = 0
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
@@ -517,7 +526,8 @@ class Actions:
|
||||
# Started after the planning task has finished, so the next
|
||||
# task is not rejected as "still busy".
|
||||
if needs_review:
|
||||
dialog = SwitchMappingDialog(self.window, reviewable, create_cables)
|
||||
dialog = SwitchMappingDialog(self.window, reviewable, create_cables,
|
||||
interface_loader=lambda device_id: cable_targets(nb, device_id))
|
||||
if not dialog.exec():
|
||||
return
|
||||
stored = {switch["id"]: switch for switch in self.state.switches}
|
||||
|
||||
+88
-25
@@ -619,7 +619,10 @@ class SwitchMappingDialog(_Dialog):
|
||||
|
||||
NEW = "\x00new"
|
||||
|
||||
def __init__(self, parent, plans, create_cables):
|
||||
def __init__(self, parent, plans, create_cables, interface_loader=None):
|
||||
# interface_loader(device_id) → cable targets of another chosen neighbor device.
|
||||
self.interface_loader = interface_loader
|
||||
self._far_end_cache = {}
|
||||
super().__init__(parent, "Zuordnung prüfen",
|
||||
"Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
|
||||
"erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
|
||||
@@ -716,9 +719,9 @@ class SwitchMappingDialog(_Dialog):
|
||||
"Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: "
|
||||
f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ "
|
||||
"überspringt den Nachbarn.", muted=True, wrap=True))
|
||||
self.neighbor_table = QTableWidget(0, 5)
|
||||
self.neighbor_table = QTableWidget(0, 6)
|
||||
self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)",
|
||||
"Nachbar-Port", "NetBox-Gerät"])
|
||||
"Nachbar-Port", "NetBox-Gerät", "Nachbar-Schnittstelle"])
|
||||
for switch, plan in plans:
|
||||
for neighbor in plan["neighbors"]:
|
||||
row = self.neighbor_table.rowCount()
|
||||
@@ -727,14 +730,22 @@ class SwitchMappingDialog(_Dialog):
|
||||
combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]],
|
||||
neighbor.get("device_id") or 0)
|
||||
texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or
|
||||
neighbor.get("management_ip") or "", neighbor.get("remote_port") or "")
|
||||
neighbor.get("management_ip") or neighbor.get("chassis_id") or "",
|
||||
neighbor.get("remote_port") or "")
|
||||
for column, text in enumerate(texts):
|
||||
self.neighbor_table.setItem(row, column, QTableWidgetItem(text))
|
||||
self.neighbor_table.setCellWidget(row, 4, combo)
|
||||
self.neighbor_rows.append((switch, neighbor, combo))
|
||||
self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260))
|
||||
port_combo = SearchableComboBox("Schnittstelle suchen …")
|
||||
self._fill_far_ends(port_combo, neighbor.get("interfaces") or [],
|
||||
neighbor.get("suggested_interface"), neighbor.get("interface_id"))
|
||||
self.neighbor_table.setCellWidget(row, 5, port_combo)
|
||||
combo.currentIndexChanged.connect(
|
||||
lambda _index, device_combo=combo, target=port_combo, item=neighbor:
|
||||
self._device_changed(device_combo, target, item))
|
||||
self.neighbor_rows.append((switch, neighbor, combo, port_combo))
|
||||
self._prepare_table(self.neighbor_table, (130, 95, 200, 140, 220, 220))
|
||||
neighbor_layout.addWidget(self.neighbor_table, 1)
|
||||
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
|
||||
found = sum(1 for _switch, neighbor, *_combos in self.neighbor_rows if neighbor.get("device_id"))
|
||||
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
|
||||
|
||||
# Networks --------------------------------------------------------------
|
||||
@@ -959,13 +970,43 @@ class SwitchMappingDialog(_Dialog):
|
||||
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
|
||||
status.setForeground(QColor(theme.color("warning")))
|
||||
|
||||
@staticmethod
|
||||
def _fill_far_ends(combo, interfaces, suggested=None, current=None, evaluated=True):
|
||||
""""automatic" (with the interface it would pick) plus the cable targets of the device.
|
||||
|
||||
``evaluated`` is False for a device chosen in the dialog: its automatic match is only known at sync time.
|
||||
"""
|
||||
automatic = f"automatisch ({suggested})" if suggested else (
|
||||
"automatisch – keine passende gefunden" if interfaces and evaluated else "automatisch")
|
||||
items = [(automatic, 0)] + [(item["name"] + (" (hat Kabel)" if item.get("cabled") else ""), item["id"])
|
||||
for item in interfaces]
|
||||
combo.set_items(items, current or 0)
|
||||
combo.setEnabled(bool(interfaces) or bool(suggested))
|
||||
|
||||
def _device_changed(self, device_combo, target, neighbor):
|
||||
device_id = int(device_combo.valid_data() or 0)
|
||||
if not device_id:
|
||||
self._fill_far_ends(target, [])
|
||||
return
|
||||
if device_id == (neighbor.get("device_id") or 0):
|
||||
self._fill_far_ends(target, neighbor.get("interfaces") or [], neighbor.get("suggested_interface"),
|
||||
neighbor.get("interface_id"))
|
||||
return
|
||||
if device_id not in self._far_end_cache:
|
||||
try:
|
||||
self._far_end_cache[device_id] = self.interface_loader(device_id) if self.interface_loader else []
|
||||
except Exception: # noqa: BLE001 – the choice stays "automatic"
|
||||
self._far_end_cache[device_id] = []
|
||||
self._fill_far_ends(target, self._far_end_cache[device_id], evaluated=False)
|
||||
|
||||
def _filter_interfaces(self, only_unclear):
|
||||
for row, _switch, item, _combo in self.interface_rows:
|
||||
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
|
||||
|
||||
def accept(self):
|
||||
result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}),
|
||||
"neighbor_devices": dict(switch.get("neighbor_devices") or {})}
|
||||
"neighbor_devices": dict(switch.get("neighbor_devices") or {}),
|
||||
"neighbor_interfaces": dict(switch.get("neighbor_interfaces") or {})}
|
||||
for switch, _plan in self.plans}
|
||||
# Members moved to another device: their port choices refer to the old
|
||||
# device and are dropped, so the ports are matched again automatically.
|
||||
@@ -996,7 +1037,7 @@ class SwitchMappingDialog(_Dialog):
|
||||
mapping.pop(item["name"], None)
|
||||
else:
|
||||
mapping[item["name"]] = target
|
||||
for switch, neighbor, combo in self.neighbor_rows:
|
||||
for switch, neighbor, combo, port_combo in self.neighbor_rows:
|
||||
chosen = combo.valid_data()
|
||||
chosen = int(chosen or 0)
|
||||
stored = result[switch["id"]]["neighbor_devices"]
|
||||
@@ -1004,6 +1045,13 @@ class SwitchMappingDialog(_Dialog):
|
||||
stored.pop(neighbor["local_port"], None)
|
||||
else:
|
||||
stored[neighbor["local_port"]] = chosen
|
||||
# 0 = automatic (name, port number, MAC or single port); otherwise the chosen NetBox interface.
|
||||
interface_id = int(port_combo.valid_data() or 0) if chosen else 0
|
||||
interfaces = result[switch["id"]]["neighbor_interfaces"]
|
||||
if interface_id:
|
||||
interfaces[neighbor["local_port"]] = interface_id
|
||||
else:
|
||||
interfaces.pop(neighbor["local_port"], None)
|
||||
network_map = dict(self.previous_network_map)
|
||||
for item, combo, status in self.network_rows:
|
||||
chosen = combo.currentData()
|
||||
@@ -1038,17 +1086,22 @@ class RawDataDialog(_Dialog):
|
||||
SECTIONS = {
|
||||
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
|
||||
"neighbors": "LLDP", "cdp_neighbors": "CDP", "vlan_config": "VLAN-Konfiguration", "lldp_status": "LLDP-Status",
|
||||
# LANCOM LCOS SX 3.x
|
||||
"system": "System", "status": "Port-Status", "port_config": "Port-Konfiguration", "vlans": "VLANs",
|
||||
"vlan_ports": "VLAN-Ports", "ip": "IP", "lldp_config": "LLDP-Konfiguration",
|
||||
"session": "Sitzung",
|
||||
}
|
||||
|
||||
def __init__(self, parent, items, selected_id=None):
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche.",
|
||||
width=900)
|
||||
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche. "
|
||||
"„Sitzung“ zeigt den kompletten Ablauf, bei Fehlern bis zum Abbruch.", width=900)
|
||||
self.resize(1040, 700)
|
||||
self.items = items
|
||||
top = QHBoxLayout()
|
||||
self.switch_combo = QComboBox()
|
||||
for switch, _snapshot in items:
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']})", switch["id"])
|
||||
for switch, snapshot in items:
|
||||
suffix = " – abgebrochen" if snapshot.get("failed") else ""
|
||||
self.switch_combo.addItem(f"{switch['name']} ({switch['host']}){suffix}", switch["id"])
|
||||
if selected_id:
|
||||
self.switch_combo.setCurrentIndex(max(0, self.switch_combo.findData(selected_id)))
|
||||
top.addWidget(self.switch_combo, 1)
|
||||
@@ -1056,14 +1109,6 @@ class RawDataDialog(_Dialog):
|
||||
top.addWidget(button("Alles speichern …", "download", on_click=self.save_all))
|
||||
self.root.addLayout(top)
|
||||
self.tabs = QTabWidget()
|
||||
self.editors = {}
|
||||
for key, title in self.SECTIONS.items():
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
self.tabs.addTab(editor, title)
|
||||
self.editors[key] = editor
|
||||
self.root.addWidget(self.tabs, 1)
|
||||
close = button("Schließen", variant="primary", on_click=self.accept)
|
||||
self.root.addWidget(close, 0, Qt.AlignRight)
|
||||
@@ -1073,15 +1118,32 @@ class RawDataDialog(_Dialog):
|
||||
def _current(self):
|
||||
return self.items[max(0, self.switch_combo.currentIndex())]
|
||||
|
||||
@classmethod
|
||||
def _sections(cls, raw):
|
||||
"""Known outputs in a fixed order, unknown ones after them, the session last."""
|
||||
keys = [key for key in cls.SECTIONS if key != "session" and key in raw]
|
||||
keys += sorted(key for key in raw if key not in cls.SECTIONS and isinstance(raw[key], str))
|
||||
keys += ["session"] if "session" in raw else []
|
||||
return [(key, cls.SECTIONS.get(key, key)) for key in keys] or [("", "Rohdaten")]
|
||||
|
||||
def show_switch(self, *_args):
|
||||
_switch, snapshot = self._current()
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, editor in self.editors.items():
|
||||
self.tabs.clear()
|
||||
for key, title in self._sections(raw):
|
||||
editor = QPlainTextEdit()
|
||||
editor.setObjectName("LogView")
|
||||
editor.setReadOnly(True)
|
||||
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
|
||||
editor.setPlainText(str(raw.get(key) or "(keine Ausgabe)"))
|
||||
self.tabs.addTab(editor, title)
|
||||
if snapshot.get("failed"):
|
||||
self.tabs.setCurrentIndex(self.tabs.count() - 1)
|
||||
|
||||
def copy_current(self):
|
||||
editor = self.tabs.currentWidget()
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
if editor is not None:
|
||||
QGuiApplication.clipboard().setText(editor.toPlainText())
|
||||
|
||||
def save_all(self):
|
||||
path, _filter = QFileDialog.getSaveFileName(self, "SSH-Rohdaten speichern", "ssh-rohdaten.txt", "Text (*.txt)")
|
||||
@@ -1089,9 +1151,10 @@ class RawDataDialog(_Dialog):
|
||||
return
|
||||
sections = []
|
||||
for switch, snapshot in self.items:
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}) {'=' * 20}")
|
||||
suffix = " (abgebrochen)" if snapshot.get("failed") else ""
|
||||
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}){suffix} {'=' * 20}")
|
||||
raw = snapshot.get("raw", {})
|
||||
for key, title in self.SECTIONS.items():
|
||||
for key, title in self._sections(raw):
|
||||
sections.extend((f"\n--- {title.upper()} ---", str(raw.get(key) or "(keine Ausgabe)")))
|
||||
with open(path, "w", encoding="utf-8") as stream:
|
||||
stream.write("\n".join(sections))
|
||||
@@ -24,7 +24,7 @@ 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 – 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.")
|
||||
|
||||
def __init__(self, window):
|
||||
@@ -109,15 +109,21 @@ class SwitchesPage(Page):
|
||||
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)
|
||||
filters.addWidget(self.update_cables_option)
|
||||
filters.addWidget(self.backup_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),
|
||||
@@ -284,7 +290,8 @@ class SwitchesPage(Page):
|
||||
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data
|
||||
else "Nach NetBox übertragen …")
|
||||
self.cables_option.setVisible(not offline)
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots or self.state.switch_failed_raw),
|
||||
"Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
|
||||
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
|
||||
self.add_button.setEnabled(not busy)
|
||||
@@ -343,6 +350,7 @@ class SwitchesPage(Page):
|
||||
if dialog.result.get("device_id") != current.get("device_id"):
|
||||
self.state.switch_snapshots.pop(current["id"], None)
|
||||
self.state.switch_status.pop(current["id"], None)
|
||||
self.state.switch_failed_raw.pop(current["id"], None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -360,6 +368,7 @@ class SwitchesPage(Page):
|
||||
for switch_id in ids:
|
||||
self.state.switch_snapshots.pop(switch_id, None)
|
||||
self.state.switch_status.pop(switch_id, None)
|
||||
self.state.switch_failed_raw.pop(switch_id, None)
|
||||
self.state.touch()
|
||||
self.refresh()
|
||||
|
||||
@@ -389,7 +398,11 @@ class SwitchesPage(Page):
|
||||
|
||||
def show_raw(self):
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in self.state.switch_snapshots.items() if key in by_id]
|
||||
raw = dict(self.state.switch_snapshots)
|
||||
# A failed discovery is newer than an older result: show its session up to the error.
|
||||
for key, transcript in self.state.switch_failed_raw.items():
|
||||
raw[key] = {"raw": {"session": transcript}, "failed": True}
|
||||
items = [(by_id[key], snapshot) for key, snapshot in raw.items() if key in by_id]
|
||||
if not items:
|
||||
return
|
||||
selected = self._selected()
|
||||
@@ -402,7 +415,8 @@ class SwitchesPage(Page):
|
||||
menu = QMenu(self)
|
||||
menu.addAction(icon("play", muted), "Auslesen", self.discover)
|
||||
menu.addAction(icon("pencil", muted), "Bearbeiten …", self.edit_switch)
|
||||
if any(switch["id"] in self.state.switch_snapshots for switch in self._selected()):
|
||||
if any(switch["id"] in self.state.switch_snapshots or switch["id"] in self.state.switch_failed_raw
|
||||
for switch in self._selected()):
|
||||
menu.addAction(icon("terminal", muted), "SSH-Rohdaten …", self.show_raw)
|
||||
menu.addSeparator()
|
||||
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_switches)
|
||||
|
||||
@@ -48,6 +48,8 @@ class AppState(QObject):
|
||||
self.netbox_devices = None
|
||||
self.switch_snapshots = {}
|
||||
self.switch_status = {}
|
||||
# CLI session of failed discoveries (switch id → masked text) for the raw data view.
|
||||
self.switch_failed_raw = {}
|
||||
self.clients = []
|
||||
self.clients_loaded_at = None
|
||||
self.client_engine = None
|
||||
|
||||
+1
-1
@@ -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"
|
||||
@@ -130,3 +130,22 @@ def test_linksys_plain_text():
|
||||
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"])
|
||||
@@ -0,0 +1,341 @@
|
||||
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):
|
||||
if not data.endswith("\r"):
|
||||
self.buffer += data # like the real CLI: "\n" is only echoed, nothing is executed
|
||||
return
|
||||
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())
|
||||
|
||||
|
||||
def test_auto_detection_falls_back_to_carriage_return(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
|
||||
def quick(channel, timeout=20, initialize_session=False):
|
||||
return real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session)
|
||||
|
||||
monkeypatch.setattr(switches, "_read_available", quick)
|
||||
channel = FakeChannel()
|
||||
assert switches.detect_platform(channel, "SW-08# ") == "lancom_sx3"
|
||||
assert channel.mode == ""
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, channel):
|
||||
self.channel = channel
|
||||
|
||||
def invoke_shell(self, **_kwargs):
|
||||
return self.channel
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _quick_reads(monkeypatch):
|
||||
from netbox_sync.core import switches
|
||||
|
||||
real = switches._read_available
|
||||
monkeypatch.setattr(switches, "_read_available", lambda channel, timeout=20, initialize_session=False:
|
||||
real(channel, timeout=min(timeout, 0.3), initialize_session=initialize_session))
|
||||
command = lancom._run_cli_command
|
||||
monkeypatch.setattr(lancom, "_run_cli_command", lambda channel, text, timeout=20:
|
||||
command(channel, text, timeout=min(timeout, 0.3)))
|
||||
return switches
|
||||
|
||||
|
||||
def test_session_is_recorded(monkeypatch):
|
||||
switches = _quick_reads(monkeypatch)
|
||||
channel = FakeChannel()
|
||||
channel.buffer = "snmp community secret123\nSW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
outputs = switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "»» system" in outputs["session"] and "Model Name" in outputs["session"]
|
||||
assert "secret123" not in outputs["session"]
|
||||
assert "Sitzung" not in outputs # only raw outputs, no UI titles
|
||||
assert build_snapshot(outputs, "lancom_sx3")["raw"]["session"] == outputs["session"]
|
||||
|
||||
|
||||
def test_session_is_attached_to_errors(monkeypatch):
|
||||
import pytest
|
||||
|
||||
switches = _quick_reads(monkeypatch)
|
||||
|
||||
class Silent(FakeChannel):
|
||||
def send(self, data):
|
||||
self.sent.append(data.strip()) # never answers with a prompt
|
||||
|
||||
channel = Silent()
|
||||
channel.buffer = "SW-08# "
|
||||
monkeypatch.setattr(switches, "_open_client", lambda *_args: FakeClient(channel))
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
switches.run_switch_commands({"host": "x", "platform": "lancom_sx3"})
|
||||
assert "SW-08#" in caught.value.transcript and "»» system" in caught.value.transcript
|
||||
|
||||
|
||||
def test_paging_is_answered_with_space():
|
||||
class Paging(FakeChannel):
|
||||
def send(self, data):
|
||||
if data == " ":
|
||||
self.sent.append("<space>")
|
||||
self.buffer += "\r \rFlash Size : 32\nSW-08(system)# "
|
||||
elif data.strip() == "show" and self.mode == "system":
|
||||
self.sent.append("show")
|
||||
self.buffer += "show\nModel Name : LANCOM GS-2326P+\nRAM Size : 128\n -- more --, next page: Space, q to quit"
|
||||
else:
|
||||
super().send(data)
|
||||
|
||||
channel = Paging()
|
||||
channel.mode = "system"
|
||||
output = lancom._run_cli_command(channel, "show", timeout=2)
|
||||
assert channel.sent == ["show", "<space>"]
|
||||
assert "RAM Size : 128" in output and "Flash Size : 32" in output
|
||||
assert "quit" not in output and "more" not in output
|
||||
|
||||
|
||||
def test_neighbor_on_named_local_port():
|
||||
neighbors = """
|
||||
Local Port : Port 2
|
||||
Chassis ID : 00-a0-57-11-22-33
|
||||
Port ID : LAN1
|
||||
System Name : AP-005
|
||||
Management Address : 10.0.0.50 (IPv4)
|
||||
SW-08(lldp)#"""
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
port = next(item for item in snapshot["interfaces"] if item["name"] == "2")
|
||||
assert port["neighbor"]["local_port"] == "2"
|
||||
assert port["neighbor"]["system_name"] == "AP-005" and port["neighbor"]["remote_port"] == "LAN1"
|
||||
assert port["neighbor"]["management_ip"] == "10.0.0.50"
|
||||
|
||||
|
||||
def test_reparse_fixes_older_exports():
|
||||
neighbors = "Local Port : Port 2\nPort ID : LAN1\nSystem Name : AP-005\nSW-08(lldp)#"
|
||||
snapshot = build_snapshot(dict(outputs(), neighbors=neighbors), "lancom_sx3")
|
||||
snapshot["neighbors"][0]["local_port"] = "Port 2" # as written by 4.16.3
|
||||
for item in snapshot["interfaces"]:
|
||||
item["neighbor"] = None
|
||||
snapshot["discovered_at"] = 123
|
||||
rebuilt = lancom.reparse(snapshot)
|
||||
assert rebuilt["discovered_at"] == 123
|
||||
assert next(item for item in rebuilt["interfaces"] if item["name"] == "2")["neighbor"]["system_name"] == "AP-005"
|
||||
assert lancom.reparse({"platform": "aruba_cx", "raw": {}}) == {"platform": "aruba_cx", "raw": {}}
|
||||
|
||||
|
||||
# Real "show info" layout: lower-case "Local port", empty values and lines indented after a paging prompt.
|
||||
REAL_NEIGHBORS = """show info 1-26
|
||||
Local port : Port 2
|
||||
Chassis ID : 00-A0-57-00-00-01
|
||||
Port ID : LAN1
|
||||
Port Description : LAN1
|
||||
System Name : AP-005
|
||||
Management Address : 10.0.0.22 (IPv4)
|
||||
Management Address : fe80::1 (IPv6)
|
||||
|
||||
Local port : Port 12
|
||||
Chassis ID : PC-020
|
||||
Port ID : C4-EF-BB-00-00-01
|
||||
Port Description :
|
||||
System Name :
|
||||
System Description :
|
||||
|
||||
Local port : Port 25
|
||||
Chassis ID : MikroTik
|
||||
Port ID : bridge/ether1
|
||||
Port Description :
|
||||
System Name :
|
||||
System Description : 6.49.17 (stable) MikroTik
|
||||
Management Address : 192.168.88.3 (IPv4)
|
||||
|
||||
SW-08(lldp)# """
|
||||
|
||||
|
||||
def test_real_neighbor_layout():
|
||||
neighbors = lancom.parse_neighbors(REAL_NEIGHBORS)
|
||||
assert [(item["local_port"], item["system_name"], item["remote_port"]) for item in neighbors] == [
|
||||
("2", "AP-005", "LAN1"), ("12", "PC-020", "C4-EF-BB-00-00-01"), ("25", "MikroTik", "bridge/ether1")]
|
||||
assert neighbors[0]["management_ip"] == "10.0.0.22" and neighbors[1]["port_description"] == ""
|
||||
|
||||
|
||||
def test_prompt_is_no_port_description():
|
||||
config = PORT_CONFIG.replace("25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n\n",
|
||||
"25 Enabled SFP_Auto_AMS Disabled 9600 Discard Disabled\n")
|
||||
ports = lancom.parse_port_config(config.replace("\nSW-08(port)#", "\n\nSW-08(port)#"))
|
||||
assert ports[25]["description"] == "" and ports[1]["description"] == "Uplink"
|
||||
ports = lancom.parse_port_config("26 Enabled Auto Disabled 9600 Discard Disabled\n\n\nSW-08(port)# ")
|
||||
assert ports[26]["description"] == ""
|
||||
@@ -612,3 +612,70 @@ def test_vlans_of_another_site_are_only_labelled():
|
||||
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)"]
|
||||
|
||||
|
||||
def test_skipped_cables_are_explained():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0
|
||||
assert any("nicht in NetBox gefunden" in note for note in report["notes"])
|
||||
switch["neighbor_devices"] = {"1/1/2": 0} # "no cable" is chosen deliberately: no note
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert not any("übersprungen" in note for note in report["notes"])
|
||||
|
||||
|
||||
def test_wireless_interfaces_are_no_cable_targets():
|
||||
"""LANCOM LW-600: eth1 plus wlan0/wlan1; LLDP reports "LAN1" – wlan1 must not make it ambiguous."""
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records += [
|
||||
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=51, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=52, name="wlan1", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
|
||||
]
|
||||
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="LAN1", port_description="LAN1")
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert report["errors"] == []
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||
|
||||
|
||||
def _ap_with_two_ports():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7)))
|
||||
nb.dcim.interfaces.records += [
|
||||
Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=51, name="eth2", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||
Record(nb.dcim.interfaces, id=52, name="wlan0", device=SimpleNamespace(id=5), mac_address=None,
|
||||
type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None),
|
||||
]
|
||||
snapshot["neighbors"][0].update(system_name="AP-005", remote_port="Uplink", port_description="")
|
||||
return nb, switch, snapshot
|
||||
|
||||
|
||||
def test_far_end_interface_can_be_chosen():
|
||||
nb, switch, snapshot = _ap_with_two_ports()
|
||||
plan = plan_switch_sync(nb, switch, snapshot)
|
||||
neighbor = plan["neighbors"][0]
|
||||
assert [item["name"] for item in neighbor["interfaces"]] == ["eth1", "eth2"] # no Wi-Fi
|
||||
assert neighbor["suggested_interface"] is None and neighbor["interface_id"] is None
|
||||
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0 and any("keine passende Schnittstelle" in n for n in report["notes"])
|
||||
|
||||
switch["neighbor_interfaces"] = {"1/1/2": 51}
|
||||
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] == 51
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 51}]
|
||||
|
||||
|
||||
def test_chosen_interface_of_another_device_is_ignored():
|
||||
nb, switch, snapshot = _ap_with_two_ports()
|
||||
switch["neighbor_interfaces"] = {"1/1/2": 20} # belongs to server-01, not AP-005
|
||||
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0
|
||||
Reference in new issue
Block a user