feat: printer import via SNMP v2c/v3 scan with page counter and supplies

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 09:39:50 +01:00
1 parent 05d34e4823
commit 235fb8e26a
12 files changed
+1957 -44

No files matched your search

+33 -14
View File
@@ -141,9 +141,7 @@ class APSyncEngine(ClientSyncEngine):
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 []
self.netbox_aps = self._known_devices({})
return self.ap_sites
tenant = self.nb.tenancy.tenants.get(tenant_id)
if tenant is None:
@@ -161,11 +159,26 @@ class APSyncEngine(ClientSyncEngine):
for site in self.nb.dcim.sites.filter(**scope)), key=lambda row: row["name"].casefold())
self.roles = sorted(((item.name, item.id) for item in self.nb.dcim.device_roles.all()),
key=lambda pair: pair[0].casefold())
self.netbox_aps = self._known_devices(scope)
return self.ap_sites
def _known_devices(self, scope):
"""Devices of this kind in NetBox (``scope`` limits them to the tenant group)."""
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, **scope)) \
if manufacturer else []
return self.ap_sites
return list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id, **scope)) if manufacturer else []
def _identity(self, ap):
"""``(manufacturer, model, platform or None)`` of a new device."""
return MANUFACTURER, ap["model"] or "Access Point", PLATFORM
def _extra_payload(self, ap):
"""Additional fields for a new device."""
return {}
def _extra_updates(self, device, ap):
"""Additional field changes for an existing device: ``(updates, change texts)``."""
return {}, []
def suggest_site(self, hint):
"""NetBox site for a Sophos site name, or ``None`` when unclear."""
@@ -292,11 +305,13 @@ class APSyncEngine(ClientSyncEngine):
if description and (getattr(device, "description", "") or "").startswith("Firmware") \
and device.description != description:
updates["description"] = description
extra, extra_texts = self._extra_updates(device, ap)
updates.update(extra)
if updates:
report["devices_updated"] += 1
changes.append("Aktualisieren: " + ", ".join(
f"{key} → {value}" for key, value in updates.items() if key != "tenant")
+ (" (Mandant ergänzt)" if "tenant" in updates else ""))
[f"{key} → {value}" for key, value in updates.items() if key not in ("tenant", *extra)]
+ extra_texts) + (" (Mandant ergänzt)" if "tenant" in updates else ""))
if not dry_run:
device.update(updates)
else:
@@ -309,19 +324,23 @@ class APSyncEngine(ClientSyncEngine):
"Standard-Standort wählen")
if not role_id:
raise APImportError("keine Geräterolle gewählt")
manufacturer_id = self._manufacturer(MANUFACTURER, report, dry_run)
type_id = self._device_type(MANUFACTURER, manufacturer_id, ap["model"] or "Access Point", report, dry_run)
platform_id = self._platform(PLATFORM, report, dry_run)
manufacturer, model, platform = self._identity(ap)
manufacturer_id = self._manufacturer(manufacturer, report, dry_run)
type_id = self._device_type(manufacturer, manufacturer_id, model, report, dry_run)
platform_id = self._platform(platform, report, dry_run) if platform else None
# An explicitly chosen tenant wins, otherwise the one of the site.
tenant_id = placement.get("tenant") or self._site_tenant(site_id)
payload = {"name": ap["name"], "device_type": type_id, "role": role_id, "site": site_id,
"tenant": tenant_id, "status": "active", "platform": platform_id}
"tenant": tenant_id, "status": "active"}
if platform:
payload["platform"] = platform_id
if ap["serial"]:
payload["serial"] = ap["serial"]
if description:
payload["description"] = description
payload.update(self._extra_payload(ap))
report["devices_created"] += 1
changes.append(f"Gerät anlegen ({ap['model'] or 'Access Point'})")
changes.append(f"Gerät anlegen ({model})")
if dry_run:
if ap["mac"] or ap["ip"]:
report["interfaces_created"] += 1
@@ -379,7 +398,7 @@ class APSyncEngine(ClientSyncEngine):
if not ap["ip"]:
return changes
prefix = self._prefix_for(ap["ip"], tenant_id)
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else "32"
length = str(getattr(prefix, "prefix", "")).split("/")[-1] if prefix else str(ap.get("prefix_length") or 32)
vrf_id = related_id(prefix, "vrf") if prefix else None
address = f"{ap['ip']}/{length}"
where = f" (VRF {getattr(getattr(prefix, 'vrf', None), 'name', vrf_id)})" if vrf_id else ""
+10 -1
View File
@@ -11,7 +11,7 @@ from pathlib import Path
from netbox_sync import CONFIG_DIR_NAME
from netbox_sync.core.clients import DEFAULT_CLIENT_OPTIONS
SECRET_KEYS = ("password", "token_secret")
SECRET_KEYS = ("password", "token_secret", "community", "auth_password", "priv_password")
CONFIG_VERSION = 5
DEFAULT_SETTINGS = {
@@ -127,6 +127,10 @@ def empty_profile(name):
# Sophos AP import: tenant, role, rename option and site choices
# ("site_map": Sophos site -> NetBox site ID, "ap_sites": AP key -> NetBox site ID).
"access_points": {},
# SNMP printer scan: targets, role, site choices and remembered credential per address.
"printers": {},
# SNMP credentials (v2c communities and v3 users) – secrets encrypted.
"snmp_credentials": [],
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -178,11 +182,14 @@ class ProfileStore:
"vlan_map": dict(record.get("vlan_map", {})),
"network_map": dict(record.get("network_map", {})),
"access_points": dict(record.get("access_points", {})),
"printers": dict(record.get("printers", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for credential in record.get("snmp_credentials", []):
profile["snmp_credentials"].append(self._decrypt_record(credential, f"{name}: SNMP"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5/4.6: VLAN and network decisions were stored per switch.
@@ -254,6 +261,8 @@ class ProfileStore:
"vlan_map": dict(profile.get("vlan_map", {})),
"network_map": dict(profile.get("network_map", {})),
"access_points": dict(profile.get("access_points", {})),
"printers": dict(profile.get("printers", {})),
"snmp_credentials": [self._encrypt_record(item) for item in profile.get("snmp_credentials", [])],
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+454
View File
@@ -0,0 +1,454 @@
"""Printers found by an SNMP network scan, documented in NetBox.
Every address is pinged (or probed on the printer ports 9100/515/631), then
queried via SNMP. The credentials of the profile are tried in order – SNMPv2c
communities and SNMPv3 users – and the one that works is remembered per
address. Printers are recognised by the Host Resources MIB (hrDeviceType
printer) or the Printer MIB (RFC 3805), so this works for every manufacturer.
Devices that only answer on printer ports are listed as "printer without SNMP".
The sync reuses the access point import: devices are matched by serial number,
MAC address, name and IP address. Page counter, supplies, colour capability and
the date of the scan are optionally stored in custom fields.
"""
import datetime
import ipaddress
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from netbox_sync.core import netscan, snmp
from netbox_sync.core.ap_sync import CHUNK, APSyncEngine
from netbox_sync.core.netbox import normalize_mac, related_id, version_tuple
PRINTER_PORTS = (9100, 631, 515)
SYS = "1.3.6.1.2.1.1"
SYS_DESCR, SYS_OBJECT_ID, SYS_UPTIME = f"{SYS}.1.0", f"{SYS}.2.0", f"{SYS}.3.0"
SYS_CONTACT, SYS_NAME, SYS_LOCATION = f"{SYS}.4.0", f"{SYS}.5.0", f"{SYS}.6.0"
HR_DEVICE_TYPE = "1.3.6.1.2.1.25.3.2.1.2"
HR_DEVICE_DESCR = "1.3.6.1.2.1.25.3.2.1.3"
HR_PRINTER = "1.3.6.1.2.1.25.3.1.5"
HR_PRINTER_STATUS = "1.3.6.1.2.1.25.3.5.1.1"
HR_PRINTER_ERRORS = "1.3.6.1.2.1.25.3.5.1.2"
PRT_SERIAL = "1.3.6.1.2.1.43.5.1.1.17"
PRT_INPUT = "1.3.6.1.2.1.43.8.2.1"
PRT_LIFE_COUNT = "1.3.6.1.2.1.43.10.2.1.4"
PRT_SUPPLIES = "1.3.6.1.2.1.43.11.1.1"
PRT_COLORANT = "1.3.6.1.2.1.43.12.1.1.4"
PRT_DISPLAY = "1.3.6.1.2.1.43.16.5.1.2"
PRT_ALERT_DESCR = "1.3.6.1.2.1.43.18.1.1.8"
IF_TABLE = "1.3.6.1.2.1.2.2.1"
IP_ADDR_IFINDEX = "1.3.6.1.2.1.4.20.1.2"
IP_ADDR_MASK = "1.3.6.1.2.1.4.20.1.3"
ENT_SOFTWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.10"
ENT_FIRMWARE_REV = "1.3.6.1.2.1.47.1.1.1.1.9"
# IANA enterprise numbers of printer manufacturers (from sysObjectID).
ENTERPRISES = {
11: "HP", 1347: "Kyocera", 2435: "Brother", 367: "Ricoh", 1602: "Canon", 18334: "Konica Minolta",
641: "Lexmark", 253: "Xerox", 1248: "Epson", 2001: "OKI", 674: "Dell", 236: "Samsung", 297: "Fujifilm",
1129: "Toshiba", 2385: "Sharp", 26696: "HP", 2699: "Printer Working Group", 1552: "Utax", 3369: "Sharp",
10642: "Zebra", 683: "Zebra", 5530: "Develop", 4322: "Develop", 15315: "Muratec", 3793: "Panasonic",
}
MANUFACTURER_NAMES = (
"Hewlett-Packard", "HP", "Kyocera", "Brother", "Ricoh", "Canon", "Konica Minolta", "Lexmark", "Xerox", "Epson",
"OKI", "Dell", "Samsung", "Fujifilm", "Fuji Xerox", "Toshiba", "Sharp", "Utax", "TA Triumph-Adler", "Develop",
"Zebra", "Muratec", "Panasonic", "Olivetti", "Kyocera Mita", "Konica", "Minolta", "Nashuatec", "Gestetner",
)
PRINTER_STATUS = {1: "sonstiges", 2: "unbekannt", 3: "bereit", 4: "druckt", 5: "wärmt auf"}
ERROR_BITS = ("wenig Papier", "kein Papier", "wenig Toner", "kein Toner", "Klappe offen", "Papierstau", "offline",
"Service angefordert", "Papierfach fehlt", "Ausgabefach fehlt", "Verbrauchsmaterial fehlt",
"Ausgabefach fast voll", "Ausgabefach voll", "Papierfach leer", "Wartung überfällig")
SUPPLY_TYPES = {3: "Toner", 4: "Resttoner", 5: "Tinte", 6: "Tintenpatrone", 7: "Tintenbehälter", 9: "Trommel",
10: "Entwickler", 15: "Fixiereinheit", 20: "Transfereinheit", 21: "Tonerkassette",
22: "Fixieröl", 32: "Heftklammern"}
CUSTOM_FIELDS = (
("printer_page_count", "Seitenzähler", "integer"),
("printer_supplies", "Verbrauchsmaterial", "longtext"),
("printer_color", "Farbdrucker", "boolean"),
("printer_last_scan", "Letzter Drucker-Scan", "date"),
)
ROLE_HINTS = ("drucker", "printer", "multifunktion", "mfp", "mfd", "multifunction")
class PrinterError(ValueError):
pass
# ----------------------------------------------------------------------
# Reading a printer
# ----------------------------------------------------------------------
def _first(values):
return next((value for _key, value in sorted(values.items(), key=lambda item: snmp.oid_key(item[0]))
if snmp.text(value)), None)
def manufacturer_from(object_id, *texts):
for text in texts:
for name in MANUFACTURER_NAMES:
if re.search(rf"\b{re.escape(name)}\b", text or "", re.IGNORECASE):
return {"Hewlett-Packard": "HP", "Kyocera Mita": "Kyocera", "Fuji Xerox": "Fujifilm",
"Konica": "Konica Minolta", "Minolta": "Konica Minolta"}.get(name, name)
parts = snmp.oid_key(object_id) if object_id else ()
if parts[:6] == (1, 3, 6, 1, 4, 1) and len(parts) > 6:
return ENTERPRISES.get(parts[6], "")
return ""
def clean_model(text, manufacturer):
model = re.sub(r"\s+", " ", snmp.text(text)).strip(" ;,")
model = re.split(r";|,| - |\bFW\b|\bFirmware\b|\bS/N\b", model)[0].strip()
for prefix in (manufacturer, "Hewlett-Packard", "HP", "Kyocera Mita", "Konica Minolta", "KONICA MINOLTA"):
if prefix and model.casefold().startswith(prefix.casefold() + " "):
model = model[len(prefix) + 1:].strip()
return model[:100]
def mac_text(value):
if isinstance(value, bytes) and len(value) == 6 and any(value):
return normalize_mac(value.hex()) or ""
return normalize_mac(snmp.text(value)) or "" if value else ""
def error_flags(value):
if not isinstance(value, bytes):
return []
flags = []
for index, name in enumerate(ERROR_BITS):
byte, bit = divmod(index, 8)
if byte < len(value) and value[byte] & (0x80 >> bit):
flags.append(name)
return flags
def supplies_from(walked, colorants):
"""List of ``{"name", "type", "level", "max", "percent"}`` from prtMarkerSuppliesTable."""
supplies = []
for _index, row in sorted(snmp.table(walked, PRT_SUPPLIES).items()):
name = snmp.text(row.get(6))
kind = SUPPLY_TYPES.get(row.get(5), "")
level, maximum = row.get(9), row.get(8)
if not name and not kind:
continue
colour = colorants.get(row.get(3)) if row.get(3) else ""
percent = None
if isinstance(level, int) and isinstance(maximum, int) and level >= 0 and maximum > 0:
percent = max(0, min(100, round(level * 100 / maximum)))
state = {-3: "vorhanden", -2: "unbekannt", -1: "sonstiges"}.get(level, "") if isinstance(level, int) else ""
if isinstance(level, int) and level >= 0 and maximum in (-1, -2, None):
state = f"{level}"
supplies.append({"name": name or " ".join(filter(None, (kind, colour))), "type": kind, "colour": colour,
"level": level, "max": maximum, "percent": percent, "state": state})
return supplies
def supplies_text(supplies):
lines = []
for item in supplies:
value = f"{item['percent']} %" if item["percent"] is not None else (item["state"] or "–")
lines.append(f"{item['name']}: {value}")
return "\n".join(lines)
def trays_from(walked):
trays = []
for _index, row in sorted(snmp.table(walked, PRT_INPUT).items()):
name = snmp.text(row.get(13)) or snmp.text(row.get(18)) or f"Fach {len(trays) + 1}"
media = snmp.text(row.get(12))
capacity, current = row.get(9), row.get(10)
level = ""
if isinstance(current, int) and isinstance(capacity, int) and capacity > 0 and current >= 0:
level = f"{current}/{capacity} Blatt"
elif current == -3:
level = "Papier vorhanden"
elif current == 0:
level = "leer"
trays.append({"name": name, "media": media, "capacity": capacity if isinstance(capacity, int) else None,
"level": level})
return trays
def read_printer(client, ip):
"""Printer data via SNMP, or ``None`` when the device is no printer."""
base = client.get([SYS_DESCR, SYS_OBJECT_ID, SYS_NAME, SYS_LOCATION, SYS_CONTACT, SYS_UPTIME])
types = client.walk(HR_DEVICE_TYPE, limit=200)
printer_indexes = [snmp.oid_key(oid)[-1] for oid, value in types.items() if value == HR_PRINTER]
serials = client.walk(PRT_SERIAL, limit=20)
counters = client.walk(PRT_LIFE_COUNT, limit=20)
if not printer_indexes and not serials and not counters:
return None
descr = client.get([f"{HR_DEVICE_DESCR}.{index}" for index in printer_indexes]) if printer_indexes else {}
status = client.get([f"{oid}.{index}" for index in printer_indexes[:1]
for oid in (HR_PRINTER_STATUS, HR_PRINTER_ERRORS)]) if printer_indexes else {}
colorants_raw = client.walk(PRT_COLORANT, limit=50)
colorants = {snmp.oid_key(oid)[-1]: snmp.text(value) for oid, value in colorants_raw.items()}
supplies = supplies_from(client.walk(PRT_SUPPLIES, limit=600), colorants)
trays = trays_from(client.walk(PRT_INPUT, limit=600))
display = [snmp.text(value) for value in client.walk(PRT_DISPLAY, limit=20).values() if snmp.text(value)]
alerts = list(dict.fromkeys(snmp.text(value) for value in client.walk(PRT_ALERT_DESCR, limit=100).values()
if snmp.text(value)))
interfaces = snmp.table(client.walk(IF_TABLE, limit=800), IF_TABLE)
addressing = client.get([f"{IP_ADDR_IFINDEX}.{ip}", f"{IP_ADDR_MASK}.{ip}"])
firmware = snmp.text(_first(client.walk(ENT_SOFTWARE_REV, limit=50)) or _first(
client.walk(ENT_FIRMWARE_REV, limit=50)))
sys_descr = snmp.text(base.get(SYS_DESCR))
object_id = base.get(SYS_OBJECT_ID) or ""
model_text = snmp.text(next(iter(descr.values()), "")) if descr else ""
manufacturer = manufacturer_from(object_id, model_text, sys_descr)
model = clean_model(model_text or sys_descr, manufacturer)
if not firmware:
match = re.search(r"(?:firmware|fw|version|ver\.?)\s*[:=]?\s*([\w.\-]+)", sys_descr, re.IGNORECASE)
firmware = match.group(1) if match else ""
if_index = addressing.get(f"{IP_ADDR_IFINDEX}.{ip}")
mac = mac_text(interfaces.get((if_index,), {}).get(6)) if isinstance(if_index, int) else ""
if not mac:
for _index, row in sorted(interfaces.items()):
if row.get(3) in (6, 71, 117) and mac_text(row.get(6)):
mac = mac_text(row.get(6))
break
prefix_length = None
mask = addressing.get(f"{IP_ADDR_MASK}.{ip}")
if isinstance(mask, str):
try:
prefix_length = ipaddress.ip_network(f"0.0.0.0/{mask}").prefixlen
except ValueError:
prefix_length = None
colours = [name for name in colorants.values() if name]
colour = any(name.casefold() not in ("black", "schwarz", "unknown", "other") for name in colours) or any(
item["colour"] and item["colour"].casefold() not in ("black", "schwarz") for item in supplies)
page_count = max((value for value in counters.values() if isinstance(value, int)), default=None)
status_value = status.get(f"{HR_PRINTER_STATUS}.{printer_indexes[0]}") if printer_indexes else None
errors = error_flags(status.get(f"{HR_PRINTER_ERRORS}.{printer_indexes[0]}")) if printer_indexes else []
serial = snmp.text(_first(serials)).upper()
return {
"name": snmp.text(base.get(SYS_NAME)), "sys_descr": sys_descr, "object_id": object_id,
"manufacturer": manufacturer, "model": model, "serial": serial, "firmware": firmware,
"site_hint": snmp.text(base.get(SYS_LOCATION)), "contact": snmp.text(base.get(SYS_CONTACT)),
"uptime": base.get(SYS_UPTIME), "mac": mac, "prefix_length": prefix_length,
"page_count": page_count, "color": bool(colour), "supplies": supplies, "trays": trays,
"status": PRINTER_STATUS.get(status_value, ""), "errors": errors, "display": display, "alerts": alerts,
}
# ----------------------------------------------------------------------
# Scan
# ----------------------------------------------------------------------
def credential_label(record):
try:
return snmp.Credential(record).label
except snmp.SnmpError:
return "ungültig"
def _ordered(credentials, preferred_id):
if not preferred_id:
return list(credentials)
return sorted(credentials, key=lambda record: record.get("id") != preferred_id)
def scan_host(ip, credentials, preferred=None, timeout=1.0):
"""``{"ip", "alive", "printer": bool, ...}`` for one address."""
alive = netscan.ping(ip) is not None
ports = []
if not alive:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if not ports:
return {"ip": ip, "alive": False, "printer": False}
result = {"ip": ip, "alive": True, "printer": False, "snmp": "", "credential_id": None, "notes": []}
try:
client, notes = snmp.connect(ip, _ordered(credentials, (preferred or {}).get(ip)), timeout=timeout)
result["notes"] += notes
info = read_printer(client, ip)
result["snmp"] = client.credential.label
result["credential_id"] = client.credential.record.get("id")
if info:
result.update(info, printer=True)
if not result["mac"]:
result["mac"] = netscan.arp_mac(ip) or ""
return result
except snmp.SnmpAuthError as error:
result["notes"].append(str(error))
except snmp.SnmpError as error:
if not isinstance(error, snmp.SnmpTimeout):
result["notes"].append(f"SNMP-Fehler: {error}")
except OSError as error:
result["notes"].append(f"SNMP-Fehler: {error}")
if result["snmp"]:
return result # answers SNMP but is no printer
if not ports:
ports = [port for port in PRINTER_PORTS if netscan.tcp_open(ip, port, 0.6)]
if 9100 in ports or (631 in ports and 515 in ports):
result.update(printer=True, name=netscan.reverse_dns(ip) or "", mac=netscan.arp_mac(ip) or "",
manufacturer="", model="", serial="", firmware="", site_hint="", supplies=[], trays=[],
page_count=None, color=None, errors=[], display=[], alerts=[], status="",
prefix_length=None)
result["notes"].append("Druckerports offen (" + ", ".join(map(str, ports)) + "), aber keine SNMP-Antwort"
" – Zugangsdaten prüfen")
return result
def scan(ips, credentials, on_result, cancelled=lambda: False, preferred=None, workers=48, timeout=1.0):
if not credentials:
raise PrinterError("Bitte mindestens eine SNMP-Community oder einen SNMPv3-Benutzer hinterlegen.")
for record in credentials:
snmp.Credential(record) # validates protocols early
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(scan_host, ip, credentials, preferred, timeout): ip for ip in ips}
for future in as_completed(futures):
if cancelled():
for pending in futures:
pending.cancel()
break
try:
on_result(future.result())
except Exception as error: # noqa: BLE001 - one host must not stop the scan
on_result({"ip": futures[future], "alive": True, "printer": False, "notes": [str(error)]})
def to_import(host):
"""Scan result → record for the sync (same keys as an access point)."""
name = host.get("name") or netscan.reverse_dns(host["ip"]) or f"Drucker {host['ip']}"
issues = list(host.get("notes", []))
if host.get("errors"):
issues.append("Gerät meldet: " + ", ".join(host["errors"]))
return dict(host, name=re.sub(r"\s+", " ", name).strip()[:64], serial=(host.get("serial") or "").upper(),
mac=normalize_mac(host.get("mac")) or "", issues=issues, site_hint=host.get("site_hint") or "")
def mark_duplicates(printers):
for key, text in (("serial", "Seriennummer"), ("mac", "MAC-Adresse")):
groups = {}
for printer in printers:
if printer.get(key):
groups.setdefault(printer[key], []).append(printer)
for value, members in groups.items():
if len(members) > 1:
for printer in members:
others = ", ".join(other["ip"] for other in members if other is not printer)
printer["issues"].append(f"{text} {value} doppelt (auch {others})")
def printer_key(printer):
return printer.get("serial") or printer.get("mac") or printer["ip"]
# ----------------------------------------------------------------------
# NetBox
# ----------------------------------------------------------------------
class PrinterSyncEngine(APSyncEngine):
"""Access point import with printer identity, IP matching and custom fields."""
def __init__(self, nb, log=None, role_id=None, counters=True):
super().__init__(nb, log)
self.role_id = role_id
self.counters = counters
self.today = datetime.date.today().isoformat()
def _known_devices(self, scope):
if not self.role_id:
return []
return list(self.nb.dcim.devices.filter(role_id=self.role_id, **scope))
def _identity(self, printer):
return printer.get("manufacturer") or "Unbekannt", printer.get("model") or "Drucker", None
def _custom_values(self, printer):
if not self.counters or not printer.get("snmp"):
return {}
values = {"printer_last_scan": self.today}
if printer.get("page_count") is not None:
values["printer_page_count"] = printer["page_count"]
if printer.get("supplies"):
values["printer_supplies"] = supplies_text(printer["supplies"])
if printer.get("color") is not None:
values["printer_color"] = bool(printer["color"])
return values
def _extra_payload(self, printer):
values = self._custom_values(printer)
return {"custom_fields": values} if values else {}
def _extra_updates(self, device, printer):
values = self._custom_values(printer)
current = dict(getattr(device, "custom_fields", None) or {})
changed = {key: value for key, value in values.items() if current.get(key) != value}
if not changed or set(changed) == {"printer_last_scan"} and len(values) > 1:
return {}, []
texts = []
if "printer_page_count" in changed:
texts.append(f"Seitenzähler {current.get('printer_page_count') or '–'} → {changed['printer_page_count']}")
if "printer_supplies" in changed:
texts.append("Verbrauchsmaterial")
if "printer_color" in changed:
texts.append("Farbdrucker" if changed["printer_color"] else "Schwarzweiß")
return {"custom_fields": dict(current, **values)}, texts or ["Scan-Datum"]
def match(self, printers):
"""Base matching plus the IP address assigned to a device interface."""
only_netbox = super().match(printers)
open_items = [printer for printer in printers if printer.get("device") is None and printer.get("ip")]
if not open_items:
return only_netbox
by_ip = {}
ips = sorted({printer["ip"] for printer in open_items})
for start in range(0, len(ips), CHUNK):
for record in self.nb.ipam.ip_addresses.filter(address=ips[start:start + CHUNK]):
if getattr(record, "assigned_object_type", None) != "dcim.interface":
continue
device_id = related_id(getattr(record, "assigned_object", None), "device")
if device_id:
by_ip.setdefault(str(record.address).split("/")[0], set()).add(device_id)
matched = set()
for printer in open_items:
devices = by_ip.get(printer["ip"], set())
if len(devices) == 1:
device = self.nb.dcim.devices.get(next(iter(devices)))
if device is not None:
printer["device"], printer["method"] = device, "IP-Adresse"
matched.add(device.id)
if related_id(device, "tenant") not in self.tenant_ids:
printer["issues"].append("NetBox-Gerät gehört " + (
f"Mandant „{getattr(device.tenant, 'name', '')}“ außerhalb der Mandantengruppe"
if related_id(device, "tenant") else "keinem Mandanten"))
return [device for device in only_netbox if device.id not in matched]
def ensure_custom_fields(self, dry_run, report):
"""Create the printer custom fields that are missing."""
if not self.counters:
return
existing = {field.name for field in self.nb.extras.custom_fields.filter(
name=[name for name, _label, _type in CUSTOM_FIELDS])}
key = "object_types" if version_tuple(self.nb) >= (4, 0) else "content_types"
for name, label, kind in CUSTOM_FIELDS:
if name in existing:
continue
report["changes"].append(f"Benutzerdefiniertes Feld {label} ({name}) anlegen")
report["objects_created"] += 1
if not dry_run:
self.nb.extras.custom_fields.create({
"name": name, "label": label, "type": kind, key: ["dcim.device"], "group_name": "Drucker",
"required": False, "description": "Aus dem SNMP-Drucker-Scan",
})
def sync(self, printers, placements, role_id, rename=True, dry_run=True, default_site=None):
report = self.new_report()
try:
self.ensure_custom_fields(dry_run, report)
except Exception as error: # noqa: BLE001 - devices can still be documented
report["errors"].append(f"Benutzerdefinierte Felder: {error}")
self.counters = False
result = super().sync(printers, placements, role_id, rename, dry_run, default_site)
for key, value in result.items():
if isinstance(value, list):
report[key] = report.get(key, []) + value
else:
report[key] = report.get(key, 0) + value
return report
+540
View File
@@ -0,0 +1,540 @@
"""Small SNMP client (v2c and v3 USM) for reading devices – no external SNMP library.
Supports GET and GETBULK walks. SNMPv3 handles engine discovery, time
synchronisation, authentication (MD5, SHA-1, SHA-224/256/384/512) and privacy
(DES, AES-128 and AES-192/256 with Blumenthal key extension) using the
``cryptography`` package that paramiko already brings along.
"""
import hashlib
import hmac
import itertools
import random
import socket
import struct
import time
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
try: # cryptography >= 43 moved TripleDES (used for single DES with K1=K2=K3)
from cryptography.hazmat.decrepit.ciphers.algorithms import TripleDES
except ImportError: # pragma: no cover - older cryptography
TripleDES = algorithms.TripleDES
PORT = 161
# ASN.1 / SNMP tags
INTEGER, OCTET_STRING, NULL, OID, SEQUENCE = 0x02, 0x04, 0x05, 0x06, 0x30
IP_ADDRESS, COUNTER32, GAUGE32, TIMETICKS, OPAQUE, COUNTER64 = 0x40, 0x41, 0x42, 0x43, 0x44, 0x46
NO_SUCH_OBJECT, NO_SUCH_INSTANCE, END_OF_MIB_VIEW = 0x80, 0x81, 0x82
GET, GET_NEXT, RESPONSE, GET_BULK, REPORT = 0xA0, 0xA1, 0xA2, 0xA5, 0xA8
AUTH_PROTOCOLS = { # name -> (hash, length of the truncated HMAC)
"MD5": (hashlib.md5, 12), "SHA": (hashlib.sha1, 12), "SHA-224": (hashlib.sha224, 16),
"SHA-256": (hashlib.sha256, 24), "SHA-384": (hashlib.sha384, 32), "SHA-512": (hashlib.sha512, 48),
}
PRIV_PROTOCOLS = {"DES": 8, "AES": 16, "AES-192": 24, "AES-256": 32} # name -> key length
REPORT_TEXT = {
"1.3.6.1.6.3.15.1.1.1.0": "Sicherheitsstufe wird nicht unterstützt",
"1.3.6.1.6.3.15.1.1.2.0": "nicht im Zeitfenster",
"1.3.6.1.6.3.15.1.1.3.0": "unbekannter Benutzer",
"1.3.6.1.6.3.15.1.1.4.0": "unbekannte Engine-ID",
"1.3.6.1.6.3.15.1.1.5.0": "falsches Authentifizierungs-Passwort oder -Protokoll",
"1.3.6.1.6.3.15.1.1.6.0": "Entschlüsselung fehlgeschlagen (Privacy-Passwort oder -Protokoll falsch)",
}
class SnmpError(Exception):
"""Base error."""
class SnmpTimeout(SnmpError):
"""No answer – host down, SNMP off or (for v2c) wrong community."""
class SnmpAuthError(SnmpError):
"""The agent answered but rejected the credentials (SNMPv3 report)."""
# ----------------------------------------------------------------------
# BER encoding
# ----------------------------------------------------------------------
def _length(size):
if size < 0x80:
return bytes([size])
raw = size.to_bytes((size.bit_length() + 7) // 8, "big")
return bytes([0x80 | len(raw)]) + raw
def tlv(tag, content):
return bytes([tag]) + _length(len(content)) + content
def enc_int(value, tag=INTEGER):
size = max(1, (value.bit_length() + 8) // 8)
return tlv(tag, value.to_bytes(size, "big", signed=True))
def enc_str(value):
return tlv(OCTET_STRING, value if isinstance(value, bytes) else str(value).encode())
def enc_oid(oid):
parts = [int(part) for part in str(oid).strip(".").split(".")]
body = bytearray([parts[0] * 40 + parts[1]])
for part in parts[2:]:
chunk = [part & 0x7F]
part >>= 7
while part:
chunk.append(0x80 | (part & 0x7F))
part >>= 7
body += bytes(reversed(chunk))
return tlv(OID, bytes(body))
def seq(*items):
return tlv(SEQUENCE, b"".join(items))
def decode(data, pos=0):
"""``(tag, content, next position)`` of the TLV at ``pos``."""
if pos + 2 > len(data):
raise SnmpError("Antwort unvollständig")
tag, size = data[pos], data[pos + 1]
pos += 2
if size & 0x80:
count = size & 0x7F
size = int.from_bytes(data[pos:pos + count], "big")
pos += count
if pos + size > len(data):
raise SnmpError("Antwort unvollständig")
return tag, data[pos:pos + size], pos + size
def children(content):
items, pos = [], 0
while pos < len(content):
tag, value, pos = decode(content, pos)
items.append((tag, value))
return items
def dec_oid(content):
first = content[0]
parts = [first // 40 if first < 80 else 2, first % 40 if first < 80 else first - 80]
value = 0
for byte in content[1:]:
value = (value << 7) | (byte & 0x7F)
if not byte & 0x80:
parts.append(value)
value = 0
return ".".join(map(str, parts))
def dec_value(tag, content):
if tag == INTEGER:
return int.from_bytes(content, "big", signed=True)
if tag in (COUNTER32, GAUGE32, TIMETICKS, COUNTER64):
return int.from_bytes(content, "big")
if tag == OID:
return dec_oid(content)
if tag == IP_ADDRESS:
return ".".join(str(byte) for byte in content)
if tag in (OCTET_STRING, OPAQUE):
return bytes(content)
return None # NULL, noSuchObject, noSuchInstance, endOfMibView
def oid_key(oid):
return tuple(int(part) for part in oid.strip(".").split("."))
def in_subtree(oid, root):
return oid_key(oid)[:len(oid_key(root))] == oid_key(root)
def text(value):
"""OCTET STRING as readable text (trailing NULs and control characters removed)."""
if value is None:
return ""
if isinstance(value, bytes):
for encoding in ("utf-8", "cp1252"):
try:
value = value.decode(encoding)
break
except UnicodeDecodeError:
continue
return "".join(char for char in str(value) if char.isprintable()).strip()
# ----------------------------------------------------------------------
# PDUs
# ----------------------------------------------------------------------
def _pdu(kind, request_id, oids, non_repeaters=0, max_repetitions=0):
varbinds = seq(*(seq(enc_oid(oid), tlv(NULL, b"")) for oid in oids))
return tlv(kind, enc_int(request_id) + enc_int(non_repeaters) + enc_int(max_repetitions) + varbinds)
def _parse_pdu(tag, content):
request_id, status, index, varbinds = children(content)
bindings = []
for _tag, binding in children(varbinds[1]):
(_oid_tag, oid_raw), (value_tag, value_raw) = children(binding)
bindings.append((dec_oid(oid_raw), value_tag, dec_value(value_tag, value_raw)))
return {"type": tag, "request_id": dec_value(INTEGER, request_id[1]), "error_status": dec_value(INTEGER, status[1]),
"error_index": dec_value(INTEGER, index[1]), "varbinds": bindings}
# ----------------------------------------------------------------------
# SNMPv3 keys and crypto
# ----------------------------------------------------------------------
_KEY_CACHE = {}
def aes_cfb(key, iv, data, decrypt=False):
"""AES-CFB128 (RFC 3826) built on ECB – the CFB mode of ``cryptography`` is being deprecated."""
encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
out, register = bytearray(), iv
for start in range(0, len(data), 16):
block = data[start:start + 16]
stream = encryptor.update(register)
chunk = bytes(a ^ b for a, b in zip(block, stream))
out += chunk
register = (block if decrypt else chunk).ljust(16, b"\0")
return bytes(out)
def password_to_key(password, hash_func):
"""RFC 3414 A.2: hash of the password repeated to 1 MB."""
key = (password, hash_func().name)
if key not in _KEY_CACHE:
data = password.encode()
if not data:
raise SnmpError("leeres SNMPv3-Passwort")
digest = hash_func()
repeated = (data * (64 // len(data) + 2))
chunk = (repeated * (1048576 // len(repeated) + 1))[:1048576]
digest.update(chunk)
_KEY_CACHE[key] = digest.digest()
return _KEY_CACHE[key]
def localize(key, engine_id, hash_func):
return hash_func(key + engine_id + key).digest()
def priv_key(password, engine_id, hash_func, size):
key = localize(password_to_key(password, hash_func), engine_id, hash_func)
while len(key) < size: # Blumenthal key extension for AES-192/256
key += hash_func(key).digest()
return key[:size] if size > 8 else key[:16] # DES needs key + pre-IV
class Credential:
"""One set of credentials: ``{"version": "2c", "community": …}`` or a v3 user."""
def __init__(self, record):
self.record = record
self.version = str(record.get("version") or "2c")
self.community = record.get("community") or "public"
self.username = record.get("username") or ""
self.auth_protocol = record.get("auth_protocol") or ""
self.auth_password = record.get("auth_password") or ""
self.priv_protocol = record.get("priv_protocol") or ""
self.priv_password = record.get("priv_password") or ""
self.context = record.get("context") or ""
if self.version == "3":
if self.auth_protocol and self.auth_protocol not in AUTH_PROTOCOLS:
raise SnmpError(f"unbekanntes Authentifizierungs-Protokoll {self.auth_protocol}")
if self.priv_protocol and self.priv_protocol not in PRIV_PROTOCOLS:
raise SnmpError(f"unbekanntes Privacy-Protokoll {self.priv_protocol}")
if self.priv_protocol and not self.auth_protocol:
raise SnmpError("Privacy ohne Authentifizierung ist bei SNMPv3 nicht möglich")
@property
def label(self):
if self.version != "3":
return "SNMPv2c"
level = ("authPriv" if self.priv_protocol else "authNoPriv") if self.auth_protocol else "noAuthNoPriv"
return f"SNMPv3 {self.username} ({level})"
# ----------------------------------------------------------------------
# Client
# ----------------------------------------------------------------------
_ids = itertools.count(random.randint(1, 1 << 30))
class SnmpClient:
def __init__(self, host, credential, timeout=1.0, retries=1, port=PORT):
self.host, self.port = host, port
self.credential = credential if isinstance(credential, Credential) else Credential(credential)
self.timeout, self.retries = timeout, retries
self.engine_id = b""
self.boots = self.engine_time = 0
self._time_base = 0.0
self._salt = random.getrandbits(64)
self.bulk = True
# transport ----------------------------------------------------------
def _exchange(self, packet, accept):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(self.timeout)
for _attempt in range(self.retries + 1):
try:
sock.sendto(packet, (self.host, self.port))
except OSError as error:
raise SnmpTimeout(str(error)) from error
deadline = time.monotonic() + self.timeout
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
sock.settimeout(remaining)
try:
data, _addr = sock.recvfrom(65535)
except (socket.timeout, ConnectionResetError):
break
except OSError:
break
try:
result = accept(data)
except SnmpAuthError:
raise
except (SnmpError, ValueError, IndexError):
continue
if result is not None:
return result
raise SnmpTimeout(f"{self.host}: keine SNMP-Antwort")
# v2c ----------------------------------------------------------------
def _request_v2(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
request_id = next(_ids) & 0x7FFFFFFF
community = self.credential.community.encode()
packet = seq(enc_int(1), enc_str(community), _pdu(pdu_type, request_id, oids, non_repeaters, max_repetitions))
def accept(data):
_tag, content, _pos = decode(data)
version, community_raw, (pdu_tag, pdu_content) = children(content)
if community_raw[1] != community:
return None
pdu = _parse_pdu(pdu_tag, pdu_content)
return pdu if pdu["request_id"] == request_id else None
return self._exchange(packet, accept)
# v3 -----------------------------------------------------------------
def _hash(self):
return AUTH_PROTOCOLS[self.credential.auth_protocol][0] if self.credential.auth_protocol else None
def _discover(self):
msg_id = next(_ids) & 0x7FFFFFFF
usm = seq(enc_str(b""), enc_int(0), enc_int(0), enc_str(b""), enc_str(b""), enc_str(b""))
scoped = seq(enc_str(b""), enc_str(b""), _pdu(GET, msg_id, []))
packet = seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(b"\x04"), enc_int(3)),
enc_str(usm), scoped)
message = self._exchange(packet, lambda data: self._parse_v3(data, msg_id, verify=False))
if not message["engine_id"]:
raise SnmpError(f"{self.host}: keine SNMPv3-Engine-ID erhalten")
self._set_engine(message)
def _set_engine(self, message):
self.engine_id = message["engine_id"]
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
hash_func = self._hash()
cred = self.credential
self._auth_key = localize(password_to_key(cred.auth_password, hash_func), self.engine_id, hash_func) \
if hash_func else None
self._priv_key = priv_key(cred.priv_password, self.engine_id, hash_func, PRIV_PROTOCOLS[cred.priv_protocol]) \
if cred.priv_protocol else None
def _now(self):
return self.engine_time + int(time.monotonic() - self._time_base)
def _encrypt(self, plain, now):
cred = self.credential
self._salt = (self._salt + 1) & 0xFFFFFFFFFFFFFFFF
if cred.priv_protocol == "DES":
salt = struct.pack(">II", self.boots & 0xFFFFFFFF, self._salt & 0xFFFFFFFF)
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
plain += b"\x00" * (-len(plain) % 8)
encryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).encryptor()
else:
salt = struct.pack(">Q", self._salt)
iv = struct.pack(">II", self.boots, now) + salt
return aes_cfb(self._priv_key, iv, plain), salt
return encryptor.update(plain) + encryptor.finalize(), salt
def _decrypt(self, data, salt, boots, engine_time):
if self.credential.priv_protocol == "DES":
iv = bytes(a ^ b for a, b in zip(self._priv_key[8:16], salt))
decryptor = Cipher(TripleDES(self._priv_key[:8] * 3), modes.CBC(iv)).decryptor()
else:
iv = struct.pack(">II", boots, engine_time) + salt
return aes_cfb(self._priv_key, iv, data, decrypt=True)
return decryptor.update(data) + decryptor.finalize()
def _parse_v3(self, data, msg_id, verify=True):
_tag, content, _pos = decode(data)
version, header, (_usm_tag, usm_raw), (data_tag, data_raw) = children(content)
if dec_value(INTEGER, version[1]) != 3:
raise SnmpError("keine SNMPv3-Antwort")
header_items = children(header[1])
if dec_value(INTEGER, header_items[0][1]) != msg_id:
return None
flags = header_items[2][1][0] if header_items[2][1] else 0
_t, usm_content, _p = decode(usm_raw)
engine_id, boots, engine_time, user, auth_params, priv_params = (item[1] for item in children(usm_content))
message = {"engine_id": bytes(engine_id), "boots": dec_value(INTEGER, boots),
"time": dec_value(INTEGER, engine_time)}
if verify and flags & 0x01 and self._auth_key:
hash_func, size = AUTH_PROTOCOLS[self.credential.auth_protocol]
position = data.find(auth_params)
zeroed = data[:position] + b"\x00" * len(auth_params) + data[position + len(auth_params):]
if hmac.new(self._auth_key, zeroed, hash_func).digest()[:size] != auth_params:
raise SnmpError("Antwort mit ungültiger Signatur")
if data_tag == OCTET_STRING:
if not self._priv_key:
raise SnmpError("verschlüsselte Antwort ohne Privacy-Schlüssel")
plain = self._decrypt(bytes(data_raw), bytes(priv_params), message["boots"], message["time"])
_t, scoped, _p = decode(plain)
else:
scoped = data_raw
_context_engine, _context_name, (pdu_tag, pdu_content) = children(scoped)
message["pdu"] = _parse_pdu(pdu_tag, pdu_content)
return message
def _request_v3(self, pdu_type, oids, non_repeaters=0, max_repetitions=0, resync=True):
if not self.engine_id:
self._discover()
cred = self.credential
msg_id = next(_ids) & 0x7FFFFFFF
pdu = _pdu(pdu_type, msg_id, oids, non_repeaters, max_repetitions)
scoped = seq(enc_str(self.engine_id), enc_str(cred.context), pdu)
flags = 0x04 | (0x01 if cred.auth_protocol else 0) | (0x02 if cred.priv_protocol else 0)
salt, now = b"", self._now()
if cred.priv_protocol:
encrypted, salt = self._encrypt(scoped, now)
body = enc_str(encrypted)
else:
body = scoped
auth_size = AUTH_PROTOCOLS[cred.auth_protocol][1] if cred.auth_protocol else 0
def build(auth_params):
usm = seq(enc_str(self.engine_id), enc_int(self.boots), enc_int(now), enc_str(cred.username),
enc_str(auth_params), enc_str(salt))
return seq(enc_int(3), seq(enc_int(msg_id), enc_int(65507), enc_str(bytes([flags])), enc_int(3)),
enc_str(usm), body)
packet = build(b"\x00" * auth_size)
if cred.auth_protocol:
hash_func, size = AUTH_PROTOCOLS[cred.auth_protocol]
packet = build(hmac.new(self._auth_key, packet, hash_func).digest()[:size])
def accept(data):
return self._parse_v3(data, msg_id)
message = self._exchange(packet, accept)
pdu = message["pdu"]
if pdu["type"] == REPORT:
oid = pdu["varbinds"][0][0] if pdu["varbinds"] else ""
if oid == "1.3.6.1.6.3.15.1.1.2.0" and resync: # not in time window: resynchronise once
self.boots, self.engine_time = message["boots"], message["time"]
self._time_base = time.monotonic()
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions, resync=False)
raise SnmpAuthError(f"SNMPv3 {cred.username}: {REPORT_TEXT.get(oid, 'abgelehnt (' + oid + ')')}")
return pdu
# public API ---------------------------------------------------------
def request(self, pdu_type, oids, non_repeaters=0, max_repetitions=0):
if self.credential.version == "3":
return self._request_v3(pdu_type, oids, non_repeaters, max_repetitions)
return self._request_v2(pdu_type, oids, non_repeaters, max_repetitions)
def get(self, oids):
"""``{oid: value}``; missing objects are left out."""
result = {}
oids = list(oids)
for start in range(0, len(oids), 20):
pdu = self.request(GET, oids[start:start + 20])
if pdu["error_status"]:
# v1-style error for one bad OID: fall back to single requests
for oid in oids[start:start + 20]:
single = self.request(GET, [oid])
if not single["error_status"]:
result.update({o: v for o, tag, v in single["varbinds"] if tag < NO_SUCH_OBJECT})
continue
result.update({oid: value for oid, tag, value in pdu["varbinds"] if tag < NO_SUCH_OBJECT})
return result
def walk(self, root, limit=2000):
"""``{oid: value}`` of the subtree below ``root``."""
result, current = {}, root
while len(result) < limit:
if self.bulk:
pdu = self.request(GET_BULK, [current], 0, 25)
if pdu["error_status"]:
self.bulk = False
continue
else:
pdu = self.request(GET_NEXT, [current])
if pdu["error_status"]:
break
if not pdu["varbinds"]:
break
done = False
for oid, tag, value in pdu["varbinds"]:
if tag == END_OF_MIB_VIEW or not in_subtree(oid, root) or oid_key(oid) <= oid_key(current):
done = True
break
result[oid] = value
current = oid
if done:
break
return result
def connect(host, credentials, timeout=1.0, retries=1, check_oid="1.3.6.1.2.1.1.2.0", port=PORT):
"""First credential that works for ``host``: ``(client, notes)``.
``notes`` collects why other credentials failed (e.g. a wrong v3 password),
which helps to spot misconfigured devices. Raises ``SnmpTimeout`` when no
credential got an answer.
"""
notes = []
for record in credentials:
try:
client = SnmpClient(host, record, timeout, retries, port)
if client.get([check_oid]):
return client, notes
notes.append(f"{client.credential.label}: keine Daten")
except SnmpAuthError as error:
notes.append(str(error))
except SnmpTimeout:
continue
except SnmpError as error:
notes.append(str(error))
if notes:
raise SnmpAuthError("; ".join(notes))
raise SnmpTimeout(f"{host}: keine SNMP-Antwort")
def table(walked, root):
"""Group a walked table by row index: ``{index tuple: {column: value}}``."""
rows = {}
base = len(oid_key(root))
for oid, value in walked.items():
key = oid_key(oid)
if len(key) <= base + 1:
continue
rows.setdefault(key[base + 1:], {})[key[base]] = value
return rows