feat: optional running-config backup as NetBox attachment
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
eee60d26ad
commit
770edc4a03
5 files changed
+145
-4
No files matched your search
@@ -97,6 +97,13 @@ 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
|
||||
(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
|
||||
- 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
|
||||
- The switch configuration is only changed when "Enable LLDP if needed" is
|
||||
explicitly switched on
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import ipaddress
|
||||
import re
|
||||
import threading
|
||||
@@ -805,6 +807,15 @@ def parse_lags(config, platform):
|
||||
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):
|
||||
"""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))
|
||||
@@ -897,6 +908,7 @@ def build_snapshot(outputs, platform):
|
||||
"raw": {**{key: value for key, value in outputs.items() if key != "config"},
|
||||
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
|
||||
"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", "")),
|
||||
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
|
||||
"lldp_disabled": outputs.get("lldp_disabled", False),
|
||||
@@ -1678,7 +1690,54 @@ def _sync_lag_members(snapshot, owners, records, dry_run, report):
|
||||
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 sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||
backup_config=False):
|
||||
"""Write a discovery snapshot to NetBox.
|
||||
|
||||
With ``dry_run`` nothing is written; the returned report lists what would
|
||||
@@ -1850,6 +1909,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
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
|
||||
@@ -432,6 +432,7 @@ class Actions:
|
||||
if not self.require_netbox_config():
|
||||
return
|
||||
by_id = {switch["id"]: switch for switch in self.state.switches}
|
||||
backup = self.state.settings.get("backup_config")
|
||||
# VLAN and network decisions are shared by all switches of the profile.
|
||||
vlan_map = self.state.profile.setdefault("vlan_map", {})
|
||||
network_map = self.state.profile.setdefault("network_map", {})
|
||||
@@ -498,7 +499,8 @@ class Actions:
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
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)))
|
||||
return nb, reports
|
||||
|
||||
def show_preview(result):
|
||||
@@ -522,7 +524,8 @@ class Actions:
|
||||
ctx.check_cancelled()
|
||||
ctx.progress(index, len(items), switch["name"])
|
||||
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"))
|
||||
for error in report["errors"]:
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
reports.append((switch, report))
|
||||
|
||||
@@ -93,12 +93,17 @@ class SwitchesPage(Page):
|
||||
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
|
||||
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
|
||||
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
|
||||
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.switch_filter, 1)
|
||||
filters.addWidget(self.only_up)
|
||||
filters.addWidget(self.only_neighbors)
|
||||
filters.addStretch(1)
|
||||
filters.addWidget(self.cables_option)
|
||||
filters.addWidget(self.backup_option)
|
||||
result_card.add(filters)
|
||||
result_columns = [
|
||||
Column("switch", "Switch", 140),
|
||||
@@ -144,6 +149,7 @@ class SwitchesPage(Page):
|
||||
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
|
||||
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.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
|
||||
self.state.switches_changed.connect(self.refresh)
|
||||
self.state.profile_switched.connect(self.refresh)
|
||||
self.state.profile_edited.connect(self.refresh_switches)
|
||||
@@ -155,7 +161,8 @@ class SwitchesPage(Page):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
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")):
|
||||
widget.blockSignals(True)
|
||||
widget.setChecked(bool(self.state.settings.get(key)))
|
||||
widget.blockSignals(False)
|
||||
|
||||
@@ -4,6 +4,7 @@ from fake_netbox import Endpoint, FakeNetBox, Record
|
||||
|
||||
from netbox_sync.core.switches import (
|
||||
build_snapshot,
|
||||
mask_config,
|
||||
match_interfaces,
|
||||
parse_lags,
|
||||
parse_stack,
|
||||
@@ -465,3 +466,65 @@ def test_lag_members_are_assigned_to_their_lag_in_netbox():
|
||||
assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
|
||||
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"
|
||||
|
||||
|
||||
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 == []
|
||||
Reference in new issue
Block a user