diff --git a/netbox_sync/core/lancom.py b/netbox_sync/core/lancom.py index 9e43a1c..5bcf8b4 100644 --- a/netbox_sync/core/lancom.py +++ b/netbox_sync/core/lancom.py @@ -12,6 +12,7 @@ import time from netbox_sync.core.switches import ( CLI_ERROR, CLI_PROMPT, + MAC_PATTERN, _compress_vlans, _interface, _membership, @@ -120,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 "" @@ -148,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 @@ -240,14 +243,18 @@ def parse_neighbors(output): 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": _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 diff --git a/netbox_sync/core/switches.py b/netbox_sync/core/switches.py index 22ce371..36917de 100644 --- a/netbox_sync/core/switches.py +++ b/netbox_sync/core/switches.py @@ -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}") diff --git a/tests/test_lancom.py b/tests/test_lancom.py index 81386b0..c2d339e 100644 --- a/tests/test_lancom.py +++ b/tests/test_lancom.py @@ -295,3 +295,47 @@ def test_reparse_fixes_older_exports(): 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"] == "" diff --git a/tests/test_switch_sync.py b/tests/test_switch_sync.py index e4b73a1..353ee99 100644 --- a/tests/test_switch_sync.py +++ b/tests/test_switch_sync.py @@ -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"])