Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8fce752d2 | ||
|
|
7f04944343 | ||
|
|
894de49014 | ||
|
|
96d40b2005 | ||
|
|
b1ac0689dc | ||
|
|
be3a02179c | ||
|
|
52680e5b7c | ||
|
|
1968098b63 | ||
|
|
17c010ecbc | ||
|
|
dbaf2a83c0 |
No files matched your search
@@ -86,7 +86,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
decisions are stored per profile (shared by all its switches); only VLANs
|
||||
that still need a decision are shown, stored and unambiguous ones are in a
|
||||
collapsed section that can be expanded for editing. Mapped VLANs are assigned
|
||||
to the ports (802.1Q mode, untagged/tagged)
|
||||
to the ports (802.1Q mode, untagged/tagged). The interface at the other end
|
||||
of a port's cable (e.g. a router or access point) is kept in step: VLANs it
|
||||
is missing are added, VLANs the switch port no longer carries are removed;
|
||||
other VLANs there stay. The same applies to the connection VLANs of the
|
||||
cable itself (NetBox Utilities plugin, `cable-vlans` API). After the preview the app asks before changing these
|
||||
far ends ("Nur Switch" syncs the switch alone)
|
||||
- Tenant required: a switch without tenant in NetBox is refused; every created
|
||||
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
|
||||
- Stacks are detected (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.21.1"
|
||||
#define AppVersion "4.24.1"
|
||||
#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.21.1"
|
||||
APP_VERSION = "4.24.1"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ def inventory_report(client):
|
||||
else "") if part)),
|
||||
("CPU", f"{client['cpu']} ({client.get('cores') or '?'} Kerne)" if client.get("cpu") else ""),
|
||||
("RAM", f"{client['memory'] / 1024 ** 3:.0f} GB" if client.get("memory") else ""),
|
||||
("Zuletzt angemeldet", (client.get("user") or "").strip()),
|
||||
("Erfasst", client.get("scanned_at") and time.strftime("%d.%m.%Y %H:%M", time.localtime(client["scanned_at"]))),
|
||||
):
|
||||
if value:
|
||||
@@ -56,6 +57,16 @@ def _cell(text):
|
||||
return str(text or "").replace("|", "/").replace("\n", " ").strip()
|
||||
|
||||
|
||||
def client_description(client):
|
||||
"""Short description for asset and device: UUID and the last signed-in user."""
|
||||
parts = ["Windows-Client"]
|
||||
if client.get("uuid"):
|
||||
parts.append(f"UUID {client['uuid']}")
|
||||
if (client.get("user") or "").strip():
|
||||
parts.append(f"Zuletzt angemeldet: {client['user'].strip()}")
|
||||
return "; ".join(parts)[:200]
|
||||
|
||||
|
||||
def merge_report(comments, report):
|
||||
"""Replace the managed report block in ``comments`` and keep everything written by hand."""
|
||||
comments = comments or ""
|
||||
@@ -263,7 +274,7 @@ class ClientSyncEngine:
|
||||
if len(assets) > 1:
|
||||
return [f"Asset übersprungen – {len(assets)} Assets mit der Seriennummer {serial}"]
|
||||
report_text = inventory_report(client)
|
||||
description = f"Windows-Client; UUID {client['uuid']}" if client.get("uuid") else "Windows-Client"
|
||||
description = client_description(client)
|
||||
if not assets:
|
||||
report["assets_created"] += 1
|
||||
if not dry_run:
|
||||
@@ -289,10 +300,10 @@ class ClientSyncEngine:
|
||||
updates["device"] = device.id
|
||||
if tenant_id and related_id(asset, "tenant") is None:
|
||||
updates["tenant"] = tenant_id
|
||||
if client.get("uuid") and (getattr(asset, "description", "") or "") != description:
|
||||
if (client.get("uuid") or client.get("user")) and (getattr(asset, "description", "") or "") != description:
|
||||
updates["description"] = description
|
||||
current = getattr(asset, "comments", "") or ""
|
||||
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
|
||||
if report_text and (updates or _without_timestamp(_report_body(current)) != _without_timestamp(report_text)):
|
||||
updates["comments"] = merge_report(current, report_text)
|
||||
if not updates:
|
||||
return []
|
||||
@@ -300,7 +311,7 @@ class ClientSyncEngine:
|
||||
if not dry_run:
|
||||
asset.update(updates)
|
||||
labels = {"name": "Name", "status": "Status", "device_type": "Gerätetyp", "device": "Gerät", "tenant": "Mandant",
|
||||
"description": "UUID", "comments": "Inventarbericht"}
|
||||
"description": "Beschreibung", "comments": "Inventarbericht"}
|
||||
return ["Asset aktualisieren: " + ", ".join(labels[key] for key in updates)]
|
||||
|
||||
def software_sync(self):
|
||||
@@ -365,7 +376,8 @@ class ClientSyncEngine:
|
||||
if self.software:
|
||||
changes.extend(self._sync_software(client, None, dry_run, report))
|
||||
return changes
|
||||
payload = {"name": name, "device_type": type_id, "role": role_id, "site": site_id, "status": "active"}
|
||||
payload = {"name": name, "device_type": type_id, "role": role_id, "site": site_id, "status": "active",
|
||||
"description": client_description(client)}
|
||||
if platform_id:
|
||||
payload["platform"] = platform_id
|
||||
if serial:
|
||||
@@ -394,9 +406,13 @@ class ClientSyncEngine:
|
||||
if tenant_id and related_id(device, "tenant") is None:
|
||||
updates["tenant"] = tenant_id
|
||||
changes.append("Mandant setzen")
|
||||
description = client_description(client)
|
||||
if (client.get("uuid") or client.get("user")) and (getattr(device, "description", "") or "") != description:
|
||||
updates["description"] = description
|
||||
changes.append(f"Beschreibung → {description}")
|
||||
report_text = inventory_report(client)
|
||||
current = getattr(device, "comments", "") or ""
|
||||
if report_text and _without_timestamp(_report_body(current)) != _without_timestamp(report_text):
|
||||
if report_text and (updates or _without_timestamp(_report_body(current)) != _without_timestamp(report_text)):
|
||||
updates["comments"] = merge_report(current, report_text)
|
||||
changes.append(f"Inventarbericht aktualisieren ({len(client.get('software') or [])} Programme)")
|
||||
if updates:
|
||||
|
||||
@@ -241,9 +241,21 @@ def chassis_name(types):
|
||||
return ""
|
||||
|
||||
|
||||
def _strip_nul(value):
|
||||
"""Drop NUL characters (some installers pad registry strings with them; NetBox rejects them)."""
|
||||
if isinstance(value, str):
|
||||
return value.replace("\x00", "").strip() if "\x00" in value else value
|
||||
if isinstance(value, dict):
|
||||
return {key: _strip_nul(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_strip_nul(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def apply_scan(row, raw, now=None):
|
||||
"""Merge the raw WinRM result into a result row."""
|
||||
row = dict(row)
|
||||
raw = _strip_nul(raw)
|
||||
row["scanned_at"] = now or time.time()
|
||||
if not raw.get("ok"):
|
||||
row["status"] = "error"
|
||||
|
||||
@@ -378,12 +378,17 @@ class PrinterSyncEngine(APSyncEngine):
|
||||
key=lambda row: (row["manufacturer"].casefold(), row["model"].casefold()))
|
||||
return result
|
||||
|
||||
def existing_type(self, printer):
|
||||
"""NetBox device type row of ``printer`` (same manufacturer and model), or ``None``."""
|
||||
manufacturer, model, _platform = self._identity(printer)
|
||||
return next((row for row in self.device_types if row["model"].casefold() == model.casefold()
|
||||
and row["manufacturer"].casefold() in (
|
||||
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")),
|
||||
None)
|
||||
|
||||
def type_exists(self, printer):
|
||||
"""Is the device type of ``printer`` already in NetBox (same manufacturer and model)?"""
|
||||
manufacturer, model, _platform = self._identity(printer)
|
||||
return any(row["model"].casefold() == model.casefold() and row["manufacturer"].casefold() in (
|
||||
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")
|
||||
for row in self.device_types)
|
||||
return self.existing_type(printer) is not None
|
||||
|
||||
def suggest_type(self, printer):
|
||||
"""Device type with a similar model name, or ``None``."""
|
||||
|
||||
@@ -1920,7 +1920,7 @@ def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||
backup_config=False, update_cables=False):
|
||||
backup_config=False, update_cables=False, sync_peer_vlans=True):
|
||||
"""Write a discovery snapshot to NetBox.
|
||||
|
||||
With ``dry_run`` nothing is written; the returned report lists what would
|
||||
@@ -1950,7 +1950,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
and stack_member(name, snapshot.get("platform")) == member)
|
||||
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
||||
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||
records, foreign = {}, set()
|
||||
records, foreign, port_vlans, old_vlans = {}, set(), {}, {}
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
@@ -1962,6 +1962,13 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
||||
label = port_label(port["vlans"], interface.get("lag"))
|
||||
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
|
||||
if netbox_interface_type(interface) != "virtual":
|
||||
port_vlans[key] = port["vlans"] or {}
|
||||
if record:
|
||||
# VLANs the port had before this run – the ones it loses are removed at the far end, too.
|
||||
old_vlans[key] = ({related_id(record, "untagged_vlan")}
|
||||
| {getattr(item, "id", item) for item in getattr(record, "tagged_vlans", None) or []})
|
||||
old_vlans[key].discard(None)
|
||||
try:
|
||||
if record:
|
||||
changes = {}
|
||||
@@ -2054,6 +2061,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"IP-Adresse {address} auf {interface['name']}: {error}")
|
||||
|
||||
new_peers, new_cables = {}, {}
|
||||
if create_cables:
|
||||
lookup = _RemoteLookup(nb)
|
||||
manual_devices = config.get("neighbor_devices") or {}
|
||||
@@ -2113,20 +2121,147 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
report["cables_created"] += 1
|
||||
report["changes"].append(f"Kabel {device.name} {label}")
|
||||
if not dry_run:
|
||||
nb.dcim.cables.create({
|
||||
new_cables[key] = nb.dcim.cables.create({
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||
"status": "connected",
|
||||
"tenant": tenant_id,
|
||||
})
|
||||
remote.cable = True # avoid a second cable from the reverse direction
|
||||
new_peers[key] = remote
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if sync_peer_vlans:
|
||||
_sync_cable_vlans(nb, records, port_vlans, old_vlans, new_cables, vlan_ids, own_devices, dry_run, report)
|
||||
_sync_peer_vlans(nb, records, port_vlans, old_vlans, new_peers, vlan_ids, vlan_sites, own_devices, dry_run, report)
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
def _sync_cable_vlans(nb, records, port_vlans, old_vlans, new_cables, vlan_ids, own_devices, dry_run, report):
|
||||
"""Keep the connection VLANs of each port's cable (NetBox Utilities plugin) in step with the port.
|
||||
|
||||
Like the far end: the port's VLANs are added, VLANs it lost in this run are
|
||||
removed, others stay. Without the plugin (or its cable VLAN API) nothing happens.
|
||||
"""
|
||||
try:
|
||||
endpoint = nb.plugins.utilities.cable_vlans
|
||||
except AttributeError:
|
||||
return
|
||||
for key, vlans in port_vlans.items():
|
||||
record = records.get(key)
|
||||
cable_id = getattr(new_cables.get(key), "id", None) or (related_id(record, "cable") if record else None)
|
||||
if not isinstance(cable_id, int) or vlans.get("tagged_all"):
|
||||
continue
|
||||
try:
|
||||
peer = _cable_peer(nb, record) if record else None
|
||||
if peer is not None and related_id(peer, "device") in own_devices:
|
||||
continue # switch-to-switch cable: both sides sync it, VLANs would flip
|
||||
port_ids = {vlan_ids[vid] for vid in list(vlans.get("untagged", [])) + list(vlans.get("tagged", []))
|
||||
if isinstance(vlan_ids.get(vid), int)}
|
||||
removed = old_vlans.get(key, set()) - port_ids
|
||||
assignments = list(endpoint.filter(cable_id=cable_id))
|
||||
assignment = assignments[0] if assignments else None
|
||||
current = {getattr(item, "id", item) for item in (getattr(assignment, "vlans", None) or [])}
|
||||
wanted = (current - removed) | port_ids
|
||||
if wanted == current:
|
||||
continue
|
||||
texts = []
|
||||
if wanted - current:
|
||||
texts.append(f"{len(wanted - current)} VLAN(s) vom Switch-Port übernommen")
|
||||
if current - wanted:
|
||||
texts.append(f"{len(current - wanted)} VLAN(s) entfernt (am Switch-Port weggefallen)")
|
||||
name = record.name if record else key
|
||||
report["changes"].append(f"Kabel-VLANs {name}: {', '.join(texts)}")
|
||||
if dry_run:
|
||||
continue
|
||||
if assignment:
|
||||
assignment.update({"vlans": sorted(wanted)})
|
||||
else:
|
||||
endpoint.create({"cable": cable_id, "vlans": sorted(wanted)})
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) == 404:
|
||||
return # plugin version without the cable VLAN API
|
||||
report["errors"].append(f"Kabel-VLANs von {key}: {error}")
|
||||
|
||||
|
||||
def _cable_peer(nb, record):
|
||||
"""The single far-end interface of ``record``'s cable, or ``None``."""
|
||||
cable_id = related_id(record, "cable")
|
||||
if not cable_id:
|
||||
return None
|
||||
cable = nb.dcim.cables.get(cable_id)
|
||||
if cable is None:
|
||||
return None
|
||||
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") == record.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":
|
||||
return None
|
||||
return nb.dcim.interfaces.get(_term(far[0], "object_id"))
|
||||
|
||||
|
||||
def _sync_peer_vlans(nb, records, port_vlans, old_vlans, new_peers, vlan_ids, vlan_sites, own_devices, dry_run, report):
|
||||
"""Keep the interface at the other end of each switch port's cable in step with the port.
|
||||
|
||||
VLANs the port carries are added; VLANs the port carried before this run but
|
||||
no longer does are removed. Other VLANs of the far end stay untouched. Devices
|
||||
synced by this run are skipped, so the far end never has to be maintained by hand.
|
||||
"""
|
||||
site_cache = {}
|
||||
for key, vlans in port_vlans.items():
|
||||
record = records.get(key)
|
||||
try:
|
||||
peer = new_peers.get(key)
|
||||
if peer is not None and not isinstance(getattr(peer, "id", None), int):
|
||||
peer = None
|
||||
if peer is None and record is not None and not isinstance(getattr(record, "cable", None), bool):
|
||||
peer = _cable_peer(nb, record)
|
||||
if peer is None:
|
||||
continue
|
||||
peer_device = related_id(peer, "device")
|
||||
if peer_device in own_devices or vlans.get("tagged_all"):
|
||||
continue
|
||||
port_ids = {vlan_ids[vid] for vid in list(vlans.get("untagged", [])) + list(vlans.get("tagged", []))
|
||||
if vid in vlan_ids}
|
||||
removed = old_vlans.get(key, set()) - port_ids
|
||||
if peer_device not in site_cache:
|
||||
site_cache[peer_device] = related_id(nb.dcim.devices.get(peer_device), "site")
|
||||
peer_site = site_cache[peer_device]
|
||||
|
||||
def allowed(vid):
|
||||
return vid in vlan_ids and vlan_sites.get(vid, (None,))[0] in (None, peer_site)
|
||||
|
||||
mode = _record_mode(peer)
|
||||
if mode == "tagged-all":
|
||||
continue
|
||||
current_untagged = related_id(peer, "untagged_vlan")
|
||||
current_tagged = {getattr(item, "id", item) for item in getattr(peer, "tagged_vlans", None) or []}
|
||||
untagged = next((vlan_ids[vid] for vid in vlans.get("untagged", []) if allowed(vid)), None)
|
||||
tagged = {vlan_ids[vid] for vid in vlans.get("tagged", []) if allowed(vid)}
|
||||
kept_untagged = None if current_untagged in removed else current_untagged
|
||||
new_untagged = kept_untagged or untagged
|
||||
new_tagged = ((current_tagged - removed) | tagged) - {new_untagged}
|
||||
if new_untagged == current_untagged and new_tagged == current_tagged:
|
||||
continue
|
||||
new_mode = "tagged" if new_tagged else "access" if new_untagged else None
|
||||
peer_name = f"{_term(_term(peer, 'device') or {}, 'name') or peer_device} {peer.name}"
|
||||
before = current_tagged | ({current_untagged} - {None})
|
||||
after = new_tagged | ({new_untagged} - {None})
|
||||
texts = []
|
||||
if after - before:
|
||||
texts.append(f"{len(after - before)} VLAN(s) vom Switch-Port übernommen")
|
||||
if before - after:
|
||||
texts.append(f"{len(before - after)} VLAN(s) entfernt (am Switch-Port weggefallen)")
|
||||
report["changes"].append(f"Gegenstelle {peer_name}: {', '.join(texts) or 'VLAN-Zuordnung angepasst'}")
|
||||
if not dry_run:
|
||||
peer.update({"mode": new_mode, "untagged_vlan": new_untagged,
|
||||
"tagged_vlans": sorted(new_tagged, key=str)})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"VLANs der Gegenstelle von {key}: {error}")
|
||||
|
||||
|
||||
def describe_snapshot(snapshot):
|
||||
stack = snapshot.get("stack") or []
|
||||
return (
|
||||
|
||||
@@ -567,14 +567,23 @@ class Actions:
|
||||
# Opened after the preview task has fully finished, so the
|
||||
# follow-up task is not rejected as "still busy".
|
||||
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
||||
if dialog.exec():
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
|
||||
if not dialog.exec():
|
||||
return
|
||||
peers = [f"{switch['name']}: {change}" for switch, report in reports
|
||||
for change in report["changes"] if change.startswith(("Gegenstelle ", "Kabel-VLANs "))]
|
||||
sync_peers = not peers or widgets.confirm(
|
||||
self.window, "Gegenstellen anpassen?",
|
||||
f"{len(peers)} Kabel bzw. per Kabel verbundene Schnittstelle(n) anderer Geräte haben andere VLANs als "
|
||||
"der Switch-Port. Sollen sie angeglichen werden (fehlende ergänzen, am Switch weggefallene "
|
||||
"entfernen)? Ohne Anpassung wird nur der Switch synchronisiert.",
|
||||
ok_text="Angleichen", cancel_text="Nur Switch", details="\n".join(peers))
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables, sync_peers)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False, sync_peers=True):
|
||||
def work(ctx):
|
||||
reports = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
@@ -583,7 +592,7 @@ class Actions:
|
||||
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
||||
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)
|
||||
update_cables=update_cables, sync_peer_vlans=sync_peers)
|
||||
for error in report["errors"]:
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
for note in report.get("notes", []):
|
||||
|
||||
@@ -368,8 +368,9 @@ class ClientsPage(Page):
|
||||
self.agent_targets.setFixedHeight(52)
|
||||
grid.addWidget(label("Ziele"), 0, 0)
|
||||
grid.addWidget(self.agent_targets, 0, 1, 1, 5)
|
||||
self.agent_key = PasswordField("noch kein Schlüssel")
|
||||
self.agent_key.setReadOnly(True)
|
||||
self.agent_key = PasswordField("Schlüssel erzeugen oder vorhandenen einfügen")
|
||||
self.agent_key.setToolTip("Schlüssel bereits verteilter Agenten hier einfügen")
|
||||
self.agent_key.editingFinished.connect(self._agent_key_edited)
|
||||
grid.addWidget(label("Agent-Schlüssel"), 1, 0)
|
||||
grid.addWidget(self.agent_key, 1, 1)
|
||||
self.agent_key_new = button("Neu erzeugen", "refresh", on_click=self.new_agent_key,
|
||||
@@ -400,6 +401,17 @@ class ClientsPage(Page):
|
||||
self.agent_config.setEnabled(bool(key))
|
||||
self.agent_key_new.setText("Neu erzeugen" if key else "Schlüssel erzeugen")
|
||||
|
||||
def _agent_key_edited(self):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
key = self.agent_key.text().strip()
|
||||
if key == self.state.profile.get("agent_key", ""):
|
||||
return
|
||||
self.state.edit_profile(agent_key=key)
|
||||
self._update_agent_key()
|
||||
if key:
|
||||
self.window.toast("Agent-Schlüssel übernommen.", "info")
|
||||
|
||||
def new_agent_key(self):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
|
||||
@@ -12,6 +12,7 @@ from PySide6.QtWidgets import (
|
||||
QStackedWidget,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QToolButton,
|
||||
)
|
||||
|
||||
from netbox_sync.core import netscan, printers, snmp
|
||||
@@ -194,11 +195,13 @@ class SnmpCredentialsDialog(_Dialog):
|
||||
class ModelMappingDialog(_Dialog):
|
||||
"""Decide per printer model that is missing in NetBox: create, map to an existing type, skip or ignore."""
|
||||
|
||||
def __init__(self, parent, rows, device_types):
|
||||
def __init__(self, parent, rows, device_types, others=()):
|
||||
super().__init__(parent, "Modelle zuordnen",
|
||||
"Diese Modelle gibt es in NetBox nicht als Gerätetyp. Gerätetypen werden nicht automatisch "
|
||||
"angelegt – pro Modell einen vorhandenen Gerätetyp wählen, die Drucker dieses Modells diesmal "
|
||||
"überspringen oder dauerhaft ignorieren (gespeichert im Profil).", width=900)
|
||||
"Hier stehen nur Modelle, die es in NetBox nicht als Gerätetyp gibt"
|
||||
+ (f" – die übrigen {len(others)} neuen Drucker haben einen und werden normal übertragen"
|
||||
if others else "") + ". Gerätetypen werden nicht automatisch angelegt – pro Modell einen "
|
||||
"vorhandenen Gerätetyp wählen, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
|
||||
"ignorieren (gespeichert im Profil).", width=900)
|
||||
self.resize(1040, 520)
|
||||
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
|
||||
self.table = QTableWidget(0, 4)
|
||||
@@ -229,11 +232,42 @@ class ModelMappingDialog(_Dialog):
|
||||
for column, width in enumerate((330, 60, 250, 300)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
self.root.addWidget(self.table, 1)
|
||||
if others:
|
||||
self._add_others(others)
|
||||
self.root.addWidget(self.error_banner)
|
||||
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
|
||||
self.root.addWidget(buttons)
|
||||
self.result = {}
|
||||
|
||||
def _add_others(self, others):
|
||||
"""Collapsed list of the new printers whose device type exists – they need no decision here."""
|
||||
caption = f"Weitere neue Drucker mit vorhandenem Gerätetyp ({len(others)})"
|
||||
toggle = QToolButton()
|
||||
toggle.setText(caption)
|
||||
toggle.setCheckable(True)
|
||||
toggle.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
|
||||
toggle.setArrowType(Qt.RightArrow)
|
||||
toggle.setAutoRaise(True)
|
||||
table = QTableWidget(len(others), 3)
|
||||
table.setHorizontalHeaderLabels(["Drucker", "Hersteller / Modell (SNMP)", "Gerätetyp in NetBox"])
|
||||
for row, (name, model, device_type) in enumerate(others):
|
||||
for column, text in enumerate((name, model, device_type)):
|
||||
table.setItem(row, column, QTableWidgetItem(text))
|
||||
table.verticalHeader().hide()
|
||||
table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
table.setSelectionMode(QTableWidget.NoSelection)
|
||||
table.horizontalHeader().setStretchLastSection(True)
|
||||
for column, width in enumerate((260, 330, 300)):
|
||||
table.setColumnWidth(column, width)
|
||||
table.setVisible(False)
|
||||
|
||||
def toggled(shown):
|
||||
toggle.setArrowType(Qt.DownArrow if shown else Qt.RightArrow)
|
||||
table.setVisible(shown)
|
||||
toggle.toggled.connect(toggled)
|
||||
self.root.addWidget(toggle)
|
||||
self.root.addWidget(table, 1)
|
||||
|
||||
def accept(self):
|
||||
result = {}
|
||||
for key, text, action, device_type in self.rows:
|
||||
@@ -629,7 +663,16 @@ class PrintersPage(AccessPointsPage):
|
||||
decision["action"] = "skip"
|
||||
text = f"{first.get('manufacturer') or 'Unbekannt'} · {first.get('model') or '(kein Modell – nur Ports)'}"
|
||||
rows.append((text, len(members), key, decision, self.engine.suggest_type(first)))
|
||||
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types)
|
||||
others = []
|
||||
for printer in self.aps:
|
||||
if printer.get("device") or self._excluded(printer):
|
||||
continue
|
||||
row = self.engine.existing_type(printer)
|
||||
if row:
|
||||
others.append((" · ".join(filter(None, (printer["name"], printer.get("ip")))),
|
||||
f"{printer.get('manufacturer') or ''} · {printer.get('model') or ''}",
|
||||
f"{row['manufacturer']} {row['model']}".strip()))
|
||||
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types, others)
|
||||
if not dialog.exec():
|
||||
return False
|
||||
for key, value in dialog.result.items():
|
||||
|
||||
@@ -68,7 +68,7 @@ class Endpoint:
|
||||
def create(self, payload):
|
||||
if isinstance(payload, list): # bulk create
|
||||
return [self.create(item) for item in payload]
|
||||
record = Record(self, id=next(_ids), cable=None, **payload)
|
||||
record = Record(self, **{"id": next(_ids), "cable": None, **payload})
|
||||
self.records.append(record)
|
||||
self.created.append(payload)
|
||||
return record
|
||||
|
||||
+11
-1
@@ -285,7 +285,7 @@ def test_new_client_gets_an_asset_linked_to_the_device():
|
||||
device = nb.dcim.devices.records[0]
|
||||
asset = assets.created[0]
|
||||
assert asset["serial"] == "PW0K84A9" and asset["device"] == device.id and asset["status"] == "used"
|
||||
assert asset["device_type"] == device.device_type and asset["description"] == "Windows-Client; UUID 4C4C-1234"
|
||||
assert asset["device_type"] == device.device_type and asset["description"] == "Windows-Client; UUID 4C4C-1234; Zuletzt angemeldet: FIRMA\max"
|
||||
assert "| 7-Zip | 24 | |" in asset["comments"]
|
||||
|
||||
again = ClientSyncEngine(nb)
|
||||
@@ -338,3 +338,13 @@ def test_asset_gets_the_tenant_of_the_transfer_or_the_device():
|
||||
again.load_targets()
|
||||
report = again.sync([client2], 1, 2, dry_run=False)
|
||||
assert report["errors"] == [] and assets2.records[0].tenant == 9 and assets2.records[0].device == 300
|
||||
|
||||
|
||||
def test_nul_characters_are_stripped_and_user_is_in_the_report():
|
||||
from netbox_sync.core.client_sync import inventory_report
|
||||
from netbox_sync.core.clients import apply_scan
|
||||
raw = {"ok": True, "source": "agent", "name": "pc01", "user": "FIRMA\max",
|
||||
"software": [{"name": "Office", "version": "16", "publisher": "Microsoft\x00"}]}
|
||||
row = apply_scan({"name": "PC01"}, raw, now=0)
|
||||
assert row["software"][0]["publisher"] == "Microsoft"
|
||||
assert "- **Zuletzt angemeldet:** FIRMA\max" in inventory_report(row)
|
||||
@@ -679,3 +679,58 @@ def test_chosen_interface_of_another_device_is_ignored():
|
||||
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0
|
||||
|
||||
|
||||
def test_far_end_of_a_cable_gets_missing_vlans_of_the_switch_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="LAN", tenant=SimpleNamespace(id=7), site=None),
|
||||
Record(nb.ipam.vlans, id=136, vid=36, name="WMGMT", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [36], "tagged_all": False}
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
peer = nb.dcim.interfaces.get(20)
|
||||
peer.cable, peer.mode, peer.untagged_vlan, peer.tagged_vlans = SimpleNamespace(id=70), "access", 120, []
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70,
|
||||
a_terminations=[{"object_type": "dcim.interface", "object_id": 2}],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 20}]))
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert any("Gegenstelle" in change and "1 VLAN" in change for change in report["changes"])
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert peer.mode == "tagged" and peer.untagged_vlan == 120 and peer.tagged_vlans == [136]
|
||||
again = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("Gegenstelle" in change for change in again["changes"])
|
||||
# VLAN 36 is removed on the switch: it disappears at the far end, too; a manual VLAN stays.
|
||||
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=199, vid=99, name="MANUELL", tenant=SimpleNamespace(id=7),
|
||||
site=None))
|
||||
peer.tagged_vlans = [136, 199]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [], "tagged_all": False}
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert any("1 VLAN(s) entfernt" in change for change in report["changes"])
|
||||
assert peer.untagged_vlan == 120 and peer.tagged_vlans == [199] and peer.mode == "tagged"
|
||||
|
||||
|
||||
def test_cable_vlans_of_the_utilities_plugin_follow_the_switch_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="LAN", tenant=SimpleNamespace(id=7), site=None),
|
||||
Record(nb.ipam.vlans, id=136, vid=36, name="WMGMT", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [36], "tagged_all": False}
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70,
|
||||
a_terminations=[{"object_type": "dcim.interface", "object_id": 2}],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 20}]))
|
||||
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(cable_vlans=Endpoint()))
|
||||
cable_vlans = nb.plugins.utilities.cable_vlans
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Kabel-VLANs 2: 2 VLAN(s) vom Switch-Port übernommen" in report["changes"] and cable_vlans.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert cable_vlans.created == [{"cable": 70, "vlans": [120, 136]}]
|
||||
cable_vlans.records[0].cable = SimpleNamespace(id=70)
|
||||
|
||||
# VLAN 36 is removed on the switch; a VLAN set by hand on the cable stays.
|
||||
cable_vlans.records[0].vlans = [120, 136, 199]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [], "tagged_all": False}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert cable_vlans.updates[-1] == (cable_vlans.records[0].id, {"vlans": [120, 199]})
|
||||
Reference in new issue
Block a user