feat: set_hostname renames the host (#45)
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m14s
CI / driver (pull_request) Successful in 1m15s
driver / publish (pull_request) Skipped

netOrk could save a Linux host's new name but not apply it: the driver had
no set_hostname(), so apply-hostname answered "The driver linux does not
support set_hostname()".

HostnameMixin.set_hostname() takes a bare name or an FQDN. The short name
goes to hostnamectl, or to /etc/hostname and hostname(1) without systemd.
/etc/hosts follows: every line naming the old name, else the 127.0.1.1
line; a file with neither is left alone. A cloud-init host gets
preserve_hostname: true, or its next boot restores the image's name.
Names that are not RFC 1123 hostnames are refused before anything runs.
Files are staged unprivileged and installed by root
(_install_file_as_root), never written from privileged stdin.

It lives in its own module because linux.py may not grow (quality
ratchet); the two lines it adds there are offset by a stale comment and
an import that fits on one line, so the baseline drops to 2286.
This commit is contained in:
Christian Manivong committed 2026-10-29 21:57:40 +01:00
1 parent b6677c9fc5
commit 4108eb83dd
5 files changed
+446 -6

No files matched your search

+8
View File
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- `set_hostname()` (#45): netOrk could save a Linux host's new name but not apply it
("The driver linux does not support set_hostname()"). The host now takes the short
name through `hostnamectl`, or `/etc/hostname` and `hostname(1)` without systemd;
`/etc/hosts` follows (the lines naming the old name, else the `127.0.1.1` line), and a
cloud-init host gets `preserve_hostname: true` so its next boot keeps the name. Names
that are not valid hostnames are refused before anything runs on the host.
### Changed
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
+145
View File
@@ -0,0 +1,145 @@
"""Renaming the host: static and runtime hostname, ``/etc/hosts``, cloud-init (#45)."""
from __future__ import annotations
import re
from shlex import quote as _shlex_quote
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from napalm_device_types import CommandResult
from napalm_device_types.models import FixStepOutcomeDict
#: One label of a hostname (RFC 1123): letters, digits and inner hyphens. It
#: also keeps every name ``set_hostname`` accepts safe in a root shell.
_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$")
#: Names ``/etc/hosts`` keeps whatever the host was called.
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain"})
#: What the host is called before the rename: its short name and its FQDN.
_OLD_NAME_COMMANDS = ("hostname", "hostname -f 2>/dev/null")
#: Without this, cloud-init's ``update_hostname`` puts the image's name back on
#: the next boot.
_CLOUD_INIT_PRESERVE = "/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg"
_CLOUD_INIT_PRESERVE_CONTENT = (
"# The hostname was set on purpose: keep it across reboots.\npreserve_hostname: true\n"
)
def _split_hostname(name: str) -> tuple[str, str | None]:
"""``(short name, FQDN or None)`` of *name*.
:raises ValueError: when *name* is not a valid hostname or FQDN.
"""
labels = name.split(".")
if len(name) > 253 or not all(_LABEL_RE.match(label) for label in labels):
raise ValueError(f"not a valid hostname: {name!r}")
return labels[0], (name if len(labels) > 1 else None)
def _renamed_line(line: str, targets: set[str], new: list[str]) -> str | None:
"""*line* of ``/etc/hosts`` with *new* where the first of *targets* stood.
The other names on it stay; ``None`` when the line names none of *targets*.
"""
entry, hash_, comment = line.partition("#")
address, *names = entry.split() or [""]
if not any(n.lower() in targets for n in names):
return None
result: list[str] = []
inserted = False
for name in names:
if name.lower() not in targets:
result.append(name)
elif not inserted:
result += new
inserted = True
tail = f" {hash_}{comment}" if hash_ else ""
return f"{address}\t{' '.join(dict.fromkeys(result))}{tail}"
def _rename_in_hosts(content: str, old_names: set[str], short: str, fqdn: str | None) -> str:
"""*content* of ``/etc/hosts`` with the host's old names replaced by the new.
Every line naming the host gets the new names. When no line names it, the
Debian ``127.0.1.1`` line takes them; a file with neither is returned
unchanged -- nothing is appended to a host that never listed itself.
"""
old = {n.lower() for n in old_names} - _LOOPBACK_NAMES
new = [fqdn, short] if fqdn else [short]
lines = content.split("\n")
renamed = [_renamed_line(line, old, new) for line in lines]
if all(r is None for r in renamed):
renamed = _renamed_self_line(lines, new)
return "\n".join(r or line for line, r in zip(lines, renamed, strict=True))
def _renamed_self_line(lines: list[str], new: list[str]) -> list[str | None]:
"""The first ``127.0.1.1`` line of *lines* naming *new* instead, the rest ``None``."""
result: list[str | None] = [None] * len(lines)
for i, line in enumerate(lines):
address, *names = line.partition("#")[0].split() or [""]
if address == "127.0.1.1" and names:
result[i] = _renamed_line(line, {n.lower() for n in names}, new)
break
return result
class HostnameMixin:
"""``set_hostname`` for a Linux host, over the driver's command channel."""
if TYPE_CHECKING:
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult: ...
def _install_file_as_root(self, path: str, content: str) -> CommandResult: ...
def _root_outcome(self, command: str, timeout: float, done: str) -> FixStepOutcomeDict: ...
def set_hostname(self, new_hostname: str) -> None:
"""Rename the host: static and runtime hostname, ``/etc/hosts``, cloud-init.
Takes a bare name or an FQDN; the hostname itself is the short name, and
an FQDN goes to ``/etc/hosts`` in front of it. ``hostnamectl`` sets it
where there is one, otherwise ``/etc/hostname`` and ``hostname(1)``.
Files are installed from a staged copy (``_install_file_as_root``).
:raises ValueError: for a name that is not a valid hostname, before
anything runs on the host.
:raises RuntimeError: when the host refuses a step; the steps before it
stay done.
"""
short, fqdn = _split_hostname(new_hostname)
old_names = {self.run_command(c, timeout=30).stdout.strip() for c in _OLD_NAME_COMMANDS}
hosts = self.run_command("cat /etc/hosts", timeout=30)
name = _shlex_quote(short)
outcome = self._root_outcome(
f"if command -v hostnamectl >/dev/null 2>&1 && hostnamectl set-hostname {name} "
f"2>/dev/null; then :; else printf '%s\\n' {name} > /etc/hostname "
f"&& hostname {name}; fi",
30,
"",
)
if not outcome["ok"]:
raise RuntimeError(outcome["output"] or "the host refused the new hostname")
if hosts.exit_code == 0:
renamed = _rename_in_hosts(hosts.stdout, old_names - {""}, short, fqdn)
if renamed != hosts.stdout:
self._install_or_raise("/etc/hosts", renamed)
if self.run_command("test -d /etc/cloud/cloud.cfg.d", timeout=30).exit_code == 0:
self._install_or_raise(_CLOUD_INIT_PRESERVE, _CLOUD_INIT_PRESERVE_CONTENT)
def _install_or_raise(self, path: str, content: str) -> None:
"""``_install_file_as_root``, raising its output when it failed."""
result = self._install_file_as_root(path, content)
if result.exit_code != 0:
reason = (result.stderr or result.stdout).strip() or f"status {result.exit_code}"
raise RuntimeError(f"hostname set, but {path} could not be written: {reason}")
+3 -5
View File
@@ -69,11 +69,9 @@ from napalm_device_types.models import (
)
from napalm_device_types.ssh_host_keys import HostKeyCheck
from netmiko import ConnectHandler
from netmiko.exceptions import (
NetmikoAuthenticationException,
NetmikoTimeoutException,
)
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from napalm_linux._hostname import HostnameMixin
from napalm_linux._shell import PROMPT_RE as _PROMPT_RE
from napalm_linux._shell import prepare_shell
@@ -321,6 +319,7 @@ class LinuxDriver(
SystemdServicesMixin,
HostStatusMixin,
ContainerEngineMixin,
HostnameMixin,
OSDriver,
):
"""NAPALM driver for generic Linux systems.
@@ -367,7 +366,6 @@ class LinuxDriver(
self._secret: str = optional_args.get("secret", password)
# Optional sudo password for privilege escalation (e.g. apt-get update)
self._sudo_password: str | None = optional_args.get("sudo_password")
# Expected apt proxy URL — checked as a device warning on apt systems.
if optional_args.get("debugging"):
logger.setLevel(logging.DEBUG)
+1 -1
View File
@@ -22,7 +22,7 @@
"napalm_linux.linux"
],
"python_file_lines": {
"napalm_linux/linux.py": 2288
"napalm_linux/linux.py": 2286
},
"untyped_public": []
}
+289
View File
@@ -0,0 +1,289 @@
"""``set_hostname`` renames the host itself, not only what netOrk calls it (#45).
The static and runtime hostname take the short name; ``/etc/hosts`` follows, so
the host still resolves its own name; and a cloud-init host is told to keep the
name, or its next boot puts the image's name back. Every file root writes is
staged without privilege first, as ``_install_file_as_root`` does for the fixes.
"""
from __future__ import annotations
import shlex
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from napalm_linux import LinuxDriver
from napalm_linux._hostname import _rename_in_hosts, _split_hostname
_PW = "pw-45"
_STAGED = "/tmp/netork-stage.Xy34Zw"
_HOSTS = "127.0.0.1\tlocalhost\n127.0.1.1\told.example.net old\n\n::1 localhost ip6-localhost\n"
class Host:
"""The host's exec channels: every line, its stdin, and whether it ran as root."""
def __init__(self, *, hosts=_HOSTS, cloud_init=False, rename_status=0, hosts_status=0):
self.runs: list[SimpleNamespace] = []
self.hosts = hosts
self.cloud_init = cloud_init
self.rename_status = rename_status
self.hosts_status = hosts_status
def open_session(self):
return _Channel(self)
def answer(self, command: str, script: str) -> tuple[str, int]:
if command.startswith("sudo -n "):
return "sudo: a password is required\n", 1
if script == "hostname":
return "old\n", 0
if script.startswith("hostname -f"):
return "old.example.net\n", 0
if script == "cat /etc/hosts":
return self.hosts, 0
if script.startswith("test -d /etc/cloud"):
return "", 0 if self.cloud_init else 1
if "mktemp" in script:
return _STAGED, 0
if "hostnamectl" in script:
return (
"hostname: you must be root\n" if self.rename_status else ""
), self.rename_status
if "/etc/hosts" in script and "install" in script:
return ("install: cannot create\n" if self.hosts_status else ""), self.hosts_status
return "", 0
@property
def root_scripts(self) -> list[str]:
return [run.script for run in self.runs if run.root]
def staged(self) -> list[bytes]:
return [run.stdin for run in self.runs if "mktemp" in run.script]
class _Channel:
def __init__(self, host: Host):
self._host = host
self._run: SimpleNamespace | None = None
self._out = b""
self._status = 0
def exec_command(self, command):
assert _PW not in command
root = command.startswith(("sudo ", "sh -c "))
parts = shlex.split(command)
script = parts[parts.index("-c") + 1] if root else command
script = script.removeprefix("exec </dev/null; ")
self._run = SimpleNamespace(line=command, script=script, root=root, stdin=b"")
self._host.runs.append(self._run)
output, self._status = self._host.answer(command, script)
self._out = output.encode()
def settimeout(self, timeout):
pass
def sendall(self, data):
self._run.stdin += data
def shutdown_write(self):
pass
def close(self):
pass
def recv_ready(self):
return bool(self._out)
def recv(self, size):
chunk, self._out = self._out[:size], self._out[size:]
return chunk
def recv_stderr_ready(self):
return False
def recv_stderr(self, size):
return b""
def exit_status_ready(self):
return not self._out
def recv_exit_status(self):
return self._status
def _driver(host: Host, *, sudo_password: str | None = _PW) -> LinuxDriver:
optional_args = {"sudo_password": sudo_password} if sudo_password else {}
driver = LinuxDriver("h", "admin", "p", optional_args=optional_args)
driver._device = MagicMock()
driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: host)
driver._root = False
driver._pkg_manager = "apt"
return driver
def _hosts_written(host: Host) -> str:
"""What was staged for /etc/hosts, or "" when it was left alone."""
staged = b""
for run in host.runs:
if "mktemp" in run.script:
staged = run.stdin
elif run.root and "/etc/hosts" in run.script:
return staged.decode()
return ""
class TestSplitHostname:
@pytest.mark.parametrize(
"name, expected",
[
("web-01", ("web-01", None)),
("web-01.example.net", ("web-01", "web-01.example.net")),
("A1", ("A1", None)),
("a" * 63, ("a" * 63, None)),
],
)
def test_valid(self, name, expected):
assert _split_hostname(name) == expected
@pytest.mark.parametrize(
"name",
[
"",
"web_01",
"-web",
"web-",
"a" * 64,
".".join(["a" * 60] * 5),
"web 01",
"web;reboot",
"web.",
".web",
"web..example",
"$(id)",
],
)
def test_invalid(self, name):
with pytest.raises(ValueError):
_split_hostname(name)
class TestRenameInHosts:
def test_old_names_replaced_on_every_line_they_appear(self):
content = "127.0.0.1 localhost old\n10.0.0.5 old.example.net old # me\n"
assert _rename_in_hosts(content, {"old", "old.example.net"}, "new", "new.example.net") == (
"127.0.0.1\tlocalhost new.example.net new\n10.0.0.5\tnew.example.net new # me\n"
)
def test_other_aliases_and_lines_kept(self):
content = "# static\n127.0.1.1 old mail\n::1 localhost\n"
assert _rename_in_hosts(content, {"old"}, "new", None) == (
"# static\n127.0.1.1\tnew mail\n::1 localhost\n"
)
def test_names_compared_without_case(self):
assert _rename_in_hosts("127.0.1.1 OLD\n", {"old"}, "new", None) == "127.0.1.1\tnew\n"
def test_no_old_name_but_a_127_0_1_1_line_takes_the_new_name(self):
content = "127.0.0.1 localhost\n127.0.1.1 ubuntu\n"
assert _rename_in_hosts(content, {"old"}, "new", "new.example.net") == (
"127.0.0.1 localhost\n127.0.1.1\tnew.example.net new\n"
)
def test_neither_leaves_the_file_alone(self):
content = "127.0.0.1 localhost localhost.localdomain\n::1 localhost\n"
assert _rename_in_hosts(content, {"old"}, "new", None) == content
def test_localhost_is_never_renamed(self):
content = "127.0.0.1 localhost\n"
assert _rename_in_hosts(content, {"localhost"}, "new", None) == content
class TestSetHostname:
def test_short_name_set_as_root(self):
host = Host()
_driver(host).set_hostname("new")
rename = host.root_scripts[0]
assert "hostnamectl set-hostname new" in rename
assert "/etc/hostname" in rename and "hostname new" in rename
def test_fqdn_sets_the_short_name_and_both_in_hosts(self):
host = Host()
_driver(host).set_hostname("new.example.net")
assert "hostnamectl set-hostname new " in host.root_scripts[0]
assert "example" not in host.root_scripts[0]
assert _hosts_written(host) == (
"127.0.0.1\tlocalhost\n127.0.1.1\tnew.example.net new\n\n::1 localhost ip6-localhost\n"
)
def test_hosts_installed_from_a_staged_file_never_privileged_stdin(self):
host = Host()
_driver(host).set_hostname("new")
hosts_install = [s for s in host.root_scripts if "/etc/hosts" in s]
assert len(hosts_install) == 1
assert f"install -m 644 -o root -g root -- {_STAGED}" in hosts_install[0]
for run in host.runs:
if run.root:
assert run.stdin == f"{_PW}\n".encode()
def test_unchanged_hosts_not_rewritten(self):
host = Host(hosts="127.0.0.1 localhost\n")
_driver(host).set_hostname("new")
assert not any("/etc/hosts" in s for s in host.root_scripts)
def test_cloud_init_host_keeps_the_name(self):
host = Host(cloud_init=True)
_driver(host).set_hostname("new")
assert any(
"/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg" in s for s in host.root_scripts
)
assert any(b"preserve_hostname: true" in staged for staged in host.staged())
def test_no_cloud_init_no_drop_in(self):
host = Host()
_driver(host).set_hostname("new")
assert not any("cloud.cfg.d" in s for s in host.root_scripts)
def test_invalid_name_runs_nothing(self):
host = Host()
driver = _driver(host)
with pytest.raises(ValueError):
driver.set_hostname("new;reboot")
assert host.runs == []
driver._device.send_command.assert_not_called()
def test_failed_rename_raises_and_writes_nothing(self):
host = Host(rename_status=1)
with pytest.raises(RuntimeError):
_driver(host).set_hostname("new")
assert not any("/etc/hosts" in s for s in host.root_scripts)
def test_sudo_without_password_says_what_to_do(self):
host = Host()
with pytest.raises(RuntimeError, match="no sudo password was given"):
_driver(host, sudo_password=None).set_hostname("new")
def test_failed_hosts_write_raises(self):
host = Host(hosts_status=1)
with pytest.raises(RuntimeError, match="/etc/hosts"):
_driver(host).set_hostname("new")