Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 f1af9f8f86 chore: release 4.10.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:22 +01:00
MrBlakeandClaude Opus 5.5 2fb6ac38ec feat: ignore Sophos sites without site and tenant
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:46:21 +01:00
MrBlakeandClaude Opus 5.5 2dcd0b0855 chore: release 4.10.3
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:29 +01:00
MrBlakeandClaude Opus 5.5 159a933964 feat: Sophos AP import without upfront tenant, tenant never preselected
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-02 15:23:28 +01:00
6 changed files with 90 additions and 78 deletions

No files matched your search

+12 -11
View File
@@ -49,7 +49,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Add several NetBox devices in one step — host taken from the primary IP,
platform suggested from model/manufacturer
platform suggested from model/manufacturer; members of a NetBox virtual
chassis are added once, through the chassis master
- Platform "detect automatically" via SSH
- Parallel SSH queries; SSH host keys are stored on first contact and verified
afterwards
@@ -95,18 +96,18 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
Windows encoding) and checks it: missing site, duplicate IP, serial number or
MAC address
- Finds existing APs in NetBox globally by serial number and MAC address and by
name within the tenant group; NetBox APs of the tenant group that are missing
in the export are listed as "only in NetBox"
- Sophos sites are mapped to NetBox sites of the tenant group (suggested by
name, stored per profile); the site is optional – APs without one go to a
default site, since NetBox requires a site for every device. The tenant is
mandatory and can be chosen per Sophos site (default: the site's tenant)
- No tenant to pick up front: existing APs are found in all of NetBox by serial
number, MAC address and name; Sophos APs in NetBox that are missing in the
export are listed as "only in NetBox" for the tenants the export concerns
- Sophos sites are mapped to NetBox sites (suggested by name, stored per
profile); the site is optional – APs without one go to a default site, since
NetBox requires a site for every device. The tenant is mandatory and chosen
deliberately per Sophos site – it is never preselected. Sophos sites left without site and tenant are
ignored (stored per profile) and not transferred
- New APs are created with Sophos device type, role, site, serial number,
firmware, interface with MAC and IP address (primary IPv4); existing ones get
missing serial numbers and tenants, optionally the Sophos name. Tenant comes
from the NetBox site, otherwise the selected tenant; devices of other tenants
are never changed. Preview before writing
missing serial numbers and tenants, optionally the Sophos name. Preview before
writing
### Network scanner (read only)
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.10.2"
#define AppVersion "4.10.4"
#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.10.2"
APP_VERSION = "4.10.4"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+14 -2
View File
@@ -129,9 +129,21 @@ class APSyncEngine(ClientSyncEngine):
# Context
# ------------------------------------------------------------------
def load_context(self, tenant_id):
"""Sites and existing Sophos devices of the tenant's tenant group."""
def load_context(self, tenant_id=None):
"""Sites and existing Sophos devices of the tenant's tenant group, or of all of NetBox without a tenant."""
self.tenant_id = tenant_id
if tenant_id is None:
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()}
self.tenant_ids = set(tenants)
self.group_tenants = sorted(({"id": key, "name": name} for key, name in tenants.items()),
key=lambda row: row["name"].casefold())
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
"tenant": tenants.get(related_id(site, "tenant"), "")}
for site in self.nb.dcim.sites.all()), key=lambda row: row["name"].casefold())
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id)) if manufacturer else []
return self.ap_sites
tenant = self.nb.tenancy.tenants.get(tenant_id)
if tenant is None:
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
+49 -63
View File
@@ -30,8 +30,10 @@ from netbox_sync.ui.widgets import (
label,
)
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox"}
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint"}
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox",
"ignored": "ignoriert"}
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint",
"ignored": "text_faint"}
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
@@ -46,17 +48,16 @@ class SiteMappingDialog(_Dialog):
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
and to APs without a Sophos site."""
def __init__(self, parent, rows, sites, tenants, default_tenant):
def __init__(self, parent, rows, sites, tenants):
super().__init__(parent, "Standorte & Mandanten zuordnen",
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht; vorgeschlagen wird der des "
"Standorts, sonst der gewählte Mandant.", width=860)
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. Zeilen ohne "
"Standort und ohne Mandant werden ignoriert.",
width=860)
self.resize(980, 620)
self.sites = {site["id"]: site for site in sites}
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
self.default_tenant = default_tenant
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
"Mandant *"])
@@ -69,9 +70,8 @@ class SiteMappingDialog(_Dialog):
site = SearchableComboBox("Standort suchen …")
site.set_items(site_items, current["site"] or 0)
tenant = SearchableComboBox("Mandant wählen …")
tenant.set_items(tenant_items, current["tenant"] or self._site_tenant(current["site"]))
site.activated.connect(lambda _index, site=site, tenant=tenant: tenant.select_data(
self._site_tenant(site.valid_data())))
# only a stored choice is shown – never a suggestion
tenant.set_items(tenant_items, current["tenant"])
self.table.setCellWidget(row, 2, site)
self.table.setCellWidget(row, 3, tenant)
self.rows.append((key, site, tenant))
@@ -88,13 +88,10 @@ class SiteMappingDialog(_Dialog):
self.root.addWidget(buttons)
self.result = {}
def _site_tenant(self, site_id):
return (self.sites.get(site_id) or {}).get("tenant_id") or self.default_tenant
def accept(self):
result = {}
for key, site, tenant in self.rows:
if tenant.valid_data() is None:
if tenant.valid_data() is None and site.valid_data():
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
return
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
@@ -105,14 +102,14 @@ class SiteMappingDialog(_Dialog):
class AccessPointsPage(Page):
title = "Access Points"
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
"Seriennummer und MAC, im Mandanten über den Namen) und fehlende anlegen.")
"Seriennummer, MAC und Name) und fehlende anlegen.")
def __init__(self, window):
super().__init__(window)
self.aps = []
self.only_netbox = []
self.engine = None
self.tenants = []
self.roles = []
self.file_name = ""
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
@@ -121,13 +118,6 @@ class AccessPointsPage(Page):
on_click=self.sync))
form = QFormLayout()
form.setHorizontalSpacing(18)
tenant_row = QHBoxLayout()
self.tenant = SearchableComboBox("Mandant wählen …")
self.tenant.setMinimumWidth(320)
tenant_row.addWidget(self.tenant)
self.tenant_hint = label("Standorte und vorhandene APs werden in seiner Mandantengruppe gesucht.", muted=True)
tenant_row.addWidget(self.tenant_hint, 1)
form.addRow("Mandant *", tenant_row)
self.role = SearchableComboBox("Geräterolle wählen …")
self.role.setMinimumWidth(320)
form.addRow("Geräterolle", self.role)
@@ -192,7 +182,6 @@ class AccessPointsPage(Page):
self.search.textChanged.connect(self.proxy.set_text)
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
self.tenant.activated.connect(lambda _index: self._tenant_chosen())
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
self._refresh()))
@@ -214,8 +203,7 @@ class AccessPointsPage(Page):
self.state.touch()
def _profile_switched(self):
self.aps, self.only_netbox, self.engine, self.tenants = [], [], None, []
self.tenant.set_items([])
self.aps, self.only_netbox, self.engine, self.roles = [], [], None, []
self.role.set_items([])
self.default_site.set_items([])
self.rename.blockSignals(True)
@@ -224,7 +212,7 @@ class AccessPointsPage(Page):
self._refresh()
def on_show(self):
if not self.tenants and self._netbox_ready() and not self.tasks.busy:
if not self.roles and self._netbox_ready() and not self.tasks.busy:
self._load_lists()
def set_busy(self, busy):
@@ -261,36 +249,24 @@ class AccessPointsPage(Page):
def work(ctx):
nb = connect(ctx)
ctx.log("Lade Mandanten und Geräterollen …")
tenants = sorted(((item.name, item.id) for item in nb.tenancy.tenants.all()), key=lambda x: x[0].casefold())
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
return tenants, roles
ctx.log("Lade Geräterollen …")
return sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
def done(result):
self.tenants, roles = result
def done(roles):
self.roles = roles
settings = self._settings()
# The tenant is always chosen deliberately – never preselected.
self.tenant.set_items(self.tenants)
role_id = settings.get("role_id") or next(
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
or "access point" in name.casefold()), None)
self.role.set_items(roles, role_id)
if then_compare and self.tenant.valid_data():
if then_compare:
QTimer.singleShot(0, self.compare)
self.tasks.run(work, title="Mandanten laden", area="app", on_success=done,
self.tasks.run(work, title="Geräterollen laden", area="app", on_success=done,
on_error=self.actions._netbox_failed)
def _tenant_chosen(self):
self._store(tenant_id=self.tenant.valid_data())
if self.aps and self.tenant.valid_data():
self.compare()
def compare(self):
tenant_id = self.tenant.valid_data()
if not self.aps or not tenant_id or self.tasks.busy:
if not tenant_id and self.aps:
self.window.toast("Bitte zuerst den Mandanten wählen.", "info")
if not self.aps or self.tasks.busy:
return
connect = self.actions._connector()
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
@@ -299,8 +275,8 @@ class AccessPointsPage(Page):
def work(ctx):
engine = APSyncEngine(connect(ctx), ctx.log)
ctx.log("Lade Standorte und vorhandene Access Points der Mandantengruppe …")
engine.load_context(tenant_id)
ctx.log("Lade Standorte, Mandanten und vorhandene Sophos-Geräte …")
engine.load_context()
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
only_netbox = engine.match(aps)
return engine, aps, only_netbox
@@ -328,14 +304,14 @@ class AccessPointsPage(Page):
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
ap["site_hint"])
if stored:
return dict(placement_value(stored), stored=True)
value = placement_value(stored)
# neither site nor tenant: the user chose to leave these APs out
return dict(value, stored=True, ignored=not value["site"] and not value["tenant"])
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
return {"site": site, "tenant": None, "stored": False}
return {"site": site, "tenant": None, "stored": False, "ignored": False}
def _tenant_for(self, placement):
if placement.get("tenant"):
return placement["tenant"]
return self.engine._site_tenant(placement.get("site")) if self.engine else None
return placement.get("tenant")
def _site_name(self, site_id):
sites = self.engine.ap_sites if self.engine else []
@@ -356,6 +332,8 @@ class AccessPointsPage(Page):
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
related_id(device, "tenant"))
elif self.engine and self._placement(ap)["ignored"]:
site_name = ""
elif self.engine:
placement = self._placement(ap)
site_id = placement["site"] or default_site
@@ -364,11 +342,15 @@ class AccessPointsPage(Page):
tenant_name = self._tenant_name(self._tenant_for(placement))
else:
site_name = ""
state = "new" if not device else ("check" if ap["issues"] else "known")
state = ("ignored" if self.engine and self._placement(ap)["ignored"] else "new") if not device else ("check" if ap["issues"] else "known")
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
netbox_site=site_name, tenant=tenant_name or "",
netbox_device=device.name if device else "", method=ap.get("method", "")))
for device in self.only_netbox:
# NetBox APs missing in the export – only for tenants this export is about
tenants = {related_id(ap["device"], "tenant") for ap in self.aps if ap.get("device")}
tenants |= {self._tenant_for(self._placement(ap)) for ap in self.aps if not ap.get("device")}
tenants.discard(None)
for device in (device for device in self.only_netbox if related_id(device, "tenant") in tenants):
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
"serial": getattr(device, "serial", "") or "", "mac": "",
@@ -385,11 +367,13 @@ class AccessPointsPage(Page):
if self.engine:
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
f"{counts['netbox_only']} nur in NetBox"]
if counts["ignored"]:
parts.append(f"{counts['ignored']} ignoriert")
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
if missing_sites:
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
elif self.aps:
parts.append("Mandant wählen, um mit NetBox abzugleichen" if self._netbox_ready()
parts.append("Abgleich mit NetBox läuft …" if self._netbox_ready()
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
self._update_buttons()
@@ -397,7 +381,7 @@ class AccessPointsPage(Page):
def _update_buttons(self):
busy = self.tasks.busy
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
"Bitte Export laden und Mandanten wählen." if not self.engine else "Bitte warten …")
"Bitte einen Export laden." if not self.engine else "Bitte warten …")
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
@@ -423,8 +407,7 @@ class AccessPointsPage(Page):
if not rows:
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
return False
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
self.tenant.valid_data())
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants)
if not dialog.exec():
return False
settings = self._settings()
@@ -438,14 +421,16 @@ class AccessPointsPage(Page):
def sync(self):
if not self.engine or self.tasks.busy:
return
new = self._new_aps()
new = [ap for ap in self._new_aps() if not self._placement(ap)["ignored"]]
role_id = self.role.valid_data()
if new and not role_id:
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
"info")
return
if any(not self._placement(ap)["stored"] for ap in new) and not self.map_sites():
return
if any(not self._placement(ap)["stored"] for ap in new):
if not self.map_sites():
return
new = [ap for ap in new if not self._placement(ap)["ignored"]]
default_site = self.default_site.valid_data()
placements = {}
for ap in new:
@@ -458,7 +443,8 @@ class AccessPointsPage(Page):
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
"\n".join(homeless))
return
engine, aps, rename = self.engine, list(self.aps), self.rename.isChecked()
engine, rename = self.engine, self.rename.isChecked()
aps = [ap for ap in self.aps if ap.get("device") or ap_key(ap) in placements]
def run(dry_run):
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
+13
View File
@@ -115,3 +115,16 @@ def test_site_is_optional_with_default_site_and_tenant_can_be_chosen():
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
created = nb.dcim.devices.created[-1]
assert (created["site"], created["tenant"]) == (21, 8)
def test_without_tenant_the_whole_netbox_is_searched_and_tenant_comes_from_the_choice():
nb = _netbox()
engine = APSyncEngine(nb)
engine.load_context()
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
assert len(engine.ap_sites) == 2 and len(engine.netbox_aps) == 3
aps = parse_csv(CSV)
engine.match(aps)
assert [ap["device"].id if ap["device"] else None for ap in aps] == [102, 101, None]
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21, "tenant": 7}}, role_id=30, dry_run=False)
assert report["errors"] == [] and nb.dcim.devices.created[-1]["tenant"] == 7