Compare commits

...
5 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 c85df7402d chore: release 4.16.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:03:52 +01:00
MrBlakeandClaude Opus 5.5 5427cc015e fix: answer the paging prompt of LANCOM LCOS SX 3.x switches
Long outputs stop with "..., q to quit" and the pager cannot be disabled;
it is now answered with Space and removed from the output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:03:52 +01:00
MrBlakeandClaude Opus 5.5 1aa1c15aa8 chore: release 4.16.2
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:47:49 +01:00
MrBlakeandClaude Opus 5.5 51f3fc70cd feat: record the CLI session and show it as raw data, also for failed discoveries
The raw data view builds its tabs from the available outputs (incl. LANCOM)
and adds a "Sitzung" tab with the masked session up to an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:47:49 +01:00
MrBlakeandClaude Opus 5.5 411c5446fe fix: send carriage return as Enter to LANCOM LCOS SX 3.x switches
The CLI only echoes commands terminated with "\n". Auto-detection falls back
to "\r" when the first command is not completed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 15:34:34 +01:00
9 changed files with 240 additions and 34 deletions

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.16.1"
#define AppVersion "4.16.3"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.16.1"
APP_VERSION = "4.16.3"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+39 -2
View File
@@ -11,10 +11,10 @@ import time
from netbox_sync.core.switches import (
CLI_ERROR,
_interface,
CLI_PROMPT,
_compress_vlans,
_interface,
_membership,
_run_cli_command,
clean_output,
parse_vlan_list,
)
@@ -35,6 +35,43 @@ 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):
"""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 ""))
+56 -8
View File
@@ -175,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:
@@ -261,7 +262,16 @@ 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"
@@ -270,10 +280,7 @@ def detect_platform(channel, banner):
if CLI_ERROR.search(version):
# LANCOM LCOS SX 3.x has no "show version"; its system information is in the "system" mode.
from netbox_sync.core import lancom
_run_cli_command(channel, "system")
system = _run_cli_command(channel, "show", timeout=30)
_run_cli_command(channel, "exit")
if lancom.is_lancom(system):
if lancom.probe(channel):
return lancom.PLATFORM
display = _run_cli_command(channel, "display version", timeout=30)
if re.search(r"(?i)Comware", display):
@@ -281,13 +288,54 @@ def detect_platform(channel, banner):
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:
+10 -3
View File
@@ -413,7 +413,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 +441,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():
+31 -16
View File
@@ -1038,17 +1038,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 +1061,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 +1070,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 +1103,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))
+11 -3
View File
@@ -290,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)
@@ -349,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()
@@ -366,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()
@@ -395,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()
@@ -408,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)
+2
View File
@@ -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
+89
View File
@@ -104,6 +104,9 @@ class FakeChannel:
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,
@@ -178,3 +181,89 @@ def test_enable_lldp_on_disabled_ports():
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