fix(snmp): read the communities over the REST API too
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 56s
driver / test (3.13) (pull_request) Successful in 47s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 1m6s
CI / driver (pull_request) Successful in 2m29s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 56s
driver / test (3.13) (pull_request) Successful in 47s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 1m6s
CI / driver (pull_request) Successful in 2m29s
driver / publish (pull_request) Skipped
get_snmp_config sent "show snmp-server" through the CLI session, which does not exist on the REST transport, and returned None, so every switch managed over REST read as "SNMP not configured". Over REST the command now runs through the API's /cli endpoint and the output goes through the parser the SSH path uses. A failed REST read raises. Closes #10
This commit is contained in:
1 parent
ee49948b2b
commit
b26584c7da
4 files changed
+132
-42
No files matched your search
@@ -27,6 +27,9 @@ All notable changes to this driver. The format follows
|
||||
web page instead of JSON", not as a failed login.
|
||||
- An SSH attempt that failed for another reason than a timeout, such as no common key
|
||||
exchange algorithm, names that reason instead of "timed out".
|
||||
- `get_snmp_config` reads the switch's communities over the REST API too. It returned
|
||||
`None` there, so a switch managed over REST always read as having no SNMP. A read that
|
||||
fails now raises instead of reading as "no SNMP" (REST transport).
|
||||
|
||||
## [0.6.0] - 2026-10-23
|
||||
|
||||
|
||||
+34
-38
@@ -15,6 +15,7 @@ A specific transport can be forced with ``optional_args={"transport": "ssh"}``.
|
||||
Netmiko device type: ``hp_procurve`` / ``hp_procurve_telnet``
|
||||
"""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, ClassVar
|
||||
@@ -34,7 +35,7 @@ from napalm_device_types import (
|
||||
add_lag_interfaces,
|
||||
run_fix_steps,
|
||||
)
|
||||
from napalm_device_types.models import InterfaceConfigDict, VlanConfigDict
|
||||
from napalm_device_types.models import InterfaceConfigDict, SNMPConfigDict, VlanConfigDict
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
KNOWN_KEYS_ARG,
|
||||
OBSERVER_ARG,
|
||||
@@ -1204,47 +1205,42 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
"""Return device warnings. SNMP detection handled by poll task."""
|
||||
return []
|
||||
|
||||
def get_snmp_config(self):
|
||||
"""Return SNMP config if a community is configured on the switch."""
|
||||
try:
|
||||
from napalm_device_types.models import SNMPConfigDict
|
||||
except ImportError:
|
||||
return None
|
||||
def get_snmp_config(self) -> SNMPConfigDict | None:
|
||||
"""The community of the built-in agent, read-only preferred; None without one.
|
||||
|
||||
# Use a single command with short read_timeout to avoid blocking the poll.
|
||||
try:
|
||||
out = (
|
||||
self._device.send_command(
|
||||
"show snmp-server",
|
||||
expect_string=rf"{re.escape(self._device.base_prompt)}[>#]",
|
||||
read_timeout=10,
|
||||
).strip()
|
||||
if self._device
|
||||
else ""
|
||||
)
|
||||
except Exception:
|
||||
Over REST, ``show snmp-server`` runs through the API's ``/cli`` endpoint (#10).
|
||||
"""
|
||||
if self._transport == "api":
|
||||
out = self._api_show("show snmp-server")
|
||||
else:
|
||||
# Use a single command with short read_timeout to avoid blocking the poll.
|
||||
try:
|
||||
out = (
|
||||
self._device.send_command(
|
||||
"show snmp-server",
|
||||
expect_string=rf"{re.escape(self._device.base_prompt)}[>#]",
|
||||
read_timeout=10,
|
||||
)
|
||||
if self._device
|
||||
else ""
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
communities = parsers.parse_snmp_info(out)["community"]
|
||||
if not communities:
|
||||
return None
|
||||
if not out:
|
||||
return None
|
||||
|
||||
# Parse communities from output
|
||||
community = None
|
||||
for line in out.splitlines():
|
||||
m = re.match(r"\s+(\S+)\s+(Manager|Operator)\s+(Restricted|Unrestricted)", line, re.I)
|
||||
if m:
|
||||
comm = m.group(1)
|
||||
access = m.group(3).lower()
|
||||
if access == "restricted": # read-only — prefer this
|
||||
community = comm
|
||||
break
|
||||
elif community is None:
|
||||
community = comm # fallback to first found
|
||||
|
||||
if not community:
|
||||
return None
|
||||
|
||||
read_only = [name for name, c in communities.items() if c["mode"] == "ro"]
|
||||
community = (read_only or list(communities))[0]
|
||||
return SNMPConfigDict(running=True, community=community, port=161, version="2c")
|
||||
|
||||
def _api_show(self, command: str) -> str:
|
||||
"""The output of a show command through the REST API's ``/cli`` endpoint."""
|
||||
resp = self._api.post("cli", json={"cmd": command})
|
||||
if not resp.ok or resp.json().get("status") == "CCS_FAILURE":
|
||||
raise CommandErrorException(f"{command!r} over REST: HTTP {resp.status_code}")
|
||||
encoded = resp.json().get("result_base64_encoded", "")
|
||||
return base64.b64decode(encoded).decode("utf-8", "replace")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -27,9 +27,7 @@
|
||||
"napalm_procurve.procurve"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_procurve/procurve.py": 1396
|
||||
"napalm_procurve/procurve.py": 1392
|
||||
},
|
||||
"untyped_public": [
|
||||
"napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config"
|
||||
]
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""get_snmp_config reads the switch's communities over every transport (#10).
|
||||
|
||||
Over the REST API there is no CLI session, so the getter returned None and a
|
||||
switch managed over REST always read as "SNMP not configured". The API's
|
||||
``/cli`` endpoint runs ``show snmp-server`` and answers with the output in
|
||||
base64, which the SSH path's parser reads.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
SHOW_SNMP_SERVER = """\
|
||||
|
||||
Community Names
|
||||
|
||||
Community Name MIB View Write Access
|
||||
-------------------------------- -------- ------------
|
||||
private Manager Unrestricted
|
||||
c0mm Manager Restricted
|
||||
|
||||
Trap Receivers
|
||||
|
||||
Link-Change Traps Enabled on Ports [All] : All
|
||||
"""
|
||||
|
||||
NO_COMMUNITY = """\
|
||||
|
||||
Community Names
|
||||
|
||||
Community Name MIB View Write Access
|
||||
-------------------------------- -------- ------------
|
||||
"""
|
||||
|
||||
|
||||
def _cli_answer(output: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock:
|
||||
resp = MagicMock(ok=200 <= http < 300, status_code=http, text="")
|
||||
resp.json.return_value = {
|
||||
"cmd": "show snmp-server",
|
||||
"result_base64_encoded": base64.b64encode(output.encode()).decode(),
|
||||
"status": status,
|
||||
}
|
||||
return resp
|
||||
|
||||
|
||||
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
driver._api.post.return_value = resp
|
||||
return driver
|
||||
|
||||
|
||||
def test_over_rest_the_read_only_community_is_read_through_the_cli_endpoint():
|
||||
driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER))
|
||||
|
||||
config = driver.get_snmp_config()
|
||||
|
||||
assert config == {"running": True, "community": "c0mm", "port": 161, "version": "2c"}
|
||||
driver._api.post.assert_called_once_with("cli", json={"cmd": "show snmp-server"})
|
||||
|
||||
|
||||
def test_over_rest_a_switch_without_a_community_has_no_snmp_config():
|
||||
assert _rest_driver(_cli_answer(NO_COMMUNITY)).get_snmp_config() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"resp",
|
||||
[_cli_answer("", http=401), _cli_answer("Invalid input: snmp-server", status="CCS_FAILURE")],
|
||||
)
|
||||
def test_over_rest_a_failed_read_raises_instead_of_reading_as_no_snmp(resp):
|
||||
with pytest.raises(CommandErrorException, match="show snmp-server"):
|
||||
_rest_driver(resp).get_snmp_config()
|
||||
|
||||
|
||||
def test_over_ssh_the_read_only_community_is_preferred():
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "ssh"
|
||||
driver._device = MagicMock(base_prompt="swt")
|
||||
driver._device.send_command.return_value = SHOW_SNMP_SERVER
|
||||
|
||||
assert driver.get_snmp_config() == {
|
||||
"running": True,
|
||||
"community": "c0mm",
|
||||
"port": 161,
|
||||
"version": "2c",
|
||||
}
|
||||
Reference in new issue
Block a user