Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
823d968b33 | ||
|
|
0241509845 | ||
|
|
b89a364bf0 | ||
|
|
97ee72e610 | ||
|
|
c85df7402d | ||
|
|
5427cc015e |
No files matched your search
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.16.2"
|
||||
#define AppVersion "4.16.5"
|
||||
#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.16.2"
|
||||
APP_VERSION = "4.16.5"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
+57
-13
@@ -11,10 +11,11 @@ import time
|
||||
|
||||
from netbox_sync.core.switches import (
|
||||
CLI_ERROR,
|
||||
_interface,
|
||||
CLI_PROMPT,
|
||||
MAC_PATTERN,
|
||||
_compress_vlans,
|
||||
_interface,
|
||||
_membership,
|
||||
_run_cli_command as _run_with_newline,
|
||||
clean_output,
|
||||
parse_vlan_list,
|
||||
)
|
||||
@@ -35,9 +36,33 @@ COMMANDS = (
|
||||
)
|
||||
|
||||
|
||||
# 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):
|
||||
"""This CLI executes a command only on "\r"; "\n" is just echoed."""
|
||||
return _run_with_newline(channel, command, timeout=timeout, newline="\r")
|
||||
"""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):
|
||||
@@ -96,7 +121,9 @@ def run_commands(channel, log=lambda *_args: None, name="", enable_lldp=False, w
|
||||
|
||||
|
||||
def _field(text, label):
|
||||
match = re.search(rf"(?im)^{re.escape(label)}\s*:\s*(.*?)\s*$", text or "")
|
||||
# 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 ""
|
||||
|
||||
|
||||
@@ -124,17 +151,17 @@ def parse_status(output):
|
||||
|
||||
|
||||
def parse_port_config(output):
|
||||
"""``show configuration``: a port line followed by its description line."""
|
||||
"""``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 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():
|
||||
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
|
||||
|
||||
@@ -215,15 +242,19 @@ def parse_neighbors(output):
|
||||
local = _field(block, "Local Port")
|
||||
if not local:
|
||||
continue
|
||||
port = re.match(r"(\d+)", local)
|
||||
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": _field(block, "System Name"),
|
||||
"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": _field(block, "Chassis ID"),
|
||||
"chassis_id": chassis,
|
||||
"protocol": "LLDP",
|
||||
})
|
||||
return neighbors
|
||||
@@ -280,3 +311,16 @@ def build_snapshot(outputs):
|
||||
"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
|
||||
@@ -2031,21 +2031,35 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
lookup = _RemoteLookup(nb)
|
||||
manual_devices = config.get("neighbor_devices") 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
|
||||
@@ -2054,10 +2068,15 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
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,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from netbox_sync.core import 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
|
||||
@@ -320,6 +320,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:
|
||||
|
||||
@@ -214,6 +214,9 @@ def _quick_reads(monkeypatch):
|
||||
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
|
||||
|
||||
|
||||
@@ -244,3 +247,95 @@ def test_session_is_attached_to_errors(monkeypatch):
|
||||
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,13 @@ 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"])
|
||||
Reference in new issue
Block a user