fix: what bandit and the remaining lint rules found

- The six except Exception: pass (REST logout, the extra-ports lookup, the
  per-port detail in get_interfaces, closing CLI and REST sessions) now log
  at debug level (B110), so a swallowed failure leaves a trace.
- nosec for comparing a reported address with 0.0.0.0 (B104) and for the
  empty password field of get_users (B105, now a named constant); both are
  false positives.
- A long error message is split into adjacent f-strings; the unused ARP
  entry type is named _entry_type.
- tests: the failed-open test expects ConnectionException instead of any
  Exception; raise ... from exc.
This commit is contained in:
Christian Manivong committed 2026-10-23 08:34:55 +02:00
1 parent c2a788fa7a
commit fc24495b83
5 files changed
+19 -13

No files matched your search

+4 -3
View File
@@ -149,7 +149,7 @@ class ProcurveApiClient:
try: try:
self._session.delete(self._base_url + "login-sessions", timeout=self.timeout) self._session.delete(self._base_url + "login-sessions", timeout=self.timeout)
except Exception: except Exception:
pass logger.debug("REST API logout: ignored", exc_info=True)
if self._session: if self._session:
self._session.close() self._session.close()
self._session = None self._session = None
@@ -283,7 +283,7 @@ class ProcurveApiClient:
) )
seen_ids.add(pid) seen_ids.add(pid)
except Exception: except Exception:
pass logger.debug("system/status/switch for missing ports: ignored", exc_info=True)
for port in port_elements: for port in port_elements:
pid = port.get("id", "") pid = port.get("id", "")
@@ -330,7 +330,8 @@ class ProcurveApiClient:
for entry in ipv4_data.get("ipv4_element", []): for entry in ipv4_data.get("ipv4_element", []):
addr = entry.get("address", "") addr = entry.get("address", "")
mask = entry.get("mask", "") mask = entry.get("mask", "")
if not addr or addr == "0.0.0.0": # An unset address reported by the switch, not a bind address.
if not addr or addr == "0.0.0.0": # nosec B104
continue continue
try: try:
import netaddr import netaddr
+7 -3
View File
@@ -9,6 +9,9 @@ backends.
import re import re
#: get_users' password field: the switch never shows a password, so it stays empty.
_PASSWORD_NOT_SHOWN = "" # nosec B105
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# MAC address helpers # MAC address helpers
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -330,7 +333,8 @@ def parse_ip_interfaces(output: str) -> dict[str, dict]:
# Single VLAN output (no header): detect from "IP Address" line # Single VLAN output (no header): detect from "IP Address" line
if re.search(r"IP\s+Address\s*:", line, re.I): if re.search(r"IP\s+Address\s*:", line, re.I):
ip = line.split(":", 1)[-1].strip() ip = line.split(":", 1)[-1].strip()
if ip and ip not in ("0.0.0.0", ""): # An unset address reported by the switch, not a bind address.
if ip and ip != "0.0.0.0": # nosec B104
current_ip = ip current_ip = ip
if not current_vlan: if not current_vlan:
current_vlan = "VLAN1" current_vlan = "VLAN1"
@@ -375,7 +379,7 @@ def parse_arp_table(output: str) -> list[dict]:
m = _ARP_RE.search(line) m = _ARP_RE.search(line)
if not m: if not m:
continue continue
ip, mac, entry_type, port = (m.group(1), m.group(2), m.group(3), m.group(4) or "") ip, mac, _entry_type, port = (m.group(1), m.group(2), m.group(3), m.group(4) or "")
table.append( table.append(
{ {
"interface": port, "interface": port,
@@ -665,7 +669,7 @@ def parse_users(output: str) -> dict[str, dict]:
priv = 1 priv = 1
users[uname] = { users[uname] = {
"level": priv, "level": priv,
"password": "", "password": _PASSWORD_NOT_SHOWN,
"sshkeys": [], "sshkeys": [],
} }
return users return users
+6 -5
View File
@@ -238,7 +238,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
try: try:
self._device.disconnect() self._device.disconnect()
except Exception: except Exception:
pass logger.debug("closing the CLI session: ignored", exc_info=True)
self._device = None self._device = None
self._transport = None self._transport = None
@@ -556,7 +556,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
if detail.get("description"): if detail.get("description"):
ifaces[port]["description"] = detail["description"] ifaces[port]["description"] = detail["description"]
except Exception: except Exception:
pass logger.debug("show interfaces %s: ignored", port, exc_info=True)
# The CLI lists member ports only ("3-Trk3"); the trunk gets its own row. # The CLI lists member ports only ("3-Trk3"); the trunk gets its own row.
return add_lag_interfaces(ifaces) return add_lag_interfaces(ifaces)
@@ -643,7 +643,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
try: try:
self._api._session.close() self._api._session.close()
except Exception: except Exception:
pass logger.debug("closing the REST session: ignored", exc_info=True)
running = self._get_config_via_ssh() running = self._get_config_via_ssh()
return {"running": running, "startup": "", "candidate": ""} return {"running": running, "startup": "", "candidate": ""}
@@ -971,7 +971,8 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
resp = self._api.put(f"ports/{interface}", json=patch) resp = self._api.put(f"ports/{interface}", json=patch)
if not resp.ok: if not resp.ok:
raise ConnectionException( raise ConnectionException(
f"set_interface({interface}): ports PUT HTTP {resp.status_code} – {resp.text[:200]}" f"set_interface({interface}): ports PUT HTTP {resp.status_code} – "
f"{resp.text[:200]}"
) )
mode = config.get("mode") mode = config.get("mode")
if mode == "trunk": if mode == "trunk":
@@ -1286,7 +1287,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
try: try:
self._device.disconnect() self._device.disconnect()
except Exception: # noqa: BLE001 - closing a temporary session except Exception: # noqa: BLE001 - closing a temporary session
pass logger.debug("closing the temporary CLI session: ignored", exc_info=True)
self._api, self._device, self._transport = old_api, old_device, old_transport self._api, self._device, self._transport = old_api, old_device, old_transport
def _snmp_configure_cli(self, settings: dict[str, Any]) -> dict[str, Any]: def _snmp_configure_cli(self, settings: dict[str, Any]) -> dict[str, Any]:
+1 -1
View File
@@ -535,7 +535,7 @@ class TestDriverTransportDetection:
with patch("napalm_procurve.procurve.ProcurveApiClient.probe", return_value=(None, None)): with patch("napalm_procurve.procurve.ProcurveApiClient.probe", return_value=(None, None)):
with patch("napalm_procurve.procurve.ConnectHandler", side_effect=Exception("no conn")): with patch("napalm_procurve.procurve.ConnectHandler", side_effect=Exception("no conn")):
drv = ProcurveDriver("192.168.0.1", "manager", "secret") drv = ProcurveDriver("192.168.0.1", "manager", "secret")
with pytest.raises(Exception): with pytest.raises(ConnectionException):
drv.open() drv.open()
def test_auth_failure_names_why_earlier_transports_failed(self): def test_auth_failure_names_why_earlier_transports_failed(self):
+1 -1
View File
@@ -43,7 +43,7 @@ def _refuse(**kwargs):
try: try:
raise paramiko.BadHostKeyException("10.0.0.4", SERVER_KEY, OTHER_KEY) raise paramiko.BadHostKeyException("10.0.0.4", SERVER_KEY, OTHER_KEY)
except paramiko.SSHException as exc: except paramiko.SSHException as exc:
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
def _driver(seen: list, known: dict | None = None, **extra) -> ProcurveDriver: def _driver(seen: list, known: dict | None = None, **extra) -> ProcurveDriver: