diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c28932..23eb7c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- Restarting and shutting the host down (NetOrk/netork#2841): `reboot_host()` and + `shutdown_host()` from napalm-device-types' `HostRebootMixin` and `HostShutdownMixin` + run `Restart-Computer` and `Stop-Computer` over the PSRP connection, neither with + `-Force`: Windows asks running programs to close and refuses while other users are + logged on, a disconnected session included, instead of throwing away what they have + not saved. A refusal raises `RuntimeError` with the host's answer. Both cmdlets start + the shutdown and return, so no delay is needed before the session goes; a connection + the host drops before answering counts as accepted. `PsrpTransport.run_last(script)` + tells the two apart: `False` when the connection broke, `PowerShellError` when the + script wrote an error. - Time sync: napalm-device-types' `TimeSyncMixin` (4.35.0), servers and zone (NetOrk/netork#2367). `get_time_sync` reads w32time's `NtpServer` and `Type` from the registry (group policy's first; `NoSync` has no servers), whether the clock is diff --git a/README.md b/README.md index 4b20b10..cae0cc4 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ handshake once. | `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) | | `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) | | `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` | +| `reboot_host` / `shutdown_host` | `Restart-Computer`, `Stop-Computer`, neither with `-Force`: programs are asked to close, and Windows refuses while other users are logged on. A connection the host drops before answering counts as accepted | | `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) | | `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones | | `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) | diff --git a/napalm_windows/transport.py b/napalm_windows/transport.py index 296563a..679f0aa 100644 --- a/napalm_windows/transport.py +++ b/napalm_windows/transport.py @@ -104,6 +104,22 @@ class PsrpTransport: raise PowerShellError(message or "PowerShell reported an error") return "\n".join(str(o) for o in output if o is not None) + def run_last(self, script: str) -> bool: + """Run a script after which the host may stop answering: a restart, a shutdown. + + True when the script finished. False when the connection broke before the + answer came, which for such a script means the host went down first; the + transport is closed then. An error the script wrote still raises + :class:`PowerShellError`: the host answered, and refused. + """ + try: + self.run(script) + except (requests.RequestException, WinRMError, OSError) as exc: + logger.debug("Connection to %s broke during its last script: %s", self.host, exc) + self._drop() + return False + return True + def close(self) -> None: if self._pool is not None: try: diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index 1cd0136..fbd26dd 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -181,6 +181,12 @@ _SERVICE_COMMANDS = { "disable": "Set-Service -Name {name} -StartupType Disabled", } +# The host's own restart and shutdown, without -Force: Windows asks running programs to +# close and refuses while other users are logged on, instead of throwing away what they +# have not saved. Both start the shutdown and return; WinRM goes later, with the services. +_PS_REBOOT = "Restart-Computer -Confirm:$false -ErrorAction Stop" +_PS_SHUTDOWN = "Stop-Computer -Confirm:$false -ErrorAction Stop" + # Service key names, not display names: letters, digits and the few symbols # real services use (MSSQL$SQLEXPRESS, CDPUserSvc_4a5b6, {GUID}-style names). _SERVICE_NAME_RE = re.compile(r"^[\w.$@{}\-]+$", re.ASCII) @@ -353,6 +359,15 @@ class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): raise ConnectionClosedException("WinRM connection is not open") return self._transport.run(script) + def _run_power(self, script: str, what: str) -> None: + """Send a restart or shutdown; the connection the host drops counts as accepted.""" + if self._transport is None: + raise ConnectionClosedException("WinRM connection is not open") + try: + self._transport.run_last(script) + except PowerShellError as exc: + raise RuntimeError(f"The host refused to {what}: {exc}") from exc + # ------------------------------------------------------------------ # NAPALM getters # ------------------------------------------------------------------ @@ -506,6 +521,28 @@ class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver): sockets.sort(key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or "")) return {"attributed": True, "sockets": sockets} + def reboot_host(self) -> None: + """Restart the host cleanly (``HostRebootMixin``) with ``Restart-Computer``. + + Not forced: programs are asked to close, and Windows refuses while other users + are logged on, a disconnected session included. Returns once the restart is + under way; a connection the host drops before answering counts as that. + + :raises RuntimeError: when the host refuses, with its answer. + """ + self._run_power(_PS_REBOOT, "restart") + + def shutdown_host(self) -> None: + """Shut the host down cleanly and power it off (``HostShutdownMixin``) with + ``Stop-Computer``. + + Not forced, as :meth:`reboot_host`. Returns once the shutdown is under way; a + connection the host drops before answering counts as that. + + :raises RuntimeError: when the host refuses, with its answer. + """ + self._run_power(_PS_SHUTDOWN, "shut down") + def manage_service(self, name: str, action: str) -> dict[str, Any]: template = _SERVICE_COMMANDS.get(action) if template is None: diff --git a/tests/test_transport.py b/tests/test_transport.py index 54488db..8fcc708 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -11,7 +11,7 @@ from unittest.mock import patch import pytest import requests from napalm.base.exceptions import ConnectionClosedException, ConnectionException -from pypsrp.exceptions import AuthenticationError, WinRMTransportError +from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError from napalm_windows.transport import PowerShellError, PsrpTransport @@ -120,6 +120,52 @@ class TestRun: _transport().run("Get-Thing") +class TestRunLast: + """A script that may take WinRM down with it: a restart, a shutdown.""" + + def test_a_finished_script_is_true(self, psrp): + psrp["ps"].return_value.invoke.return_value = [] + psrp["ps"].return_value.had_errors = False + t = _transport() + t.open() + + assert t.run_last("Restart-Computer") is True + psrp["ps"].return_value.add_script.assert_called_once_with("Restart-Computer") + assert t.is_open is True + + def test_the_error_stream_still_raises_powershell_error(self, psrp): + psrp["ps"].return_value.invoke.return_value = [] + psrp["ps"].return_value.had_errors = True + psrp["ps"].return_value.streams.error = ["other users logged on"] + t = _transport() + t.open() + + with pytest.raises(PowerShellError, match="other users logged on"): + t.run_last("Restart-Computer") + + @pytest.mark.parametrize( + "error", + [ + requests.ConnectionError("connection reset by peer"), + requests.ReadTimeout("read timed out"), + WinRMTransportError("http", 503, "Service Unavailable"), + WinRMError("the shell was terminated"), + ConnectionResetError(104, "Connection reset by peer"), + ], + ) + def test_a_connection_that_breaks_is_false_and_closed(self, psrp, error): + psrp["ps"].return_value.invoke.side_effect = error + t = _transport() + t.open() + + assert t.run_last("Restart-Computer") is False + assert t.is_open is False + + def test_run_last_before_open_raises_connection_closed(self): + with pytest.raises(ConnectionClosedException): + _transport().run_last("Restart-Computer") + + class TestClose: def test_close_closes_pool_and_connection(self, psrp): t = _transport() diff --git a/tests/test_windows.py b/tests/test_windows.py index bbdb611..8e3f6ec 100644 --- a/tests/test_windows.py +++ b/tests/test_windows.py @@ -28,9 +28,15 @@ def _fixture(name: str) -> str: class FakeTransport: """Answers the driver's scripts from fixtures and records what it was sent.""" - def __init__(self, answers: dict[str, str] | None = None, error: str | None = None): + def __init__( + self, + answers: dict[str, str] | None = None, + error: str | None = None, + drops: bool = False, + ): self.answers = answers or {} self.error = error + self.drops = drops self.sent: list[str] = [] self.is_open = True @@ -40,6 +46,14 @@ class FakeTransport: raise PowerShellError(self.error) return self.answers.get(script, "") + def run_last(self, script: str) -> bool: + self.sent.append(script) + if self.error: + raise PowerShellError(self.error) + if self.drops: + self.is_open = False + return not self.drops + def close(self) -> None: self.is_open = False @@ -490,3 +504,55 @@ class TestManageService: "success": False, "output": "Cannot find any service with service name 'nope'.", } + + +class TestHostPower: + """``reboot_host`` and ``shutdown_host``: the clean restart and shutdown of the host + itself, never a forced one (NetOrk/netork#2841).""" + + @pytest.mark.parametrize( + ("method", "cmdlet"), + [("reboot_host", "Restart-Computer"), ("shutdown_host", "Stop-Computer")], + ) + def test_sends_the_cmdlet_without_force(self, method, cmdlet): + d = _driver() + + getattr(d, method)() + + (script,) = d._transport.sent + assert script.startswith(cmdlet) + assert "-ErrorAction Stop" in script + assert "-Force" not in script + + @pytest.mark.parametrize( + ("method", "what"), [("reboot_host", "restart"), ("shutdown_host", "shut down")] + ) + def test_a_refusal_raises_with_the_hosts_answer(self, method, what): + answer = ( + "Failed to restart the computer WIN01 with the following error message: The " + "system shutdown cannot be initiated because there are other users logged on " + "to the computer." + ) + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(error=answer) + + with pytest.raises(RuntimeError, match=f"refused to {what}: Failed to restart"): + getattr(d, method)() + + @pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"]) + def test_a_connection_dropped_by_the_host_counts_as_accepted(self, method): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(drops=True) + + getattr(d, method)() + + assert len(d._transport.sent) == 1 + + @pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"]) + def test_before_open_raises_connection_closed(self, method): + with pytest.raises(ConnectionClosedException): + getattr(WindowsDriver("win01", "admin", "secret"), method)() + + @pytest.mark.parametrize("method", ["reboot_host", "shutdown_host"]) + def test_the_capability_is_there_for_introspection(self, method): + assert callable(getattr(WindowsDriver("win01", "admin", "secret"), method, None))