fix(facts): read the host name from the gateway's System page
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m15s
CI / driver (pull_request) Successful in 2m37s
driver / publish (pull_request) Skipped

get_facts read HostName from getBasicInformation, which a VMG4005-B50A
does not send, and fell back to the address the driver connects to:
netOrk kept the gateway named 192.168.1.1. The gateway's own System page
reads host name and domain with GET /cgi-bin/System?oid=snmp, sealed like
a DAL answer; get_facts now reads them there. fqdn is the host name with
its domain. A gateway with no name set reports "", and get_facts raises
when the System page cannot be read.
This commit is contained in:
Christian Manivong committed 2026-11-12 16:42:47 +01:00
1 parent ca67c08736
commit 61a6e4f7ba
5 files changed
+149 -5

No files matched your search

+6
View File
@@ -13,6 +13,12 @@ All notable changes to this driver. The format follows
3.12 venv no longer has. 3.12 venv no longer has.
### Fixed ### Fixed
- `get_facts()` reports the gateway's host name and domain: `hostname` is the name on
the gateway's System page (`GET /cgi-bin/System?oid=snmp`), `fqdn` that name with its
domain (`VMG4005-B50A.home`). Both were read from `getBasicInformation`, which a
VMG4005-B50A does not send them in, so they fell back to the address the driver
connects to and netOrk kept the device named `192.168.1.1`. A gateway with no name
set reports `""`; `get_facts()` raises when the System page cannot be read.
- `is_alive()` returns `False` without touching the network when the driver has no - `is_alive()` returns `False` without touching the network when the driver has no
open session (never opened, or closed), and with an open session reports whether the open session (never opened, or closed), and with an open session reports whether the
gateway still answers on its port (#19). It connected to the gateway in every case, gateway still answers on its port (#19). It connected to the gateway in every case,
+31 -3
View File
@@ -152,6 +152,7 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
_RSA_KEY_PATH = "getRSAPublickKey" _RSA_KEY_PATH = "getRSAPublickKey"
_BASIC_INFO_PATH = "getBasicInformation" _BASIC_INFO_PATH = "getBasicInformation"
_DAL_PATH = "cgi-bin/DAL" _DAL_PATH = "cgi-bin/DAL"
_SYSTEM_PATH = "cgi-bin/System?oid=snmp"
#: Discovery also fetches the DAL's key exchange, which answers without a login #: Discovery also fetches the DAL's key exchange, which answers without a login
#: (``open()`` needs it). The port answering is no evidence; the answer is (#13). #: (``open()`` needs it). The port answering is no evidence; the answer is (#13).
@@ -351,20 +352,47 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
return parse_page(self._fetch_page(page)) return parse_page(self._fetch_page(page))
def get_facts(self) -> dict[str, Any]: def get_facts(self) -> dict[str, Any]:
"""Return device facts such as model, serial, OS version, and uptime.""" """Return device facts such as model, serial, OS version, and uptime.
The host name and domain are the ones on the gateway's System page;
``getBasicInformation`` does not carry them.
"""
info = self._device_info or {} info = self._device_info or {}
iface_list = list(self.get_interfaces().keys()) iface_list = list(self.get_interfaces().keys())
hostname, domain = self._system_name()
return { return {
"vendor": self.VENDOR, "vendor": self.VENDOR,
"model": info.get("ModelName", ""), "model": info.get("ModelName", ""),
"serial_number": info.get("SerialNumber", ""), "serial_number": info.get("SerialNumber", ""),
"os_version": info.get("SoftwareVersion", ""), "os_version": info.get("SoftwareVersion", ""),
"hostname": info.get("HostName", self.hostname), "hostname": hostname,
"fqdn": self.hostname, "fqdn": f"{hostname}.{domain}" if hostname and domain else hostname,
"uptime": int(info.get("SystemUpTime", 0) or 0), "uptime": int(info.get("SystemUpTime", 0) or 0),
"interface_list": iface_list, "interface_list": iface_list,
} }
def _system_name(self) -> tuple[str, str]:
"""The gateway's host name and domain, as its System page reads them
(``GET /cgi-bin/System?oid=snmp``); raises when they cannot be read.
The answer is a one-entry list, sealed ``{"content", "iv"}`` like a DAL answer.
"""
text = self._fetch_page(self._SYSTEM_PATH)
if self._crypto is None:
raise ConnectionClosedException("Not connected")
try:
answer = json.loads(text)
if isinstance(answer, dict) and {"content", "iv"} <= answer.keys():
answer = self._crypto.decrypt_response(answer)
except (ValueError, TypeError, KeyError) as exc:
raise RuntimeError(f"{self._SYSTEM_PATH} on {self._base_url}: {exc}") from exc
if not isinstance(answer, list) or not answer or not isinstance(answer[0], dict):
raise RuntimeError(f"{self._SYSTEM_PATH} on {self._base_url} answered {answer!r}")
hostname, domain = (
str(answer[0].get(key) or "").strip() for key in ("HostName", "DomainName")
)
return hostname, domain
def _status_page(self) -> dict[str, Any]: def _status_page(self) -> dict[str, Any]:
"""The DAL's ``cardpage_status``, decrypted; raises when it cannot be read. """The DAL's ``cardpage_status``, decrypted; raises when it cannot be read.
+106
View File
@@ -0,0 +1,106 @@
"""The gateway's host name comes from its System page.
``get_facts`` read ``HostName`` from ``getBasicInformation``, which a VMG4005-B50A
(V5.17(ABQA.3.1)C0) does not send, and fell back to the address the driver connects
to: netOrk kept the device named ``192.168.1.1``. The gateway's own Maintenance >
System page reads the name with ``GET /cgi-bin/System?oid=snmp``, sealed like a DAL
answer; the driver now reads it there too.
``BASIC_INFO`` and ``SYSTEM`` are those two answers from that gateway (the SNMP
community strings the System answer can carry are left out).
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
import pytest
import requests
from napalm_zyxel import ZyxelVMGDriver
BASIC_INFO: dict[str, Any] = {
"result": "ZCFG_SUCCESS",
"ModelName": "VMG4005-B50A",
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
"CurrentLanguage": "de",
"AvailableLanguages": "en,cz,it,nl,pt,ru,tr,fr,de,es",
"RememberPassword": 0,
"FWUpgradeProgressST": 0,
}
SYSTEM: list[dict[str, Any]] = [
{"HostName": "VMG4005-B50A", "DomainName": "home", "Location": "Taiwan", "Contact": ""}
]
SEALED = {"content": "SEALED", "iv": "IV"}
def _response(status: int, text: str = "") -> requests.Response:
resp = requests.Response()
resp.status_code = status
resp._content = text.encode()
resp.url = "http://192.168.1.1/"
return resp
def _driver(system: Any) -> ZyxelVMGDriver:
"""A logged-in driver whose gateway answers the System page with *system*, sealed
the way the gateway sends it, or with *system* itself when it is a response."""
driver = ZyxelVMGDriver("192.168.1.1", "admin", "password")
# NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test.
driver.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
reply = system if isinstance(system, requests.Response) else _response(200, json.dumps(SEALED))
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
if url.endswith("cgi-bin/System?oid=snmp"):
return reply
return _response(404)
session = MagicMock(spec=requests.Session)
session.get.side_effect = get
driver._session = session
driver._sessionkey = "1"
driver._crypto = MagicMock()
driver._crypto.decrypt_response.side_effect = lambda data: (
system if data == SEALED else pytest.fail(f"decrypted {data!r}")
)
driver._device_info = BASIC_INFO
driver.get_interfaces = lambda: {"br0": {}} # type: ignore[method-assign] # test_interfaces.py
return driver
def test_the_host_name_is_the_one_on_the_system_page():
assert _driver(SYSTEM).get_facts()["hostname"] == "VMG4005-B50A"
def test_the_fqdn_joins_the_host_name_and_the_domain():
assert _driver(SYSTEM).get_facts()["fqdn"] == "VMG4005-B50A.home"
def test_without_a_domain_the_fqdn_is_the_host_name():
facts = _driver([{**SYSTEM[0], "DomainName": ""}]).get_facts()
assert facts["fqdn"] == "VMG4005-B50A"
def test_a_gateway_without_a_name_reports_none_not_its_address():
facts = _driver([{**SYSTEM[0], "HostName": "", "DomainName": ""}]).get_facts()
assert (facts["hostname"], facts["fqdn"]) == ("", "")
def test_the_page_is_also_read_unsealed():
facts = _driver(_response(200, json.dumps(SYSTEM))).get_facts()
assert facts["hostname"] == "VMG4005-B50A"
def test_get_facts_raises_when_the_system_page_cannot_be_read():
with pytest.raises(RuntimeError, match="System"):
_driver(_response(500)).get_facts()
@pytest.mark.parametrize("answer", [[], {"result": "ZCFG_SUCCESS"}, ["VMG4005-B50A"]])
def test_get_facts_raises_on_a_system_page_it_cannot_read(answer: Any):
with pytest.raises(RuntimeError, match="System"):
_driver(_response(200, json.dumps(answer))).get_facts()
+3 -1
View File
@@ -161,7 +161,9 @@ def test_a_gateway_without_wifi_has_no_wifi_interfaces():
def test_get_facts_lists_the_gateways_interfaces(): def test_get_facts_lists_the_gateways_interfaces():
names = _driver(CARDPAGE).get_facts()["interface_list"] driver = _driver(CARDPAGE)
driver._system_name = lambda: ("VMG4005-B50A", "home") # type: ignore[method-assign] # test_facts.py
names = driver.get_facts()["interface_list"]
assert sorted(names) == ["atm0.1", "br0", "eth1", "ptm0.2"] assert sorted(names) == ["atm0.1", "br0", "eth1", "ptm0.2"]
+3 -1
View File
@@ -11,7 +11,6 @@ MOCK_BASIC_INFO = {
"ModelName": "VMG4005-B50A", "ModelName": "VMG4005-B50A",
"SoftwareVersion": "V5.13(ABKS.1)C0", "SoftwareVersion": "V5.13(ABKS.1)C0",
"SerialNumber": "S220L12345678", "SerialNumber": "S220L12345678",
"HostName": "ZyxelVMG",
"WanIp": "85.2.34.56", "WanIp": "85.2.34.56",
"LanIp": "192.168.1.1", "LanIp": "192.168.1.1",
"MacAddress": "00:1A:2B:3C:4D:5E", "MacAddress": "00:1A:2B:3C:4D:5E",
@@ -87,6 +86,8 @@ class TestZyxelVMGDriver:
return MockResponse(MOCK_BASIC_INFO) return MockResponse(MOCK_BASIC_INFO)
if "getRSAPublickKey" in url: if "getRSAPublickKey" in url:
return MockResponse({"RSAPublicKey": MOCK_RSA_KEY}) return MockResponse({"RSAPublicKey": MOCK_RSA_KEY})
if "cgi-bin/System?oid=snmp" in url: # tests/test_facts.py
return MockResponse([{"HostName": "ZyxelVMG", "DomainName": "home"}])
if "UserLogout" in url: if "UserLogout" in url:
return MockResponse({}) return MockResponse({})
return MockResponse({}) return MockResponse({})
@@ -183,6 +184,7 @@ class TestZyxelVMGDriver:
assert facts["serial_number"] == "S220L12345678" assert facts["serial_number"] == "S220L12345678"
assert facts["os_version"] == "V5.13(ABKS.1)C0" assert facts["os_version"] == "V5.13(ABKS.1)C0"
assert facts["hostname"] == "ZyxelVMG" assert facts["hostname"] == "ZyxelVMG"
assert facts["fqdn"] == "ZyxelVMG.home"
def test_get_wan_status(self): def test_get_wan_status(self):
self._setup_mocked_http() self._setup_mocked_http()