Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 d853f08445 chore: release 4.14.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:56 +01:00
MrBlakeandClaude Opus 5.5 f4c507de6c feat: optional update of existing cables; cable APs reporting their MAC as port
- Cables to neighbors that report their MAC address as port ID (e.g. access
  points) are created via the MAC or the device's single physical port
- Existing cables are compared with LLDP/CDP; differences are reported, and
  only with the optional "Bestehende Kabel anpassen" the cable is moved

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:29:55 +01:00
MrBlakeandClaude Opus 5.5 3c8bc7879c chore: release 4.13.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:50 +01:00
MrBlakeandClaude Opus 5.5 770edc4a03 feat: optional running-config backup as NetBox attachment
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:13:49 +01:00
8 changed files with 319 additions and 15 deletions

No files matched your search

+16 -1
View File
@@ -97,7 +97,22 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
plugin (0.24.0 or later) a detected stack is also entered as its switch stack plugin (0.24.0 or later) a detected stack is also entered as its switch stack
(the switch's device as stack switch, the other member devices as members); (the switch's device as stack switch, the other member devices as members);
members entered by hand are kept. Without the plugin this step is skipped members entered by hand are kept. Without the plugin this step is skipped
- Cables from LLDP/CDP, also with FQDN system names or via the management IP - Optional configuration backup ("Konfiguration als Anhang sichern"): with the
[netbox-attachments](https://github.com/Kani999/netbox-attachments) plugin the
running configuration is attached to the switch's device as a text file.
Passwords, keys and SNMP communities are removed first; a new attachment is
only added when the configuration changed (SHA-256 in the description).
Older plugin versions (parent on the attachment) and newer ones (separate
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
- 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
neighbor; such changes are marked with ⚠ in the preview. Cables to patch
panels (front/rear ports) and far ends that already have another cable are
never changed
- The switch configuration is only changed when "Enable LLDP if needed" is - The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on explicitly switched on
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.12.0" #define AppVersion "4.14.0"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.12.0" APP_VERSION = "4.14.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+129 -7
View File
@@ -1,5 +1,7 @@
"""SSH discovery and NetBox synchronization for HPE and Aruba switches.""" """SSH discovery and NetBox synchronization for HPE and Aruba switches."""
import hashlib
import io
import ipaddress import ipaddress
import re import re
import threading import threading
@@ -8,7 +10,7 @@ from pathlib import Path
import paramiko import paramiko
from netbox_sync.core.netbox import assign_mac, related_id from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
PLATFORMS = { PLATFORMS = {
"auto": "Automatisch erkennen", "auto": "Automatisch erkennen",
@@ -805,6 +807,15 @@ def parse_lags(config, platform):
return lags return lags
# Values after these words are removed from configuration backups.
_SECRET = re.compile(r"(?i)\b(password|secret|key|community|ciphertext|plaintext|psk|passphrase)\b(\s+).*$")
def mask_config(config):
"""Running configuration without passwords, keys and SNMP communities."""
return "\n".join(_SECRET.sub(r"\1\2<entfernt>", line) for line in clean_output(config).splitlines()).strip()
def _vlan_config_excerpt(config): def _vlan_config_excerpt(config):
"""Keep only VLAN-related lines – the full configuration may contain secrets.""" """Keep only VLAN-related lines – the full configuration may contain secrets."""
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line)) return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
@@ -897,6 +908,7 @@ def build_snapshot(outputs, platform):
"raw": {**{key: value for key, value in outputs.items() if key != "config"}, "raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})}, **({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")), "vlans_read": bool(outputs.get("config")),
"config_backup": mask_config(outputs["config"]) if outputs.get("config") else "",
"vlan_names": parse_vlan_names(outputs.get("config", "")), "vlan_names": parse_vlan_names(outputs.get("config", "")),
"stack": parse_stack(outputs.get("config", ""), platform, interfaces), "stack": parse_stack(outputs.get("config", ""), platform, interfaces),
"lldp_disabled": outputs.get("lldp_disabled", False), "lldp_disabled": outputs.get("lldp_disabled", False),
@@ -1462,7 +1474,17 @@ class _RemoteLookup:
if _physical_record(record) and _port_number(record.name) == number] if _physical_record(record) and _port_number(record.name) == number]
if len(found) == 1: if len(found) == 1:
return found[0] return found[0]
return None # Access points and phones often report their MAC address as port ID.
mac = normalize_mac(neighbor.get("remote_port"))
if mac:
found = [record for record in records.values()
if normalize_mac(getattr(record, "mac_address", None)) == mac]
if len(found) == 1:
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)]
return physical[0] if len(physical) == 1 else None
_NEW = "new" # placeholder ID of objects a dry run would create _NEW = "new" # placeholder ID of objects a dry run would create
@@ -1611,7 +1633,7 @@ def _new_report():
return { return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0, "interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0, "ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0, "cables_created": 0, "cables_updated": 0, "cables_skipped": 0,
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0, "vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
"changes": [], "errors": [], "notes": [], "changes": [], "errors": [], "notes": [],
} }
@@ -1678,7 +1700,101 @@ def _sync_lag_members(snapshot, owners, records, dry_run, report):
report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}") report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}")
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop): def _backup_config(nb, device, snapshot, dry_run, report):
"""Attach the running configuration to the device (optional netbox-attachments plugin).
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]
try:
app = nb.plugins.netbox_attachments
known = [item for item in app.netbox_attachments.filter(q=digest)
if digest in (getattr(item, "description", "") or "")]
except AttributeError:
return
except Exception as error: # noqa: BLE001
if getattr(getattr(error, "req", None), "status_code", None) == 404:
report["notes"].append("Konfigurations-Backup übersprungen: Plugin netbox-attachments ist nicht installiert")
else:
report["errors"].append(f"Konfigurations-Backup: {error}")
return
if known:
return
stamp = time.strftime("%Y-%m-%d %H-%M", time.localtime(snapshot.get("discovered_at") or time.time()))
name = f"Running-Config {device.name} {stamp}"
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
if dry_run:
return
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + ".txt"
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"),
})
if hasattr(attachment, "assignments"):
# Newer plugin versions assign attachments to objects separately.
app.netbox_attachment_assignments.create({"attachment": attachment.id, "object_type": "dcim.device",
"object_id": device.id})
except Exception as error: # noqa: BLE001
report["errors"].append(f"Konfigurations-Backup: {error}")
def _term(value, key):
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
def _termination_text(termination):
item = _term(termination, "object") or {}
owner = _term(_term(item, "device") or {}, "name")
return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id"))
def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
"""Compare an existing cable of a switch port with its LLDP/CDP neighbor.
NetBox is the source of truth: a different far end is only reported unless
``update_cables`` is set. Cables to patch panels (front/rear ports) or with
several terminations are never touched.
"""
cable = nb.dcim.cables.get(related_id(local, "cable"))
if cable is None:
report["cables_skipped"] += 1
return
sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])]
local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None)
far = sides[1] if local_side is sides[0] else sides[0]
if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface":
report["cables_skipped"] += 1
return
if _term(far[0], "object_id") == remote.id:
report["cables_skipped"] += 1
return
old = _termination_text(far[0])
remote_cable = related_id(remote, "cable")
if not update_cables or (remote_cable and remote_cable != cable.id):
reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables
else "„Bestehende Kabel anpassen“ ist aus")
report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})")
return
report["cables_updated"] += 1
report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}")
if not dry_run:
cable.update({
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
})
remote.cable = cable
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
backup_config=False, update_cables=False):
"""Write a discovery snapshot to NetBox. """Write a discovery snapshot to NetBox.
With ``dry_run`` nothing is written; the returned report lists what would With ``dry_run`` nothing is written; the returned report lists what would
@@ -1820,9 +1936,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if key not in records: if key not in records:
continue continue
local = records[key] local = records[key]
if local is not None and getattr(local, "cable", None): existing = getattr(local, "cable", None) if local is not None else None
report["cables_skipped"] += 1
continue
if neighbor["local_port"] in manual_devices: if neighbor["local_port"] in manual_devices:
# 0 means "no device" was chosen in the review dialog. # 0 means "no device" was chosen in the review dialog.
chosen = int(manual_devices[neighbor["local_port"]] or 0) chosen = int(manual_devices[neighbor["local_port"]] or 0)
@@ -1835,6 +1949,12 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
if remote_device.id in own_devices: if remote_device.id in own_devices:
continue continue
remote = lookup.interface(remote_device, neighbor) remote = 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
continue
if not remote or getattr(remote, "cable", None): if not remote or getattr(remote, "cable", None):
report["cables_skipped"] += 1 report["cables_skipped"] += 1
continue continue
@@ -1850,6 +1970,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
remote.cable = True # avoid a second cable from the reverse direction remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
report["errors"].append(f"Nachbar {label}: {error}") report["errors"].append(f"Nachbar {label}: {error}")
if backup_config:
_backup_config(nb, device, snapshot, dry_run, report)
return report return report
+9 -4
View File
@@ -432,6 +432,8 @@ class Actions:
if not self.require_netbox_config(): if not self.require_netbox_config():
return return
by_id = {switch["id"]: switch for switch in self.state.switches} by_id = {switch["id"]: switch for switch in self.state.switches}
backup = self.state.settings.get("backup_config")
update_cables = create_cables and bool(self.state.settings.get("update_cables"))
# VLAN and network decisions are shared by all switches of the profile. # VLAN and network decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {}) vlan_map = self.state.profile.setdefault("vlan_map", {})
network_map = self.state.profile.setdefault("network_map", {}) network_map = self.state.profile.setdefault("network_map", {})
@@ -498,7 +500,8 @@ class Actions:
for index, (switch, snapshot) in enumerate(items): for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"]) ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: berechne Änderungen …") ctx.log(f"{switch['name']}: berechne Änderungen …")
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True))) reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True,
backup_config=backup, update_cables=update_cables)))
return nb, reports return nb, reports
def show_preview(result): def show_preview(result):
@@ -509,20 +512,22 @@ class Actions:
# follow-up task is not rejected as "still busy". # follow-up task is not rejected as "still busy".
dialog = SyncPreviewDialog(self.window, reports, create_cables) dialog = SyncPreviewDialog(self.window, reports, create_cables)
if dialog.exec(): if dialog.exec():
self._apply_switch_sync(nb, items, create_cables, log) self._apply_switch_sync(nb, items, create_cables, log, update_cables)
QTimer.singleShot(0, ask) QTimer.singleShot(0, ask)
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review, self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
on_error=self._netbox_failed) on_error=self._netbox_failed)
def _apply_switch_sync(self, nb, items, create_cables, log): def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
def work(ctx): def work(ctx):
reports = [] reports = []
for index, (switch, snapshot) in enumerate(items): for index, (switch, snapshot) in enumerate(items):
ctx.check_cancelled() ctx.check_cancelled()
ctx.progress(index, len(items), switch["name"]) ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: übertrage nach NetBox …") ctx.log(f"{switch['name']}: übertrage nach NetBox …")
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False) report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False,
backup_config=self.state.settings.get("backup_config"),
update_cables=update_cables)
for error in report["errors"]: for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error") ctx.log(f"{switch['name']}: {error}", "error")
reports.append((switch, report)) reports.append((switch, report))
+2
View File
@@ -546,6 +546,8 @@ class SyncPreviewDialog(_Dialog):
items.append((f"{totals[key]} {text}", "info")) items.append((f"{totals[key]} {text}", "info"))
if create_cables: if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info")) items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
if totals.get("cables_updated"):
items.append((f"{totals['cables_updated']} Kabel angepasst", "error"))
errors = sum(len(report["errors"]) for _switch, report in reports) errors = sum(len(report["errors"]) for _switch, report in reports)
if errors: if errors:
items.append((f"{errors} Probleme", "error")) items.append((f"{errors} Probleme", "error"))
+30 -1
View File
@@ -93,12 +93,23 @@ class SwitchesPage(Page):
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen", self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox " tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.") "eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
self.update_cables_option = checkbox(
"Bestehende Kabel anpassen",
tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, "
"wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie "
"verändert. Ohne diese Option werden Abweichungen nur gemeldet.")
self.backup_option = checkbox("Konfiguration als Anhang sichern",
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.")
filters.addWidget(self.search, 2) filters.addWidget(self.search, 2)
filters.addWidget(self.switch_filter, 1) filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up) filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors) filters.addWidget(self.only_neighbors)
filters.addStretch(1) filters.addStretch(1)
filters.addWidget(self.cables_option) filters.addWidget(self.cables_option)
filters.addWidget(self.update_cables_option)
filters.addWidget(self.backup_option)
result_card.add(filters) result_card.add(filters)
result_columns = [ result_columns = [
Column("switch", "Switch", 140), Column("switch", "Switch", 140),
@@ -144,6 +155,9 @@ class SwitchesPage(Page):
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons) self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value)) self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value)) self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
self.update_cables_option.toggled.connect(self._toggle_update_cables)
self.cables_option.toggled.connect(self.update_cables_option.setEnabled)
self.state.switches_changed.connect(self.refresh) self.state.switches_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh) self.state.profile_switched.connect(self.refresh)
self.state.profile_edited.connect(self.refresh_switches) self.state.profile_edited.connect(self.refresh_switches)
@@ -155,10 +169,25 @@ class SwitchesPage(Page):
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def _load_settings(self): def _load_settings(self):
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")): for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"),
(self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")):
widget.blockSignals(True) widget.blockSignals(True)
widget.setChecked(bool(self.state.settings.get(key))) widget.setChecked(bool(self.state.settings.get(key)))
widget.blockSignals(False) widget.blockSignals(False)
self.update_cables_option.setEnabled(self.cables_option.isChecked())
def _toggle_update_cables(self, value):
if value and not widgets.confirm(
self.window, "Bestehende Kabel anpassen?",
"NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht "
"zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox "
"verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.",
ok_text="Einschalten", destructive=True):
self.update_cables_option.blockSignals(True)
self.update_cables_option.setChecked(False)
self.update_cables_option.blockSignals(False)
return
self.state.update_settings(update_cables=value)
def _status_text(self, row): def _status_text(self, row):
status = self.state.switch_status.get(row["id"]) status = self.state.switch_status.get(row["id"])
+131
View File
@@ -4,6 +4,7 @@ from fake_netbox import Endpoint, FakeNetBox, Record
from netbox_sync.core.switches import ( from netbox_sync.core.switches import (
build_snapshot, build_snapshot,
mask_config,
match_interfaces, match_interfaces,
parse_lags, parse_lags,
parse_stack, parse_stack,
@@ -465,3 +466,133 @@ def test_lag_members_are_assigned_to_their_lag_in_netbox():
assert not getattr(nb.dcim.interfaces.get(3), "lag", None) assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True) report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert not any("LAG lag1" in change for change in report["changes"]), "already assigned" assert not any("LAG lag1" in change for change in report["changes"]), "already assigned"
class _AttachmentEndpoint(Endpoint):
def create(self, payload):
record = super().create(payload)
if self.assignments is not None:
record.assignments = []
return record
def filter(self, **kwargs):
query = kwargs.pop("q", "")
return [item for item in super().filter(**kwargs) if query in (getattr(item, "description", "") or "")]
def _attachments(newer=True):
attachments = _AttachmentEndpoint()
attachments.assignments = [] if newer else None
return SimpleNamespace(netbox_attachments=attachments, netbox_attachment_assignments=Endpoint())
def test_config_backup_masks_secrets():
config = ('hostname core\nuser admin group administrators password ciphertext AQBapW==\n'
'snmp-server community geheim\nradius-server host 10.0.0.1 key plaintext topsecret\n')
masked = mask_config(config)
assert "AQBapW" not in masked and "geheim" not in masked and "topsecret" not in masked
assert "hostname core" in masked and "password <entfernt>" in masked
def test_config_is_attached_only_when_it_changed():
nb, switch, snapshot = _numbered_setup()
snapshot["config_backup"] = "hostname access-01"
# Without the plugin nothing happens.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
assert not report["errors"]
nb.plugins = SimpleNamespace(netbox_attachments=_attachments())
app = nb.plugins.netbox_attachments
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
assert any(change.startswith("Konfigurations-Backup: Anhang „Running-Config access-01")
for change in report["changes"]) and app.netbox_attachments.created == []
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
payload = app.netbox_attachments.created[0]
assert payload["file"][1].getvalue() == b"hostname access-01" and payload["file"][0].endswith(".txt")
assert app.netbox_attachment_assignments.created == [
{"attachment": app.netbox_attachments.records[0].id, "object_type": "dcim.device", "object_id": 1}]
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
assert not any("Konfigurations-Backup" in change for change in report["changes"]), "unchanged"
snapshot["config_backup"] = "hostname access-01\nvlan 10"
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
assert len(app.netbox_attachments.created) == 2
def test_config_backup_with_older_attachment_plugin():
nb, switch, snapshot = _numbered_setup()
snapshot["config_backup"] = "hostname access-01"
nb.plugins = SimpleNamespace(netbox_attachments=_attachments(newer=False))
app = nb.plugins.netbox_attachments
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
payload = app.netbox_attachments.created[0]
assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1)
assert app.netbox_attachment_assignments.created == []
def test_cable_to_access_point_that_reports_its_mac_as_port():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records += [
Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E",
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None,
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
]
snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e")
switch["neighbor_devices"] = {"1/1/2": 5}
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
# A device with a single port is cabled there even if neither name nor MAC match.
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5),
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc")
switch["neighbor_devices"] = {"1/1/2": 5}
sync_snapshot_to_netbox(nb, switch, snapshot)
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
def _cabled_setup(far_type="dcim.interface"):
"""Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0."""
nb, switch, snapshot = _numbered_setup()
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
far = {"object_type": far_type, "object_id": 99,
"object": {"name": "eth9", "device": {"name": "old-device"}}}
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far],
b_terminations=[{"object_type": "dcim.interface", "object_id": 2}]))
switch["neighbor_devices"] = {"1/1/2": 2}
return nb, switch, snapshot
def test_differing_cable_is_only_reported_by_default():
nb, switch, snapshot = _cabled_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == []
assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"])
def test_differing_cable_is_moved_when_allowed():
nb, switch, snapshot = _cabled_setup()
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True)
assert report["cables_updated"] == 1 and nb.dcim.cables.updates == []
assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"])
sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert nb.dcim.cables.updates == [(70, {
"a_terminations": [{"object_type": "dcim.interface", "object_id": 2}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})]
assert nb.dcim.cables.created == []
def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport")
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"]
nb, switch, snapshot = _cabled_setup()
nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71)
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
assert nb.dcim.cables.updates == []
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])