Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8f46c133d | ||
|
|
891a31fe45 | ||
|
|
54b3c9b362 | ||
|
|
81c4df3159 | ||
|
|
169d88f7e5 | ||
|
|
a97e59c1e2 | ||
|
|
8ed5e0ed87 |
No files matched your search
+28
-13
@@ -7,19 +7,34 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Windows Update (NetOrk/netork#2892). A refresh searches the update source the host is
|
||||
configured for (Windows Update or its WSUS server) and keeps what it found on the host;
|
||||
the pending updates are read from that, so a poll never waits minutes for a search.
|
||||
Each pending update carries its title, KB articles, the CVEs it fixes and Microsoft's
|
||||
severity rating, and is named so that next month's cumulative update keeps the same
|
||||
name. Optional previews, feature upgrades and drivers are left out.
|
||||
- Installing Windows updates (NetOrk/netork#2892): Windows does not let a remote session
|
||||
install updates, so each run is a one-shot task running as SYSTEM. It installs only the
|
||||
exact updates chosen, refuses one that is no longer offered, asks for input or has
|
||||
licence terms not yet accepted, installs nothing while a restart is pending, and never
|
||||
restarts the host. Its output arrives line by line; the task is deleted afterwards.
|
||||
- The update history: what Windows Update installed or removed, when, which component
|
||||
asked for it, and why it failed.
|
||||
- The host's SMBIOS identity, what ties it to its BMC (NetOrk/netork#2888):
|
||||
`get_system_identity` reads the system UUID and product serial
|
||||
(`Win32_ComputerSystemProduct`), the board serial (`Win32_BaseBoard`) and the system
|
||||
firmware's vendor, version and release date (`Win32_BIOS`) in one script of its own.
|
||||
Vendor placeholders such as "To be filled by O.E.M." or an all-F UUID read as empty,
|
||||
by napalm-device-types' rules (`clean_system_identity`).
|
||||
- Running processes (NetOrk/netork#2889): `get_processes` lists them the way `ps` does --
|
||||
parent, owner, CPU and memory share, virtual and resident size, start and command line
|
||||
-- from `Win32_Process` and `Get-Process -IncludeUserName` in one script. A process
|
||||
that exited between the two reads, or whose PID was reused in between, is left out.
|
||||
- Local accounts (NetOrk/netork#2889): `get_os_users` lists the host's own accounts with
|
||||
their local groups and profile folder. `uid` is the account's relative identifier
|
||||
(500 for the built-in Administrator), `sid` its whole security identifier. A domain
|
||||
controller, which has no local accounts, and a host without the LocalAccounts cmdlets
|
||||
raise `NotImplementedError`.
|
||||
- Installed software (NetOrk/netork#2890): `get_packages` lists the programs installed
|
||||
for the whole machine from the Uninstall keys, the 64-bit and the 32-bit ones, each
|
||||
with its publisher and architecture; `source` is `msi` or `exe`. Hidden system
|
||||
components and updates listed under their product are left out. Programs installed
|
||||
for one user only, and Store apps, are not read yet; nothing is installed or removed.
|
||||
- Restart required and automatic updates (NetOrk/netork#2891): `get_host_status` says
|
||||
the host needs a restart when Windows Update or component servicing waits for one;
|
||||
pending file renames, a pending update executable and a new computer name are named
|
||||
in the reason but do not count on their own. Automatic updates follow the Windows
|
||||
Update policy (`NoAutoUpdate`, `AUOptions`); without one a Windows client installs on
|
||||
its own and a server follows its local setting. When they last succeeded is the
|
||||
latest successful installation Windows Update recorded; the system drive's size and
|
||||
free space come with it. Nothing searches for updates during the reading.
|
||||
- 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
|
||||
|
||||
@@ -42,9 +42,11 @@ handshake once.
|
||||
| `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) |
|
||||
| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only |
|
||||
| `refresh_available_updates` / `get_available_updates` | The Windows Update Agent's search (`Microsoft.Update.Session`), kept in the registry for the poll; the host's update history leaves out what was installed since. See *Windows Update* |
|
||||
| `apply_updates` | A one-shot SYSTEM scheduled task that searches again and installs only the exact updates chosen; never restarts. See *Windows Update* |
|
||||
| `get_update_history` | `IUpdateSearcher.QueryHistory`, the newest 300 entries |
|
||||
| `get_system_identity` | `Win32_ComputerSystemProduct` (UUID, serial), `Win32_BaseBoard`, `Win32_BIOS`; placeholders empty (napalm-device-types' `clean_system_identity`). See *Host basics* |
|
||||
| `get_processes` | `Win32_Process` joined with `Get-Process -IncludeUserName` by PID and start, shaped like `ps` |
|
||||
| `get_os_users` | `Get-LocalUser`, `Get-LocalGroup` + `Get-LocalGroupMember` (ADSI fallback), `Win32_UserProfile`; the RID as `uid`, the SID as `sid` |
|
||||
| `get_packages` | The machine-wide Uninstall keys, native and `WOW6432Node`; no per-user installs, no Store apps, nothing installed |
|
||||
| `get_host_status` | `Microsoft.Update.SystemInfo`, the registry's restart markers, the Windows Update policy and history, the system drive |
|
||||
| `get_time_sync` / `configure_time_sync` | w32time's registry values (group policy first), `w32tm /query /status`, the registry's `TimeZoneInformation`; writes `NtpServer`/`Type` + `w32tm /config /update`, `Set-TimeZone`. See *Time sync* |
|
||||
|
||||
`running_kernel` carries the full build including the update revision
|
||||
@@ -100,47 +102,31 @@ napalm-device-types' `TimeSyncMixin`; both the servers and the zone are written.
|
||||
zone with summer time switched off reads as `None`; writing the zone switches it
|
||||
back on.
|
||||
|
||||
### Windows Update
|
||||
### Host basics
|
||||
|
||||
napalm-device-types' `UpdateMixin`, through the Windows Update Agent's COM API.
|
||||
* **Identity.** Windows decodes the SMBIOS system UUID the way dmidecode does; the
|
||||
release date is CIM's midnight UTC, read as that day.
|
||||
* **Processes.** `cpu` is the CPU time over the time since the start, per logical
|
||||
processor; `memory` the working set over the visible memory; `started` the local time
|
||||
as `ps -o lstart` prints it. Windows has no controlling terminal and no `ps` state:
|
||||
`tty` and `state` are empty. The owner needs an elevated session; without one it is
|
||||
empty. PID 0 (System Idle Process) is no process.
|
||||
* **Local accounts.** `gid` is 513, the primary group of every local account; `home` is
|
||||
the profile folder, empty until the account first logs on; `shell` is empty.
|
||||
* **Packages.** A 32-bit and a 64-bit install of one program are two packages, told
|
||||
apart by `architecture`. Keys without a `DisplayName`, `SystemComponent=1` and
|
||||
entries with a `ParentKeyName` are left out.
|
||||
* **Restart required** is Windows Update's `RebootRequired` (or its registry marker) or
|
||||
component servicing's `RebootPending`. `PendingFileRenameOperations`,
|
||||
`UpdateExeVolatile` and a pending computer rename only make up the reason.
|
||||
* **Automatic updates.** Policy first: `NoAutoUpdate=1` off, `AUOptions` 4 on, 2, 3
|
||||
and 7 off, 5 the local setting. Without a policy a client is on and a server follows
|
||||
its local `AUOptions`; a server with neither reads as unknown. The last success is the
|
||||
latest successful installation Windows Update recorded (its history, the AutoUpdate
|
||||
result, the older registry result); the interval is 31 days, the cadence of the
|
||||
monthly cumulative update.
|
||||
|
||||
* **The search is the refresh.** `refresh_available_updates` searches the source the
|
||||
host is configured for -- Windows Update, or the WSUS server group policy names --
|
||||
for `IsInstalled=0 and IsHidden=0 and Type='Software'`: no drivers. A search takes
|
||||
minutes, so the poll never runs one. It keeps its reading under
|
||||
`HKLM\SOFTWARE\napalm-windows\WindowsUpdate` (only administrators and SYSTEM may write
|
||||
there), and `get_available_updates` reads that back, leaving out what the host's
|
||||
history shows installed since. Before the first search it raises
|
||||
`PackageIndexMissing`, which a refresh cures.
|
||||
* **Names.** An update is named by what it keeps from month to month: its title without
|
||||
the month, the KB article and the version, as a package name
|
||||
(`Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems`).
|
||||
Next month's cumulative update takes this one's place under the same name, so the time
|
||||
a host has waited for it is not reset each month. `new_version` and `advisories` are
|
||||
its KB articles, `cves` its `CveIDs`, `vendor_severity` its `MsrcSeverity`, `title`
|
||||
its title. A security update, a definition update or one naming CVEs is `security`;
|
||||
another classified one is not.
|
||||
* **Not pending:** optional updates (`BrowseOnly`: previews Windows does not install by
|
||||
itself) and feature upgrades -- this path installs neither.
|
||||
* **Installing** (`apply_updates`). Windows refuses a download or an install to a
|
||||
network logon (`E_ACCESSDENIED`), so a run is a one-shot task
|
||||
`\napalm-windows\update-run-<id>` running as SYSTEM. Its script and the exact updates
|
||||
chosen (`<UpdateID>:<revision>`, those the last search found under each name) go into
|
||||
the run's registry key; no file is written. The task searches again and refuses, by
|
||||
name, an update no longer offered under that ID and revision, one offered twice, one
|
||||
that asks for input while it installs (`CanRequestUserInput`), and one whose licence
|
||||
terms the host has not accepted; while a restart is pending it installs nothing. It
|
||||
never restarts the host. The driver follows the run's log every 5 seconds and hands each
|
||||
line to `log`, then deletes the task and the key. The tasks and keys of runs whose
|
||||
connection died are deleted by the next run, which refuses to start while one is still
|
||||
installing; a run followed for 25 minutes is left to finish on the host. The task names
|
||||
itself to Windows Update as `napalm-windows`, which the history's `requested_by`
|
||||
shows. `get_scheduled_jobs` reports these tasks as an application's, offering nothing.
|
||||
* **History** (`get_update_history`): `QueryHistory`, newest 300 entries, one transaction
|
||||
each; `requested_by` is the `ClientApplicationID` (`UpdateOrchestrator`,
|
||||
`AutomaticUpdates`, `napalm-windows`), `error` the result and its HRESULT.
|
||||
|
||||
Not yet: packages, health metrics, Hyper-V.
|
||||
Not yet: Windows Update, health metrics, Hyper-V.
|
||||
See netork#300 for the plan.
|
||||
|
||||
## Preparing a host
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""One reading script's JSON object, which the host readings of this driver share."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def json_object(out: str, what: str) -> dict[str, Any]:
|
||||
"""*out*, a script's ``ConvertTo-Json`` of one object, parsed.
|
||||
|
||||
:raises ValueError: when it is empty or no object, naming *what* was read.
|
||||
"""
|
||||
out = out.strip()
|
||||
raw = json.loads(out) if out else None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"the {what} reading came back empty")
|
||||
return raw
|
||||
@@ -0,0 +1,28 @@
|
||||
"""What every host reports about itself, gathered for the driver (NetOrk/netork#2888-#2891).
|
||||
|
||||
One mixin made of one module per reading, so the driver names a single base:
|
||||
|
||||
* :mod:`napalm_windows.system_identity` -- ``get_system_identity``
|
||||
* :mod:`napalm_windows.processes` -- ``get_processes``
|
||||
* :mod:`napalm_windows.os_users` -- ``get_os_users``
|
||||
* :mod:`napalm_windows.packages` -- ``get_packages``
|
||||
* :mod:`napalm_windows.host_status` -- ``get_host_status``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_windows.host_status import WindowsHostStatusMixin
|
||||
from napalm_windows.os_users import WindowsOsUsersMixin
|
||||
from napalm_windows.packages import WindowsPackagesMixin
|
||||
from napalm_windows.processes import WindowsProcessesMixin
|
||||
from napalm_windows.system_identity import WindowsSystemIdentityMixin
|
||||
|
||||
|
||||
class WindowsHostBasicsMixin(
|
||||
WindowsSystemIdentityMixin,
|
||||
WindowsProcessesMixin,
|
||||
WindowsOsUsersMixin,
|
||||
WindowsPackagesMixin,
|
||||
WindowsHostStatusMixin,
|
||||
):
|
||||
"""The readings napalm-linux has as a matter of course; each module documents its own."""
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
:class:`WindowsHostStatusMixin` gives the driver napalm-device-types' ``get_host_status``
|
||||
(``HostStatusDict``) in one script. Each part is read on its own -- a COM object that
|
||||
does not answer over WinRM leaves the rest standing -- and nothing searches for updates:
|
||||
that is the update reading's, and too slow for a poll.
|
||||
|
||||
**Restart required** is what Windows says about its own updates:
|
||||
|
||||
* Windows Update's ``Microsoft.Update.SystemInfo.RebootRequired``, and its registry
|
||||
marker ``WindowsUpdate\\Auto Update\\RebootRequired`` where the COM object did not
|
||||
answer;
|
||||
* component-based servicing's ``RebootPending`` (features, roles, servicing stack).
|
||||
|
||||
Other markers only explain: ``PendingFileRenameOperations``, which antivirus and
|
||||
installers set routinely and which would keep the flag up for days, ``UpdateExeVolatile``
|
||||
and a new computer name taking effect at the next restart. They make up
|
||||
``reboot_reason`` with the two above, and a host with only them needs no restart.
|
||||
|
||||
**Automatic updates** follow the policy (``HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\
|
||||
WindowsUpdate\\AU``): ``NoAutoUpdate=1`` is off; ``AUOptions`` 4 installs on its own,
|
||||
2, 3 and 7 only notify or download; 5 leaves it to the local setting. Without a policy
|
||||
Windows 10 and 11 install on their own, and ignore the local ``AUOptions`` an upgrade may
|
||||
have left; a Windows Server follows its local setting (``sconfig``), and without one the
|
||||
answer is None: what each Server release does then is not established.
|
||||
|
||||
**When they last succeeded** is the latest successful installation Windows Update knows
|
||||
of, whoever started it: its history's last 50 entries, the ``Microsoft.Update.AutoUpdate``
|
||||
result and the older registry result (``Auto Update\\Results\\Install``), whichever is
|
||||
latest. Windows has something to install every month -- the cumulative update -- so
|
||||
automatic updates are meant to have installed something within 31 days
|
||||
(``auto_updates_interval``); on Linux that is the timer's day.
|
||||
|
||||
**Filesystems** are the system drive's size and free space, where updates unpack.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import FilesystemUsageDict, HostStatusDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_AU_POLICY = r"HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
|
||||
_AU_LOCAL = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
|
||||
_CBS = r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"
|
||||
_SESSION_MANAGER = r"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager"
|
||||
_COMPUTER_NAME = r"HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName"
|
||||
|
||||
# WUA's dates are UTC with no kind; IUpdateHistoryEntry.Operation 1 is an installation,
|
||||
# ResultCode 2 succeeded and 3 succeeded with errors.
|
||||
_PS_HOST_STATUS = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function V($path, $name) {{
|
||||
$item = Get-ItemProperty -LiteralPath $path -Name $name -ErrorAction SilentlyContinue
|
||||
if ($item) {{ $item.$name }}
|
||||
}}
|
||||
function Utc($t) {{
|
||||
if ($t) {{ ([DateTimeOffset][DateTime]::SpecifyKind($t, 'Utc')).ToUnixTimeSeconds() }}
|
||||
}}
|
||||
$wu = $null
|
||||
try {{ $wu = [bool](New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired }} catch {{ }}
|
||||
$installs = $null
|
||||
try {{
|
||||
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
|
||||
$count = $searcher.GetTotalHistoryCount()
|
||||
$installs = @(if ($count -gt 0) {{
|
||||
$searcher.QueryHistory(0, [Math]::Min($count, 50)) | Where-Object {{
|
||||
$_.Operation -eq 1 -and ($_.ResultCode -eq 2 -or $_.ResultCode -eq 3)
|
||||
}} | ForEach-Object {{ Utc $_.Date }}
|
||||
}})
|
||||
}} catch {{ }}
|
||||
$au = $null
|
||||
try {{
|
||||
$results = (New-Object -ComObject Microsoft.Update.AutoUpdate).Results
|
||||
$au = Utc $results.LastInstallationSuccessDate
|
||||
}} catch {{ }}
|
||||
$drive = $null
|
||||
try {{
|
||||
$disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$env:SystemDrive'"
|
||||
if ($disk) {{
|
||||
$drive = [pscustomobject]@{{
|
||||
drive = [string]$disk.DeviceID; size = [int64]$disk.Size; free = [int64]$disk.FreeSpace
|
||||
}}
|
||||
}}
|
||||
}} catch {{ }}
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{{
|
||||
wu_reboot_required = $wu
|
||||
cbs_reboot_pending = Test-Path -LiteralPath '{_CBS}\RebootPending'
|
||||
wu_reboot_key = Test-Path -LiteralPath '{_AU_LOCAL}\RebootRequired'
|
||||
file_renames = [bool](V '{_SESSION_MANAGER}' 'PendingFileRenameOperations')
|
||||
update_exe = [string](V 'HKLM:\SOFTWARE\Microsoft\Updates' 'UpdateExeVolatile')
|
||||
computer_name = [string](V '{_COMPUTER_NAME}\ComputerName' 'ComputerName')
|
||||
active_name = [string](V '{_COMPUTER_NAME}\ActiveComputerName' 'ComputerName')
|
||||
no_auto_update = [string](V '{_AU_POLICY}' 'NoAutoUpdate')
|
||||
au_options = [string](V '{_AU_POLICY}' 'AUOptions')
|
||||
local_au_options = [string](V '{_AU_LOCAL}' 'AUOptions')
|
||||
product_type = [int](Get-CimInstance -ClassName Win32_OperatingSystem).ProductType
|
||||
installs = $installs
|
||||
au_last_install = $au
|
||||
legacy_last_install = [string](V '{_AU_LOCAL}\Results\Install' 'LastSuccessTime')
|
||||
system_drive = $drive
|
||||
}})
|
||||
"""
|
||||
|
||||
#: ``AUOptions``: 2 notify, 3 download and notify, 4 install on a schedule, 7 (Server)
|
||||
#: download, notify to install and to restart; 1 is the older "never check".
|
||||
_AU_OPTIONS = {"1": False, "2": False, "3": False, "4": True, "7": False}
|
||||
#: ``Win32_OperatingSystem.ProductType`` of a client; 2 and 3 are servers.
|
||||
_WORKSTATION = 1
|
||||
#: How often a Windows host has something to install: the monthly cumulative update.
|
||||
MONTHLY = 31 * 86400
|
||||
|
||||
|
||||
def _marker(raw: dict[str, Any], key: str) -> bool:
|
||||
return raw.get(key) is True
|
||||
|
||||
|
||||
#: The markers that explain a restart, in the order they are named, each with its words.
|
||||
_REASONS = (
|
||||
(
|
||||
("wu_reboot_required", "wu_reboot_key"),
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
),
|
||||
(("cbs_reboot_pending",), "component-based servicing has a restart pending"),
|
||||
(
|
||||
("file_renames",),
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _rename(raw: dict[str, Any]) -> str | None:
|
||||
"""The new computer name a restart takes effect with, if there is one."""
|
||||
new, active = str(raw.get("computer_name") or ""), str(raw.get("active_name") or "")
|
||||
if new and active and new.lower() != active.lower():
|
||||
return f"the computer takes its new name {new} at the next restart"
|
||||
return None
|
||||
|
||||
|
||||
def _restart_reasons(raw: dict[str, Any]) -> list[str]:
|
||||
reasons = [text for keys, text in _REASONS if any(_marker(raw, key) for key in keys)]
|
||||
if str(raw.get("update_exe") or "0") != "0":
|
||||
reasons.append("an update waits for a restart (UpdateExeVolatile)")
|
||||
rename = _rename(raw)
|
||||
return [*reasons, rename] if rename else reasons
|
||||
|
||||
|
||||
def _restart_required(raw: dict[str, Any]) -> bool:
|
||||
"""Windows Update or component servicing waits for a restart; see the module."""
|
||||
return any(
|
||||
_marker(raw, key) for key in ("wu_reboot_required", "wu_reboot_key", "cbs_reboot_pending")
|
||||
)
|
||||
|
||||
|
||||
def _auto_updates(raw: dict[str, Any]) -> bool | None:
|
||||
"""Whether the host installs updates on its own; see the module."""
|
||||
if str(raw.get("no_auto_update") or "") == "1":
|
||||
return False
|
||||
policy = _AU_OPTIONS.get(str(raw.get("au_options") or ""))
|
||||
if policy is not None:
|
||||
return policy
|
||||
if int(raw.get("product_type") or 0) == _WORKSTATION:
|
||||
return True
|
||||
return _AU_OPTIONS.get(str(raw.get("local_au_options") or ""))
|
||||
|
||||
|
||||
def _registry_time(value: Any) -> int | None:
|
||||
"""``Results\\Install``'s ``LastSuccessTime``, ``YYYY-MM-DD HH:MM:SS`` in UTC."""
|
||||
try:
|
||||
return calendar.timegm(time.strptime(str(value or ""), "%Y-%m-%d %H:%M:%S"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _last_success(raw: dict[str, Any]) -> int | None:
|
||||
"""The latest successful installation any of the three sources knows of."""
|
||||
known = [*_as_list(raw.get("installs")), raw.get("au_last_install")]
|
||||
known.append(_registry_time(raw.get("legacy_last_install")))
|
||||
times = [int(t) for t in known if isinstance(t, int | float) and t > 0]
|
||||
return max(times, default=None)
|
||||
|
||||
|
||||
def _filesystems(raw: dict[str, Any]) -> list[FilesystemUsageDict] | None:
|
||||
drive = raw.get("system_drive")
|
||||
if not isinstance(drive, dict):
|
||||
return None
|
||||
total, free = int(drive.get("size") or 0), int(drive.get("free") or 0)
|
||||
return [
|
||||
{
|
||||
"mountpoint": f"{drive.get('drive') or ''}\\",
|
||||
"total": total,
|
||||
"used": total - free,
|
||||
"available": free,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def parse_host_status(raw: dict[str, Any]) -> HostStatusDict:
|
||||
"""``_PS_HOST_STATUS``'s JSON as the host status; see the module."""
|
||||
reasons = _restart_reasons(raw)
|
||||
auto = _auto_updates(raw)
|
||||
return {
|
||||
"reboot_required": _restart_required(raw),
|
||||
"reboot_reason": "; ".join(reasons) or None,
|
||||
"auto_updates": auto,
|
||||
"auto_updates_last_success": _last_success(raw),
|
||||
"auto_updates_interval": MONTHLY if auto else None,
|
||||
"filesystems": _filesystems(raw),
|
||||
}
|
||||
|
||||
|
||||
class WindowsHostStatusMixin:
|
||||
"""``get_host_status`` from Windows Update and the registry; the driver carries the
|
||||
script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_host_status(self) -> HostStatusDict:
|
||||
"""Whether the host needs a restart and installs updates on its own; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_host_status(json_object(self._run_raw(_PS_HOST_STATUS), "host status"))
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Local accounts on Windows as napalm-device-types' ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsOsUsersMixin` gives the driver ``get_os_users``. One script reads the
|
||||
accounts (``Get-LocalUser``), the local groups with their members
|
||||
(``Get-LocalGroupMember``) and the profiles' paths (``Win32_UserProfile``).
|
||||
|
||||
Windows names an account by its security identifier, not a number:
|
||||
|
||||
* ``uid`` is the relative identifier, the SID's last part: 500 for the built-in
|
||||
Administrator, 501 Guest, 1000 and up for accounts created. ``sid`` is the whole SID.
|
||||
* ``gid`` is 513, the primary group every local account has ("None"); Windows offers
|
||||
no other for them.
|
||||
* ``home`` is the profile's folder, empty for an account that never logged on and so
|
||||
has none; ``shell`` is empty.
|
||||
* ``groups`` are the local groups the account is a direct member of. A group whose
|
||||
members cannot be read -- ``Get-LocalGroupMember`` fails on a member SID it cannot
|
||||
resolve, and the ADSI fallback failed too -- names nobody.
|
||||
|
||||
These are the host's own accounts. Who may log in and how (administrators, RDP rights,
|
||||
domain accounts) is the login accounts' contract, not this one. A domain controller
|
||||
has no local accounts -- ``Get-LocalUser`` would list the domain's -- and a host without
|
||||
the LocalAccounts module cannot list them; both raise ``NotImplementedError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import UserDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PS_OS_USERS = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$role = [int](Get-CimInstance -ClassName Win32_ComputerSystem).DomainRole
|
||||
$local = [bool](Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue)
|
||||
$users = @()
|
||||
$groups = @()
|
||||
if ($role -lt 4 -and $local) {
|
||||
$homes = @{}
|
||||
Get-CimInstance -ClassName Win32_UserProfile | ForEach-Object {
|
||||
$homes[[string]$_.SID] = [string]$_.LocalPath
|
||||
}
|
||||
$users = @(Get-LocalUser | ForEach-Object {
|
||||
$sid = [string]$_.SID
|
||||
[pscustomobject]@{ name = [string]$_.Name; sid = $sid; home = $homes[$sid] }
|
||||
})
|
||||
$groups = @(Get-LocalGroup | ForEach-Object {
|
||||
$group = $_
|
||||
$members = $null
|
||||
try {
|
||||
$members = @(Get-LocalGroupMember -SID $group.SID | ForEach-Object { [string]$_.SID })
|
||||
} catch {
|
||||
try {
|
||||
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME/$($group.Name),group"
|
||||
$members = @($adsi.psbase.Invoke('Members') | ForEach-Object {
|
||||
$bytes = $_.GetType().InvokeMember('objectSid', 'GetProperty', $null, $_, $null)
|
||||
(New-Object System.Security.Principal.SecurityIdentifier($bytes, 0)).Value
|
||||
})
|
||||
} catch { $members = $null }
|
||||
}
|
||||
[pscustomobject]@{ name = [string]$group.Name; members = $members }
|
||||
})
|
||||
}
|
||||
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
domain_role = $role
|
||||
local_accounts = $local
|
||||
users = $users
|
||||
groups = $groups
|
||||
})
|
||||
"""
|
||||
|
||||
#: ``Win32_ComputerSystem.DomainRole`` of a backup and of a primary domain controller.
|
||||
_DOMAIN_CONTROLLER = 4
|
||||
#: DOMAIN_GROUP_RID_USERS: the primary group of every local account.
|
||||
_PRIMARY_GROUP = 513
|
||||
|
||||
|
||||
def _rid(sid: str) -> int:
|
||||
tail = sid.rsplit("-", 1)[-1]
|
||||
return int(tail) if tail.isdigit() else 0
|
||||
|
||||
|
||||
def _memberships(groups: list[Any]) -> dict[str, list[str]]:
|
||||
"""SID -> the names of the groups it is a direct member of, in the order read."""
|
||||
member_of: dict[str, list[str]] = {}
|
||||
for group in groups:
|
||||
members = group.get("members")
|
||||
if members is None:
|
||||
logger.warning("the members of local group %r could not be read", group.get("name"))
|
||||
continue
|
||||
for sid in _as_list(members):
|
||||
member_of.setdefault(str(sid), []).append(str(group["name"]))
|
||||
return member_of
|
||||
|
||||
|
||||
def parse_os_users(raw: dict[str, Any]) -> list[UserDict]:
|
||||
"""``_PS_OS_USERS``'s JSON as ``UserDict``s; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
"""
|
||||
if int(raw.get("domain_role") or 0) >= _DOMAIN_CONTROLLER:
|
||||
raise NotImplementedError(
|
||||
"a domain controller has no local accounts; its accounts are the domain's"
|
||||
)
|
||||
if not raw.get("local_accounts"):
|
||||
raise NotImplementedError("Get-LocalUser is not available on this host")
|
||||
member_of = _memberships(_as_list(raw.get("groups")))
|
||||
users: list[UserDict] = []
|
||||
for user in _as_list(raw.get("users")):
|
||||
sid = str(user.get("sid") or "")
|
||||
users.append(
|
||||
{
|
||||
"username": str(user["name"]),
|
||||
"uid": _rid(sid),
|
||||
"gid": _PRIMARY_GROUP,
|
||||
"home": str(user.get("home") or ""),
|
||||
"shell": "",
|
||||
"groups": member_of.get(sid, []),
|
||||
"sid": sid,
|
||||
}
|
||||
)
|
||||
return users
|
||||
|
||||
|
||||
class WindowsOsUsersMixin:
|
||||
"""``get_os_users`` from the LocalAccounts cmdlets; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_os_users(self) -> list[UserDict]:
|
||||
"""The host's local accounts; see the module.
|
||||
|
||||
:raises NotImplementedError: on a domain controller, or without ``Get-LocalUser``.
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_os_users(json_object(self._run_raw(_PS_OS_USERS), "local account"))
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Installed software on Windows as packages (NetOrk/netork#2890).
|
||||
|
||||
:class:`WindowsPackagesMixin` gives the driver napalm-device-types' ``get_packages``
|
||||
(``PackageDict``) from the machine-wide Uninstall keys, the list "Apps & features" and
|
||||
``winget list`` read too:
|
||||
|
||||
* ``HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall``: the host's native
|
||||
programs (``x64``, ``arm64`` on ARM, ``x86`` on a 32-bit Windows);
|
||||
* ``HKLM\\SOFTWARE\\WOW6432Node\\...\\Uninstall``: the 32-bit programs of a 64-bit
|
||||
Windows (``x86``).
|
||||
|
||||
A 32-bit and a 64-bit install of one program stay two packages, told apart by
|
||||
``architecture``. Left out: keys without a ``DisplayName``, ``SystemComponent=1``
|
||||
(parts Windows or a suite hides from the list) and entries with a ``ParentKeyName``
|
||||
(updates listed under their product; Windows' own updates are the update history's).
|
||||
``source`` is ``msi`` for a Windows Installer package (``WindowsInstaller=1``), else
|
||||
``exe``; ``size`` is ``EstimatedSize`` (KiB) in bytes, 0 where none is given;
|
||||
``publisher`` is the vendor the program names.
|
||||
|
||||
Not read: per-user installs (a user's own ``HKU`` hive -- over WinRM ``HKCU`` is the
|
||||
connecting account's, and the hives of whoever is logged on would make the list change
|
||||
with them), Store and MSIX apps, and winget, which is a per-user App Execution Alias
|
||||
that does not work reliably in a WinRM session. Nothing is installed or removed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import PackageDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
|
||||
_UNINSTALL = r"Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
|
||||
_PS_PACKAGES = rf"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$native = switch ($env:PROCESSOR_ARCHITECTURE) {{
|
||||
'ARM64' {{ 'arm64' }}
|
||||
'x86' {{ 'x86' }}
|
||||
default {{ 'x64' }}
|
||||
}}
|
||||
$keys = @(
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\{_UNINSTALL}'; arch = $native }},
|
||||
[pscustomobject]@{{ path = 'HKLM:\SOFTWARE\WOW6432Node\{_UNINSTALL}'; arch = 'x86' }}
|
||||
)
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(
|
||||
foreach ($key in $keys) {{
|
||||
if (Test-Path -LiteralPath $key.path) {{
|
||||
Get-ChildItem -LiteralPath $key.path -ErrorAction SilentlyContinue | ForEach-Object {{
|
||||
[pscustomobject]@{{
|
||||
key = [string]$_.PSChildName
|
||||
arch = $key.arch
|
||||
name = [string]$_.GetValue('DisplayName')
|
||||
version = [string]$_.GetValue('DisplayVersion')
|
||||
publisher = [string]$_.GetValue('Publisher')
|
||||
system = [string]$_.GetValue('SystemComponent')
|
||||
parent = [string]$_.GetValue('ParentKeyName')
|
||||
msi = [string]$_.GetValue('WindowsInstaller')
|
||||
size = [string]$_.GetValue('EstimatedSize')
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class WindowsPackageDict(PackageDict):
|
||||
"""A program from the Uninstall keys, with whose it is and which build."""
|
||||
|
||||
publisher: str
|
||||
architecture: str # x64, x86 or arm64
|
||||
|
||||
|
||||
def _size(value: Any) -> int:
|
||||
text = str(value or "").strip()
|
||||
return int(text) * 1024 if text.isdigit() else 0
|
||||
|
||||
|
||||
def _listed(entry: dict[str, Any]) -> bool:
|
||||
"""A program the host lists as installed: named, not hidden, not an update."""
|
||||
return bool(
|
||||
str(entry.get("name") or "").strip()
|
||||
and str(entry.get("system") or "") != "1"
|
||||
and not str(entry.get("parent") or "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _package(entry: dict[str, Any]) -> WindowsPackageDict:
|
||||
return {
|
||||
"name": str(entry["name"]).strip(),
|
||||
"version": str(entry.get("version") or "").strip(),
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": _size(entry.get("size")),
|
||||
"source": "msi" if str(entry.get("msi") or "") == "1" else "exe",
|
||||
"publisher": str(entry.get("publisher") or "").strip(),
|
||||
"architecture": str(entry.get("arch") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_packages(raw: Any) -> list[PackageDict]:
|
||||
"""``_PS_PACKAGES``'s JSON as packages, by name; see the module."""
|
||||
packages = [_package(e) for e in _as_list(raw) if isinstance(e, dict) and _listed(e)]
|
||||
packages.sort(key=lambda p: (p["name"].lower(), p["architecture"]))
|
||||
return list(packages)
|
||||
|
||||
|
||||
class WindowsPackagesMixin:
|
||||
"""``get_packages`` from the Uninstall keys; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_ps(self, script: str) -> Any: ...
|
||||
|
||||
def get_packages(self) -> list[PackageDict]:
|
||||
"""The programs installed for the whole machine; see the module."""
|
||||
return parse_packages(self._run_ps(_PS_PACKAGES))
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Running processes on Windows, shaped like ``ps`` output (NetOrk/netork#2889).
|
||||
|
||||
:class:`WindowsProcessesMixin` gives the driver napalm-device-types' ``get_processes``
|
||||
(``ProcessDict``). One script reads two sources and the join happens here:
|
||||
|
||||
* ``Win32_Process``: PID, parent, command line, start (``CreationDate``), the CPU time
|
||||
(``KernelModeTime`` + ``UserModeTime``, in 100 ns), ``WorkingSetSize`` and
|
||||
``VirtualSize``. Read first: it is the list.
|
||||
* ``Get-Process -IncludeUserName``: the owner, one call for all processes instead of a
|
||||
``GetOwner()`` per process. It needs an elevated session, which netOrk's WinRM
|
||||
administrator has; without one the script falls back to ``Get-Process`` and the owner
|
||||
is unknown (empty).
|
||||
|
||||
A process is reported only when both saw it with the same start: one that exited between
|
||||
the two reads is dropped rather than half-filled, and a PID reused in between is another
|
||||
process. PID 0, the System Idle Process, is no process and is left out, as ``ps`` leaves
|
||||
it out.
|
||||
|
||||
The values follow ``ps``: ``cpu`` is the CPU time over the time since the start, per
|
||||
logical processor, so 0-100; ``memory`` the working set over the visible memory;
|
||||
``vsz`` and ``rss`` in KiB; ``started`` as ``lstart`` prints it, in the host's local
|
||||
time. Windows has no controlling terminal and no process state of that kind: ``tty``
|
||||
and ``state`` are empty. A process without a readable command line (``System``,
|
||||
protected processes) shows its image name. Command lines are reported as the host
|
||||
gives them, as ``ps`` does on Linux.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.models import ProcessDict
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_PROCESSES = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Unix($t) { if ($t) { ([DateTimeOffset]$t).ToUnixTimeSeconds() } else { $null } }
|
||||
function Offset($t) { if ($t) { [int]([DateTimeOffset]$t).Offset.TotalMinutes } else { 0 } }
|
||||
$os = Get-CimInstance -ClassName Win32_OperatingSystem
|
||||
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
|
||||
$processes = @(Get-CimInstance -ClassName Win32_Process | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
pid = [int]$_.ProcessId
|
||||
ppid = [int]$_.ParentProcessId
|
||||
name = [string]$_.Name
|
||||
command = [string]$_.CommandLine
|
||||
started = Unix $_.CreationDate
|
||||
offset = Offset $_.CreationDate
|
||||
cpu = [int64]$_.KernelModeTime + [int64]$_.UserModeTime
|
||||
ws = [int64]$_.WorkingSetSize
|
||||
vsz = [int64]$_.VirtualSize
|
||||
}
|
||||
})
|
||||
try { $running = @(Get-Process -IncludeUserName) } catch { $running = @(Get-Process) }
|
||||
$owners = @($running | ForEach-Object {
|
||||
$start = $null
|
||||
try { $start = Unix $_.StartTime } catch { }
|
||||
[pscustomobject]@{ pid = [int]$_.Id; user = [string]$_.UserName; started = $start }
|
||||
})
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject ([pscustomobject]@{
|
||||
now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
cores = [int]$cs.NumberOfLogicalProcessors
|
||||
memory_kib = [int64]$os.TotalVisibleMemorySize
|
||||
processes = $processes
|
||||
owners = $owners
|
||||
})
|
||||
"""
|
||||
|
||||
#: How far the two sources' starts of one process may differ: they round differently.
|
||||
_SAME_START = 2
|
||||
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
||||
|
||||
|
||||
def _lstart(started: int | None, offset_minutes: int) -> str:
|
||||
"""Unix time in the host's local time, as ``ps -o lstart`` prints it in the C locale."""
|
||||
if started is None:
|
||||
return ""
|
||||
t = datetime.fromtimestamp(started, UTC) + timedelta(minutes=offset_minutes)
|
||||
return f"{_DAYS[t.weekday()]} {_MONTHS[t.month - 1]} {t.day:2d} {t:%H:%M:%S} {t.year}"
|
||||
|
||||
|
||||
class _Host:
|
||||
"""What the reading says about the host as a whole."""
|
||||
|
||||
def __init__(self, raw: dict[str, Any]) -> None:
|
||||
self.now = int(raw.get("now") or 0)
|
||||
self.cores = max(int(raw.get("cores") or 1), 1)
|
||||
self.memory_kib = int(raw.get("memory_kib") or 0)
|
||||
|
||||
def cpu(self, cpu_100ns: int, started: int | None) -> float:
|
||||
if started is None:
|
||||
return 0.0
|
||||
elapsed = max(self.now - started, 1)
|
||||
return round(min(cpu_100ns / 10_000_000 / elapsed / self.cores * 100, 100.0), 1)
|
||||
|
||||
def memory(self, rss_kib: int) -> float:
|
||||
return round(rss_kib * 100 / self.memory_kib, 1) if self.memory_kib else 0.0
|
||||
|
||||
|
||||
def _started(entry: dict[str, Any]) -> int | None:
|
||||
value = entry.get("started")
|
||||
return int(value) if value is not None else None
|
||||
|
||||
|
||||
def _same_process(entry: dict[str, Any], owner: dict[str, Any]) -> bool:
|
||||
"""False when ``Get-Process`` saw another start under this PID: it was reused."""
|
||||
ours, theirs = _started(entry), _started(owner)
|
||||
return ours is None or theirs is None or abs(ours - theirs) <= _SAME_START
|
||||
|
||||
|
||||
def _process(entry: dict[str, Any], owner: dict[str, Any], host: _Host) -> ProcessDict:
|
||||
started = _started(entry)
|
||||
rss = int(entry.get("ws") or 0) // 1024
|
||||
return {
|
||||
"pid": int(entry["pid"]),
|
||||
"ppid": int(entry.get("ppid") or 0),
|
||||
"user": str(owner.get("user") or ""),
|
||||
"cpu": host.cpu(int(entry.get("cpu") or 0), started),
|
||||
"memory": host.memory(rss),
|
||||
"vsz": int(entry.get("vsz") or 0) // 1024,
|
||||
"rss": rss,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
"started": _lstart(started, int(entry.get("offset") or 0)),
|
||||
"command": str(entry.get("command") or entry.get("name") or ""),
|
||||
}
|
||||
|
||||
|
||||
def parse_processes(raw: dict[str, Any]) -> list[ProcessDict]:
|
||||
"""``_PS_PROCESSES``'s JSON as ``ProcessDict``s by PID; see the module for the join."""
|
||||
host = _Host(raw)
|
||||
owners = {int(o["pid"]): o for o in _as_list(raw.get("owners"))}
|
||||
processes = []
|
||||
for entry in _as_list(raw.get("processes")):
|
||||
owner = owners.get(int(entry["pid"]))
|
||||
if not entry["pid"] or owner is None or not _same_process(entry, owner):
|
||||
continue
|
||||
processes.append(_process(entry, owner, host))
|
||||
return sorted(processes, key=lambda p: p["pid"])
|
||||
|
||||
|
||||
class WindowsProcessesMixin:
|
||||
"""``get_processes`` from ``Win32_Process`` and ``Get-Process``; the driver carries
|
||||
the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_processes(self) -> list[ProcessDict]:
|
||||
"""A snapshot of the running processes, shaped like ``ps``; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_processes(json_object(self._run_raw(_PS_PROCESSES), "process"))
|
||||
@@ -9,11 +9,9 @@ says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and th
|
||||
host's time zone; Python only normalises. Every task is a job ``task:<path><name>``
|
||||
whose schedule is a summary of its triggers. A task under ``\\Microsoft\\`` is the
|
||||
``platform``'s, any other the ``admin``'s -- Windows does not say which software
|
||||
installed a task -- except the driver's own Windows Update runs under
|
||||
``\\napalm-windows\\``, an ``application``'s that offer nothing; and a task in the root
|
||||
folder whose description starts with ``napalm-scheduled-job: <its name>`` is an
|
||||
``application``'s, read back as the cron expression and command it was written with
|
||||
(:mod:`napalm_windows.task_xml`). Its
|
||||
installed a task -- and a task in the root folder whose description starts with
|
||||
``napalm-scheduled-job: <its name>`` is an ``application``'s, read back as the cron
|
||||
expression and command it was written with (:mod:`napalm_windows.task_xml`). Its
|
||||
digest covers its triggers as well, so triggers changed by hand are a change. A
|
||||
reading whose task count does not match, or whose JSON is cut short, raises.
|
||||
|
||||
@@ -54,7 +52,6 @@ from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.task_xml import JOB_MARKER, SCHEDULE_LINE, own_command, task_xml
|
||||
from napalm_windows.time_zones import iana_time_zone
|
||||
from napalm_windows.transport import PowerShellError
|
||||
from napalm_windows.windows_update_run import TASK_PATH
|
||||
|
||||
# Every task with its run info. Times leave the host as ISO 8601 in UTC; a task
|
||||
# whose run info cannot be read keeps its definition and loses only its times.
|
||||
@@ -283,8 +280,6 @@ def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None:
|
||||
|
||||
|
||||
def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]:
|
||||
if str(task.get("path") or "").lower() == TASK_PATH.lower():
|
||||
return [] # an update run's task: deleted when its run ends
|
||||
verbs = ["enable", "disable"]
|
||||
if enabled and task.get("on_demand") is not False:
|
||||
verbs.append("run")
|
||||
@@ -308,25 +303,16 @@ def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None
|
||||
return _Definition(
|
||||
own.schedule or triggers, kind, own.command or command, "application", own.description
|
||||
)
|
||||
platform = path.lower().startswith("\\microsoft\\")
|
||||
return _Definition(
|
||||
triggers,
|
||||
"triggers",
|
||||
command,
|
||||
_owner(path),
|
||||
"platform" if platform else "admin",
|
||||
str(task.get("description") or "").strip(),
|
||||
)
|
||||
|
||||
|
||||
def _owner(path: str) -> str:
|
||||
"""Who a task that no application wrote as a job belongs to, by its folder: the
|
||||
platform's under ``\\Microsoft\\``, the driver's own update runs' under
|
||||
:data:`~napalm_windows.windows_update_run.TASK_PATH`, any other the admin's."""
|
||||
folder = path.lower()
|
||||
if folder == TASK_PATH.lower():
|
||||
return "application"
|
||||
return "platform" if folder.startswith("\\microsoft\\") else "admin"
|
||||
|
||||
|
||||
def _task_job(task: dict[str, Any]) -> ScheduledJobDict:
|
||||
path, name = str(task.get("path") or _ROOT), str(task.get("name") or "")
|
||||
triggers = "; ".join(_trigger(t) for t in _as_list(task.get("triggers")))
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""The SMBIOS identity of a Windows host: what ties it to its BMC (NetOrk/netork#2888).
|
||||
|
||||
:class:`WindowsSystemIdentityMixin` gives the driver ``get_system_identity`` with the
|
||||
shape and the placeholder rules of napalm-device-types' ``SystemIdentityMixin``, which
|
||||
reads Linux' DMI files. Windows reads the same SMBIOS tables through its CIM classes,
|
||||
in one script of its own -- not folded into ``get_facts``, so a class only the identity
|
||||
needs cannot fail the facts:
|
||||
|
||||
* ``Win32_ComputerSystemProduct``: ``UUID`` (the system UUID, which Windows decodes from
|
||||
SMBIOS 2.6+ the way dmidecode does) and ``IdentifyingNumber`` (the product serial);
|
||||
* ``Win32_BaseBoard``: ``SerialNumber``, of the first board;
|
||||
* ``Win32_BIOS``: ``Manufacturer``, ``SMBIOSBIOSVersion`` and ``ReleaseDate``. CIM gives
|
||||
the date as midnight UTC; it travels as Unix time and is read as that UTC day.
|
||||
|
||||
Vendor placeholders ("To be filled by O.E.M.", all-F UUIDs) read as empty
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import clean_system_identity
|
||||
from napalm_device_types.system_identity import SystemIdentityDict
|
||||
|
||||
from napalm_windows._reading import json_object
|
||||
|
||||
_PS_SYSTEM_IDENTITY = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$product = Get-CimInstance -ClassName Win32_ComputerSystemProduct
|
||||
$board = @(Get-CimInstance -ClassName Win32_BaseBoard) | Select-Object -First 1
|
||||
$bios = Get-CimInstance -ClassName Win32_BIOS
|
||||
[pscustomobject]@{
|
||||
uuid = [string]$product.UUID
|
||||
product_serial = [string]$product.IdentifyingNumber
|
||||
board_serial = if ($board) { [string]$board.SerialNumber } else { $null }
|
||||
bios_vendor = [string]$bios.Manufacturer
|
||||
bios_version = [string]$bios.SMBIOSBIOSVersion
|
||||
bios_date = if ($bios.ReleaseDate) {
|
||||
([DateTimeOffset]$bios.ReleaseDate).ToUnixTimeSeconds()
|
||||
} else { $null }
|
||||
} | ConvertTo-Json -Compress
|
||||
"""
|
||||
|
||||
|
||||
def _text(raw: dict[str, Any], key: str) -> str:
|
||||
return str(raw.get(key) or "")
|
||||
|
||||
|
||||
def _utc_day(value: Any) -> str:
|
||||
"""Unix time as its UTC day, ``YYYY-MM-DD``; empty for none."""
|
||||
if not isinstance(value, int | float) or isinstance(value, bool):
|
||||
return ""
|
||||
return datetime.fromtimestamp(value, UTC).date().isoformat()
|
||||
|
||||
|
||||
def parse_system_identity(raw: dict[str, Any]) -> SystemIdentityDict:
|
||||
"""``_PS_SYSTEM_IDENTITY``'s JSON as napalm-device-types' identity, placeholders empty."""
|
||||
return clean_system_identity(
|
||||
system_uuid=_text(raw, "uuid"),
|
||||
product_serial=_text(raw, "product_serial"),
|
||||
board_serial=_text(raw, "board_serial"),
|
||||
bios_vendor=_text(raw, "bios_vendor"),
|
||||
bios_version=_text(raw, "bios_version"),
|
||||
bios_date=_utc_day(raw.get("bios_date")),
|
||||
)
|
||||
|
||||
|
||||
class WindowsSystemIdentityMixin:
|
||||
"""``get_system_identity`` from the CIM classes; the driver carries the script."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def get_system_identity(self) -> SystemIdentityDict:
|
||||
"""The host's SMBIOS identity and system firmware, each value empty when unknown
|
||||
or a vendor placeholder; see the module.
|
||||
|
||||
:raises ValueError: when the reading came back empty.
|
||||
"""
|
||||
return parse_system_identity(
|
||||
json_object(self._run_raw(_PS_SYSTEM_IDENTITY), "system identity")
|
||||
)
|
||||
@@ -27,10 +27,10 @@ from napalm_device_types import FingerprintRule, OSDriver, PortSpec
|
||||
from napalm_device_types.models import ListeningSocketDict, ListeningSocketsDict, ServiceDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
from napalm_windows.host_basics import WindowsHostBasicsMixin
|
||||
from napalm_windows.scheduled_tasks import WindowsScheduledJobsMixin
|
||||
from napalm_windows.time_sync import WindowsTimeSyncMixin
|
||||
from napalm_windows.transport import PowerShellError, PsrpTransport
|
||||
from napalm_windows.windows_update import WindowsUpdateMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -262,7 +262,9 @@ def _is_noise_route(destination: str) -> bool:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsDriver(WindowsScheduledJobsMixin, WindowsTimeSyncMixin, WindowsUpdateMixin, OSDriver):
|
||||
class WindowsDriver(
|
||||
WindowsHostBasicsMixin, WindowsScheduledJobsMixin, WindowsTimeSyncMixin, OSDriver
|
||||
):
|
||||
"""NAPALM driver for Windows Server 2016+ and Windows 10/11.
|
||||
|
||||
``optional_args``:
|
||||
|
||||
@@ -1,445 +0,0 @@
|
||||
"""Windows Update over PowerShell Remoting: search, pending updates, history (netork#2892).
|
||||
|
||||
:class:`WindowsUpdateMixin` implements napalm-device-types'
|
||||
:class:`~napalm_device_types.updates.UpdateMixin` for the driver with the Windows Update
|
||||
Agent's COM API (``Microsoft.Update.Session``).
|
||||
|
||||
**The search is the refresh.** ``refresh_available_updates`` searches the source the
|
||||
host is configured for (Windows Update, or its WSUS server) for what is not installed
|
||||
and not hidden, software only -- no drivers. A search takes minutes, so the poll never
|
||||
runs one: the search keeps its reading in the registry (:data:`STORE`, under
|
||||
``HKLM\\SOFTWARE``, where only administrators and SYSTEM may write), and
|
||||
``get_available_updates`` reads it back, leaving out what the host's own history shows
|
||||
installed since. Before the first search there is nothing to read from, which is
|
||||
napalm-device-types' :exc:`PackageIndexMissing`: a refresh cures it.
|
||||
|
||||
**An update is named by what it keeps from month to month** (:func:`update_name`): its
|
||||
title without the month, the KB article and the version. Next month's cumulative update
|
||||
takes this one's place under the same name, so "pending since" is not reset every
|
||||
month. The KB articles are the update's ``new_version`` and ``advisories``; its
|
||||
``CveIDs`` and ``MsrcSeverity`` go along as ``cves`` and ``vendor_severity``. A security
|
||||
update, a definition update or one naming CVEs is ``security``. Optional updates
|
||||
(previews Windows does not install by itself) and feature upgrades are not pending:
|
||||
this path installs neither.
|
||||
|
||||
**The history** is ``QueryHistory``, its newest 300 entries, one transaction each;
|
||||
``requested_by`` is the ``ClientApplicationID`` that asked (``UpdateOrchestrator``,
|
||||
``AutomaticUpdates``, ``napalm-windows`` for the driver's own runs).
|
||||
|
||||
**Installing** is :mod:`napalm_windows.windows_update_run`: Windows refuses a download
|
||||
or an install over a network logon, so it runs in a one-shot SYSTEM task.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
from napalm_device_types import PackageIndexMissing
|
||||
from napalm_device_types.models import ApplyUpdatesResultDict, UpdateDict
|
||||
from napalm_device_types.updates import UpdateHistoryDict, UpdateHistoryPackageDict, UpdateMixin
|
||||
|
||||
from napalm_windows._powershell import _as_list
|
||||
from napalm_windows.transport import PowerShellError
|
||||
from napalm_windows.windows_update_run import install
|
||||
|
||||
#: Where the search keeps its reading, and the runs theirs.
|
||||
STORE = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate"
|
||||
|
||||
#: What every search asks: not installed, not hidden, no drivers.
|
||||
_CRITERIA = "IsInstalled=0 and IsHidden=0 and Type='Software'"
|
||||
|
||||
# The search, kept in STORE for the poll, and printed for the refresh. Its times are
|
||||
# unix seconds; the WSUS server is named where group policy points the host at one.
|
||||
_PS_WU_SEARCH = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$started = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
$session = New-Object -ComObject Microsoft.Update.Session
|
||||
$session.ClientApplicationID = 'napalm-windows'
|
||||
$found = $session.CreateUpdateSearcher().Search("__CRITERIA__")
|
||||
$rows = @(foreach ($u in $found.Updates) {
|
||||
[pscustomobject]@{
|
||||
id = [string]$u.Identity.UpdateID
|
||||
revision = [int]$u.Identity.RevisionNumber
|
||||
title = [string]$u.Title
|
||||
kb = @(foreach ($k in $u.KBArticleIDs) { [string]$k })
|
||||
cves = @(foreach ($c in $u.CveIDs) { [string]$c })
|
||||
severity = [string]$u.MsrcSeverity
|
||||
classifications = @(foreach ($c in $u.Categories) {
|
||||
if ([string]$c.Type -eq 'UpdateClassification') { [string]$c.CategoryID }
|
||||
})
|
||||
browse_only = [bool]$u.BrowseOnly
|
||||
interactive = [bool]$u.InstallationBehavior.CanRequestUserInput
|
||||
reboot = [int]$u.InstallationBehavior.RebootBehavior
|
||||
eula_accepted = [bool]$u.EulaAccepted
|
||||
downloaded = [bool]$u.IsDownloaded
|
||||
}
|
||||
})
|
||||
$policy = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate'
|
||||
$wsus = $null
|
||||
if ((Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath "$policy\AU").UseWUServer -eq 1) {
|
||||
$wsus = [string](Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath $policy).WUServer
|
||||
}
|
||||
$reading = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
searched_at = $started
|
||||
finished_at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||||
result = [int]$found.ResultCode
|
||||
wsus = $wsus
|
||||
updates = $rows
|
||||
})
|
||||
$store = '__STORE__'
|
||||
if (-not (Test-Path -LiteralPath $store)) { New-Item -Path $store -Force | Out-Null }
|
||||
Set-ItemProperty -LiteralPath $store -Name Search -Value $reading
|
||||
$reading
|
||||
""".replace("__CRITERIA__", _CRITERIA).replace("__STORE__", STORE)
|
||||
|
||||
# What the last search found, and what the host installed (by its history) -- no search.
|
||||
_PS_WU_PENDING = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$search = (Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath '__STORE__').Search
|
||||
$installed = @()
|
||||
$history_error = $null
|
||||
if ($search) {
|
||||
try {
|
||||
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
|
||||
$count = $searcher.GetTotalHistoryCount()
|
||||
if ($count -gt 0) {
|
||||
$installed = @(foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
|
||||
if ($h.Operation -eq 1 -and ($h.ResultCode -eq 2 -or $h.ResultCode -eq 3)) {
|
||||
[pscustomobject]@{
|
||||
id = [string]$h.UpdateIdentity.UpdateID
|
||||
revision = [int]$h.UpdateIdentity.RevisionNumber
|
||||
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
$history_error = $_.Exception.Message
|
||||
}
|
||||
}
|
||||
ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]@{
|
||||
search = $search
|
||||
installed = $installed
|
||||
history_error = $history_error
|
||||
})
|
||||
""".replace("__STORE__", STORE)
|
||||
|
||||
# The newest 300 entries of the host's update history; times are UTC, as unix seconds.
|
||||
_PS_WU_HISTORY = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$searcher = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateSearcher()
|
||||
$count = $searcher.GetTotalHistoryCount()
|
||||
ConvertTo-Json -Compress -Depth 3 -InputObject @(if ($count -gt 0) {
|
||||
foreach ($h in $searcher.QueryHistory(0, [Math]::Min($count, 300))) {
|
||||
[pscustomobject]@{
|
||||
id = [string]$h.UpdateIdentity.UpdateID
|
||||
revision = [int]$h.UpdateIdentity.RevisionNumber
|
||||
title = [string]$h.Title
|
||||
at = [int64]($h.Date - [datetime]'1970-01-01').TotalSeconds
|
||||
operation = [int]$h.Operation
|
||||
result = [int]$h.ResultCode
|
||||
hresult = [int64]$h.HResult
|
||||
client = [string]$h.ClientApplicationID
|
||||
}
|
||||
}
|
||||
})
|
||||
"""
|
||||
|
||||
#: The update classifications (``ICategory.CategoryID``, the same in every language).
|
||||
_SECURITY_UPDATES = "0fa1201d-4330-4fa8-8ae9-b877473b6441"
|
||||
_DEFINITION_UPDATES = "e0789628-ce08-4437-be74-2495b842f43b"
|
||||
_UPGRADES = "3689bdc8-b205-4af4-8d4a-a63924c5e9d5"
|
||||
|
||||
#: napalm-device-types' package name rule (``UpdateMixin.apply_updates``).
|
||||
NAME = re.compile(r"[a-zA-Z0-9_\-+.]+")
|
||||
#: Short enough for a store that keeps a package name in 255 characters.
|
||||
NAME_MAX = 200
|
||||
|
||||
_DATE_PREFIX = re.compile(r"^\s*\d{4}-\d{2}\s+")
|
||||
_VERSIONED = re.compile(r"\([^()]*\d+\.\d+[^()]*\)") # "(Version 1.441.120.0)", "(26100.2894)"
|
||||
_KB = re.compile(r"\(?\bKB\d+\b\)?", re.IGNORECASE)
|
||||
_V_SUFFIX = re.compile(r"\s+-?\s*v\d+(?:\.\d+)+", re.IGNORECASE) # "- v5.141"
|
||||
_NOT_NAME = re.compile(r"[^A-Za-z0-9._+-]+")
|
||||
_DASHES = re.compile(r"-{2,}")
|
||||
_KB_IN_TITLE = re.compile(r"\bKB(\d+)\b", re.IGNORECASE)
|
||||
|
||||
#: MsrcSeverity, lowest first.
|
||||
_SEVERITIES = ("Low", "Moderate", "Important", "Critical")
|
||||
|
||||
#: IUpdateHistoryEntry.ResultCode: what a finished entry other than success says.
|
||||
_RESULTS = {3: "succeeded with errors", 4: "failed", 5: "aborted"}
|
||||
_IN_PROGRESS = 1
|
||||
_UNINSTALL = 2
|
||||
|
||||
|
||||
def update_name(title: str, kbs: list[str], update_id: str) -> str:
|
||||
"""The name of an update: its title without month, KB article and version, as a
|
||||
package name (:data:`NAME`); its KB article or its ID when nothing is left."""
|
||||
text = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode()
|
||||
for pattern in (_DATE_PREFIX, _VERSIONED, _KB, _V_SUFFIX):
|
||||
text = pattern.sub(" ", text)
|
||||
name = _DASHES.sub("-", _NOT_NAME.sub("-", text)).strip("-.")
|
||||
name = name[:NAME_MAX].rstrip("-.")
|
||||
if name:
|
||||
return name
|
||||
return f"KB{kbs[0]}" if kbs else update_id
|
||||
|
||||
|
||||
class Offer(NamedTuple):
|
||||
"""One update the search offers: its exact identity and what it is."""
|
||||
|
||||
identity: str # "<UpdateID>:<RevisionNumber>"
|
||||
name: str
|
||||
title: str
|
||||
advisories: list[str]
|
||||
cves: list[str]
|
||||
severity: str | None
|
||||
security: bool | None
|
||||
|
||||
|
||||
def _security(classifications: list[str], cves: list[str], severity: str | None) -> bool | None:
|
||||
if cves or severity or {_SECURITY_UPDATES, _DEFINITION_UPDATES} & set(classifications):
|
||||
return True
|
||||
return False if classifications else None
|
||||
|
||||
|
||||
def _strings(value: Any) -> list[str]:
|
||||
return [str(v) for v in _as_list(value)]
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
"""A string the host may have left empty or out; None then."""
|
||||
return str(value or "") or None
|
||||
|
||||
|
||||
def _identity(entry: dict[str, Any]) -> str:
|
||||
return f"{entry['id']}:{int(entry.get('revision') or 0)}"
|
||||
|
||||
|
||||
def _offer(update: dict[str, Any]) -> Offer | None:
|
||||
"""The offer *update* is; None for one this path does not install."""
|
||||
classifications = [c.lower() for c in _strings(update.get("classifications"))]
|
||||
if update.get("browse_only") or _UPGRADES in classifications:
|
||||
return None
|
||||
kbs, cves = _strings(update.get("kb")), _strings(update.get("cves"))
|
||||
severity = _text(update.get("severity"))
|
||||
title = str(update.get("title") or "")
|
||||
return Offer(
|
||||
identity=_identity(update),
|
||||
name=update_name(title, kbs, str(update["id"])),
|
||||
title=title,
|
||||
advisories=[f"KB{k}" for k in kbs],
|
||||
cves=cves,
|
||||
severity=severity,
|
||||
security=_security(classifications, cves, severity),
|
||||
)
|
||||
|
||||
|
||||
class Search(NamedTuple):
|
||||
"""What one search found."""
|
||||
|
||||
searched_at: int
|
||||
seconds: int
|
||||
origin: str
|
||||
offers: list[Offer]
|
||||
|
||||
|
||||
def parse_search(raw: Any) -> Search:
|
||||
"""The search :data:`_PS_WU_SEARCH` printed, or kept.
|
||||
|
||||
:raises ValueError: when *raw* is no search.
|
||||
"""
|
||||
if not isinstance(raw, dict) or "updates" not in raw:
|
||||
raise ValueError("not a Windows Update search")
|
||||
started = int(raw.get("searched_at") or 0)
|
||||
wsus = raw.get("wsus")
|
||||
offers = [o for u in _as_list(raw["updates"]) if (o := _offer(u)) is not None]
|
||||
return Search(
|
||||
searched_at=started,
|
||||
seconds=max(int(raw.get("finished_at") or started) - started, 0),
|
||||
origin=f"WSUS {wsus}" if wsus else "Windows Update",
|
||||
offers=offers,
|
||||
)
|
||||
|
||||
|
||||
def _higher(first: str | None, second: str | None) -> str | None:
|
||||
def rank(s: str | None) -> int:
|
||||
return _SEVERITIES.index(s) if s in _SEVERITIES else -1
|
||||
|
||||
return first if rank(first) >= rank(second) else second
|
||||
|
||||
|
||||
def _merged(into: UpdateDict, offer: Offer) -> None:
|
||||
into["advisories"] = [*into.get("advisories", []), *offer.advisories]
|
||||
into["new_version"] = " ".join(into["advisories"]) or into["new_version"]
|
||||
into["cves"] = [*into.get("cves", []), *(c for c in offer.cves if c not in into["cves"])]
|
||||
into["vendor_severity"] = _higher(into.get("vendor_severity"), offer.severity)
|
||||
first, second = into.get("security"), offer.security
|
||||
if first or second:
|
||||
into["security"] = True
|
||||
elif first is None or second is None:
|
||||
into["security"] = None
|
||||
|
||||
|
||||
def pending_updates(search: Search) -> list[UpdateDict]:
|
||||
"""One update per name: offers of the same name are one, their KBs and CVEs together."""
|
||||
by_name: dict[str, UpdateDict] = {}
|
||||
for offer in search.offers:
|
||||
if offer.name in by_name:
|
||||
_merged(by_name[offer.name], offer)
|
||||
continue
|
||||
by_name[offer.name] = {
|
||||
"name": offer.name,
|
||||
"current_version": "",
|
||||
"new_version": " ".join(offer.advisories) or f"rev {offer.identity.split(':')[-1]}",
|
||||
"origin": search.origin,
|
||||
"security": offer.security,
|
||||
"title": offer.title,
|
||||
"advisories": list(offer.advisories),
|
||||
"cves": list(offer.cves),
|
||||
"vendor_severity": offer.severity,
|
||||
}
|
||||
return list(by_name.values())
|
||||
|
||||
|
||||
def _installed_since(reading: dict[str, Any], since: int) -> set[str]:
|
||||
return {
|
||||
_identity(h) for h in _as_list(reading.get("installed")) if int(h.get("at") or 0) >= since
|
||||
}
|
||||
|
||||
|
||||
def parse_pending(output: str) -> Search:
|
||||
"""The last search :data:`_PS_WU_PENDING` printed, without what was installed since.
|
||||
|
||||
:raises PackageIndexMissing: before the first search.
|
||||
:raises ValueError: when the kept reading is no search.
|
||||
"""
|
||||
reading = json.loads(output) if output.strip() else {}
|
||||
if not reading.get("search"):
|
||||
raise PackageIndexMissing("Windows Update has not been searched yet; a refresh searches it")
|
||||
search = parse_search(json.loads(reading["search"]))
|
||||
done = _installed_since(reading, search.searched_at)
|
||||
return search._replace(offers=[o for o in search.offers if o.identity not in done])
|
||||
|
||||
|
||||
def _hresult(value: Any) -> str:
|
||||
return f"0x{int(value or 0) & 0xFFFFFFFF:08X}"
|
||||
|
||||
|
||||
def _error(entry: dict[str, Any]) -> str | None:
|
||||
word = _RESULTS.get(int(entry.get("result") or 0))
|
||||
if word is None:
|
||||
return None
|
||||
return f"{word} ({_hresult(entry['hresult'])})" if entry.get("hresult") else word
|
||||
|
||||
|
||||
def _package(title: str, update_id: str, removed: bool) -> UpdateHistoryPackageDict:
|
||||
"""What one history entry changed; the history names no KB but in the title."""
|
||||
kb = [m.upper() for m in _KB_IN_TITLE.findall(title)]
|
||||
version = f"KB{kb[0]}" if kb else None
|
||||
return {
|
||||
"name": update_name(title, kb, update_id),
|
||||
"action": "remove" if removed else "install",
|
||||
"old_version": version if removed else None,
|
||||
"new_version": None if removed else version,
|
||||
"title": title,
|
||||
}
|
||||
|
||||
|
||||
def _transaction(entry: dict[str, Any]) -> UpdateHistoryDict:
|
||||
operation = int(entry.get("operation") or 1)
|
||||
at = int(entry["at"])
|
||||
title = str(entry.get("title") or "")
|
||||
return {
|
||||
"id": f"{_identity(entry)}:{operation}:{at}",
|
||||
"start": at,
|
||||
"end": None if int(entry.get("result") or 0) == _IN_PROGRESS else at,
|
||||
"packages": [_package(title, str(entry["id"]), operation == _UNINSTALL)],
|
||||
"requested_by": _text(entry.get("client")),
|
||||
"command": None,
|
||||
"error": _error(entry),
|
||||
}
|
||||
|
||||
|
||||
def parse_history(output: str, since: int | None) -> list[UpdateHistoryDict]:
|
||||
"""The transactions :data:`_PS_WU_HISTORY` printed that started at or after *since*,
|
||||
newest first."""
|
||||
entries = _as_list(json.loads(output)) if output.strip() else []
|
||||
found = [_transaction(e) for e in entries if since is None or int(e["at"]) >= since]
|
||||
return sorted(found, key=lambda t: t["start"], reverse=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The mixin
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WindowsUpdateMixin(UpdateMixin):
|
||||
"""Windows Update as napalm-device-types' updates; the driver carries the scripts."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_raw(self, script: str) -> str: ...
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]:
|
||||
"""Search the host's update source, and keep what it found for the poll.
|
||||
|
||||
A search takes minutes. One that Windows refuses (no connection to the source)
|
||||
is a failed refresh, and the reading from the last search stays.
|
||||
"""
|
||||
try:
|
||||
search = parse_search(json.loads(self._run_raw(_PS_WU_SEARCH)))
|
||||
except PowerShellError as exc:
|
||||
return {"success": False, "output": str(exc)}
|
||||
updates = pending_updates(search)
|
||||
security = sum(1 for u in updates if u.get("security"))
|
||||
return {
|
||||
"success": True,
|
||||
"output": (
|
||||
f"{search.origin} offers {len(updates)} updates, {security} of them for "
|
||||
f"security, searched in {search.seconds} s."
|
||||
),
|
||||
}
|
||||
|
||||
def _wu_search(self) -> Search:
|
||||
return parse_pending(self._run_raw(_PS_WU_PENDING))
|
||||
|
||||
def get_available_updates(self) -> list[UpdateDict]:
|
||||
"""What the last search found, without what the host installed since.
|
||||
|
||||
:raises PackageIndexMissing: before the first search; a refresh searches.
|
||||
"""
|
||||
return pending_updates(self._wu_search())
|
||||
|
||||
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
|
||||
"""The host's update history since *since* (unix seconds), newest first."""
|
||||
return parse_history(self._run_raw(_PS_WU_HISTORY), since)
|
||||
|
||||
def apply_updates(
|
||||
self,
|
||||
packages: list[str],
|
||||
*,
|
||||
log: Callable[[str], None] | None = None,
|
||||
) -> ApplyUpdatesResultDict:
|
||||
"""Install the updates named *packages* -- every pending one when empty -- in a
|
||||
one-shot SYSTEM task, line by line to *log*; the host is never restarted.
|
||||
|
||||
Each name stands for the exact updates (ID and revision) the last search found
|
||||
under it; the task searches again and installs only those
|
||||
(:mod:`napalm_windows.windows_update_run`).
|
||||
|
||||
:raises ValueError: for a name that is no package name.
|
||||
:raises PackageIndexMissing: before the first search.
|
||||
"""
|
||||
bad = [p for p in packages if not NAME.fullmatch(p or "")]
|
||||
if bad:
|
||||
raise ValueError(f"Invalid update name {bad[0]!r}")
|
||||
offers = self._wu_search().offers
|
||||
wanted = set(packages)
|
||||
chosen = [o for o in offers if not packages or o.name in wanted]
|
||||
missing = sorted(wanted - {o.name for o in offers})
|
||||
return install(self._run_raw, {o.identity: o.title for o in chosen}, missing, log)
|
||||
@@ -1,341 +0,0 @@
|
||||
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
|
||||
|
||||
Windows refuses a download or an install through the update agent to a network logon
|
||||
(``E_ACCESSDENIED``), which a WinRM session is. A scheduled task running as SYSTEM is
|
||||
not one, so a run is such a task (as PSWindowsUpdate's ``Invoke-WUJob`` does it):
|
||||
|
||||
1. **Sweep.** The tasks of earlier runs and their registry keys are deleted -- runs
|
||||
whose connection died left them behind. A run still installing refuses this one.
|
||||
2. **Start.** The run's key under :data:`RUNS` (``HKLM\\SOFTWARE``, where only
|
||||
administrators and SYSTEM may write) gets the exact updates chosen
|
||||
(``<UpdateID>:<revision>``) and the script; the task ``\\napalm-windows\\update-run-<id>``
|
||||
runs that script from the key, as SYSTEM, and is started. No file is written.
|
||||
3. **Follow.** Every few seconds the key's log is read and each new line handed on,
|
||||
until the script writes its result, or the task ends without one.
|
||||
4. **Clean up.** The task and the key are deleted.
|
||||
|
||||
The task searches again and installs nothing it cannot match exactly: an update no
|
||||
longer offered under that ID and revision (installed, replaced or withdrawn since the
|
||||
reading), one offered twice, one that asks for input while it installs, and one whose
|
||||
licence terms the host has not accepted are refused, by name. While a restart is
|
||||
pending, nothing is installed. The run never restarts the host: what follows a run is
|
||||
the caller's. An update Windows installs with a result of its own is reported with it,
|
||||
and the task names itself to Windows Update as ``napalm-windows``, as the host's
|
||||
history shows.
|
||||
|
||||
A run the follower gives up on (:data:`FOLLOW_SECONDS`) carries on on the host: its
|
||||
task is left for the next run's sweep, and what it installed shows in the history.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import ApplyUpdatesResultDict
|
||||
|
||||
from napalm_windows._powershell import _as_list, _ps_quote
|
||||
|
||||
#: Each run's own registry key lives here.
|
||||
RUNS = "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs"
|
||||
#: The task folder of the runs; the scheduled-jobs reading shows them as an application's.
|
||||
TASK_PATH = "\\napalm-windows\\"
|
||||
TASK_PREFIX = "update-run-"
|
||||
#: How often the follower looks, and how long it follows a run at most.
|
||||
POLL_SECONDS = 5
|
||||
FOLLOW_SECONDS = 25 * 60
|
||||
|
||||
# Runs as SYSTEM, from the run's key: search again, refuse what does not match exactly,
|
||||
# download, install, report. Never restarts. __KEY__ is the run's key.
|
||||
_PS_RUN = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$key = '__KEY__'
|
||||
$log = New-Object System.Collections.Generic.List[string]
|
||||
$outcome = [ordered]@{
|
||||
reboot_required = $false; installed = @(); refused = @(); failed = @(); error = $null
|
||||
}
|
||||
function Say([string]$line) {
|
||||
$log.Add($line)
|
||||
Set-ItemProperty -LiteralPath $key -Name Log -Value ($log -join "`n")
|
||||
}
|
||||
function Named($u) { '{0} ({1}:{2})' -f $u.Title, $u.Identity.UpdateID, $u.Identity.RevisionNumber }
|
||||
function IdOf($u) { '{0}:{1}' -f $u.Identity.UpdateID, $u.Identity.RevisionNumber }
|
||||
function Failed($u, $step, $r) {
|
||||
$code = [int]$r.ResultCode
|
||||
$outcome.failed += [pscustomobject]@{
|
||||
id = (IdOf $u); step = $step; result = $code; hresult = [int64]$r.HResult
|
||||
}
|
||||
Say ('{0} failed: {1} (result {2}, 0x{3:X8})' -f $step, (Named $u), $code, [int]$r.HResult)
|
||||
}
|
||||
try {
|
||||
$requested = @((Get-ItemProperty -LiteralPath $key -Name Requested).Requested)
|
||||
$session = New-Object -ComObject Microsoft.Update.Session
|
||||
$session.ClientApplicationID = 'napalm-windows'
|
||||
$installer = $session.CreateUpdateInstaller()
|
||||
$pending = (New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired
|
||||
if ($pending -or $installer.RebootRequiredBeforeInstallation) {
|
||||
throw 'A restart is pending on the host: nothing is installed until it has restarted.'
|
||||
}
|
||||
Say 'Searching Windows Update again for the chosen updates'
|
||||
$offered = @{}
|
||||
$searcher = $session.CreateUpdateSearcher()
|
||||
foreach ($u in $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'").Updates) {
|
||||
$id = IdOf $u
|
||||
if ($offered.ContainsKey($id)) { $offered[$id] += @($u) } else { $offered[$id] = @($u) }
|
||||
}
|
||||
$chosen = New-Object -ComObject Microsoft.Update.UpdateColl
|
||||
foreach ($id in $requested) {
|
||||
$u = $null
|
||||
$why = $null
|
||||
if (-not $offered.ContainsKey($id)) {
|
||||
$why = 'no longer offered: installed, replaced or withdrawn since it was read'
|
||||
} elseif ($offered[$id].Count -ne 1) {
|
||||
$why = 'offered more than once'
|
||||
} else {
|
||||
$u = $offered[$id][0]
|
||||
if ($u.InstallationBehavior.CanRequestUserInput) {
|
||||
$why = 'it asks for input while it installs'
|
||||
} elseif (-not $u.EulaAccepted) {
|
||||
$why = 'its licence terms have not been accepted on the host'
|
||||
}
|
||||
}
|
||||
if ($why) {
|
||||
$outcome.refused += [pscustomobject]@{ id = $id; reason = $why }
|
||||
Say ('Refused {0}: {1}' -f $(if ($u) { Named $u } else { $id }), $why)
|
||||
} else {
|
||||
[void]$chosen.Add($u)
|
||||
}
|
||||
}
|
||||
$ready = New-Object -ComObject Microsoft.Update.UpdateColl
|
||||
if ($chosen.Count -gt 0) {
|
||||
Say ('Downloading {0} update(s)' -f $chosen.Count)
|
||||
$downloader = $session.CreateUpdateDownloader()
|
||||
$downloader.Updates = $chosen
|
||||
$fetched = $downloader.Download()
|
||||
for ($i = 0; $i -lt $chosen.Count; $i++) {
|
||||
$u = $chosen.Item($i)
|
||||
if ($u.IsDownloaded) { [void]$ready.Add($u) }
|
||||
else { Failed $u 'Download' ($fetched.GetUpdateResult($i)) }
|
||||
}
|
||||
}
|
||||
if ($ready.Count -gt 0) {
|
||||
Say ('Installing {0} update(s); the host is not restarted' -f $ready.Count)
|
||||
$installer.Updates = $ready
|
||||
$installer.AllowSourcePrompts = $false
|
||||
try { $installer.ForceQuiet = $true } catch { }
|
||||
$done = $installer.Install()
|
||||
for ($i = 0; $i -lt $ready.Count; $i++) {
|
||||
$u = $ready.Item($i)
|
||||
$r = $done.GetUpdateResult($i)
|
||||
if ($r.ResultCode -eq 2 -or $r.ResultCode -eq 3) {
|
||||
$outcome.installed += (IdOf $u)
|
||||
Say ('Installed: ' + (Named $u))
|
||||
} else { Failed $u 'Install' $r }
|
||||
if ($r.RebootRequired) { $outcome.reboot_required = $true }
|
||||
}
|
||||
if ($done.RebootRequired) { $outcome.reboot_required = $true }
|
||||
if ($outcome.reboot_required) { Say 'A restart finishes the installation.' }
|
||||
}
|
||||
} catch {
|
||||
$outcome.error = [string]$_.Exception.Message
|
||||
if (-not $outcome.error) { $outcome.error = [string]$_ }
|
||||
Say $outcome.error
|
||||
}
|
||||
$result = ConvertTo-Json -Compress -Depth 4 -InputObject ([pscustomobject]$outcome)
|
||||
Set-ItemProperty -LiteralPath $key -Name Result -Value $result
|
||||
"""
|
||||
|
||||
# Deletes what earlier runs left -- unless one is still running, which it names.
|
||||
_PS_SWEEP = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$tasks = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.TaskName -like '__PREFIX__*' })
|
||||
$busy = @($tasks | Where-Object { [string]$_.State -eq 'Running' } | ForEach-Object { $_.TaskName })
|
||||
$swept = @()
|
||||
if ($busy.Count -eq 0) {
|
||||
foreach ($t in $tasks) {
|
||||
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName $t.TaskName -Confirm:$false
|
||||
$swept += $t.TaskName
|
||||
}
|
||||
if (Test-Path -LiteralPath '__RUNS__') {
|
||||
foreach ($k in @(Get-ChildItem -LiteralPath '__RUNS__')) {
|
||||
Remove-Item -LiteralPath $k.PSPath -Recurse
|
||||
$swept += $k.PSChildName
|
||||
}
|
||||
}
|
||||
}
|
||||
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{ busy = $busy; swept = $swept })
|
||||
"""
|
||||
|
||||
_PS_START = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$key = '__RUNS__\' + __RUN__
|
||||
New-Item -Path $key -Force | Out-Null
|
||||
$requested = [string[]]@(__REQUESTED__)
|
||||
New-ItemProperty -LiteralPath $key -Name Requested -PropertyType MultiString -Value $requested |
|
||||
Out-Null
|
||||
New-ItemProperty -LiteralPath $key -Name Script -PropertyType String -Value __SCRIPT__ | Out-Null
|
||||
$exe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||
$read = "(Get-ItemProperty -LiteralPath '$key' -Name Script).Script"
|
||||
$arg = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "& ([scriptblock]::Create(' +
|
||||
$read + '))"'
|
||||
$action = New-ScheduledTaskAction -Execute $exe -Argument $arg
|
||||
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
|
||||
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
|
||||
-ExecutionTimeLimit (New-TimeSpan -Hours 4) -MultipleInstances IgnoreNew
|
||||
$about = 'napalm-windows: installs the Windows updates an application chose; deleted when its ' +
|
||||
'run ends'
|
||||
Register-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Action $action `
|
||||
-Principal $principal -Settings $settings -Description $about | Out-Null
|
||||
Start-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__
|
||||
"""
|
||||
|
||||
# The task's state first: a result written after it was read is still found below.
|
||||
_PS_FOLLOW = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$task = @(Get-ScheduledTask -TaskPath '__PATH__' -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.TaskName -eq __TASK__ })
|
||||
$state = 'gone'
|
||||
if ($task.Count) { $state = [string]$task[0].State }
|
||||
$run = Get-ItemProperty -ErrorAction SilentlyContinue -LiteralPath ('__RUNS__\' + __RUN__)
|
||||
ConvertTo-Json -Compress -InputObject ([pscustomobject]@{
|
||||
state = $state
|
||||
log = [string]$run.Log
|
||||
result = [string]$run.Result
|
||||
})
|
||||
"""
|
||||
|
||||
_PS_CLEANUP = r"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Unregister-ScheduledTask -TaskPath '__PATH__' -TaskName __TASK__ -Confirm:$false `
|
||||
-ErrorAction SilentlyContinue
|
||||
$key = '__RUNS__\' + __RUN__
|
||||
if (Test-Path -LiteralPath $key) { Remove-Item -LiteralPath $key -Recurse }
|
||||
"""
|
||||
|
||||
|
||||
def _script(template: str, **values: str) -> str:
|
||||
"""*template* with its ``__NAME__`` placeholders filled; the run's own as given, the
|
||||
module's constants always. Values are PowerShell already: quote them first."""
|
||||
values = {"PATH": TASK_PATH, "PREFIX": TASK_PREFIX, "RUNS": RUNS, **values}
|
||||
for name, value in values.items():
|
||||
template = template.replace(f"__{name}__", value)
|
||||
return template
|
||||
|
||||
|
||||
Run = Callable[[str], str]
|
||||
Log = Callable[[str], None]
|
||||
|
||||
|
||||
class _Lines:
|
||||
"""Every line of the run, each handed to *log* once as it comes."""
|
||||
|
||||
def __init__(self, log: Log | None):
|
||||
self.log = log
|
||||
self.lines: list[str] = []
|
||||
|
||||
def say(self, line: str) -> None:
|
||||
self.lines.append(line)
|
||||
if self.log is not None:
|
||||
self.log(line)
|
||||
|
||||
def host(self, text: str, seen: int) -> int:
|
||||
"""Hand on the lines of the host's *text* past the first *seen*; how many there are."""
|
||||
lines = text.split("\n") if text else []
|
||||
for line in lines[seen:]:
|
||||
self.say(line)
|
||||
return max(len(lines), seen)
|
||||
|
||||
def result(self, success: bool, error: str | None = None) -> ApplyUpdatesResultDict:
|
||||
out: ApplyUpdatesResultDict = {"success": success, "output": "\n".join(self.lines)}
|
||||
if not success:
|
||||
out["error"] = error or "The update run did not succeed; its output says why."
|
||||
return out
|
||||
|
||||
|
||||
def _ids(run_id: str) -> dict[str, str]:
|
||||
return {"RUN": _ps_quote(run_id), "TASK": _ps_quote(TASK_PREFIX + run_id)}
|
||||
|
||||
|
||||
def _sweep(run: Run) -> list[str]:
|
||||
"""The earlier runs still installing; the others are deleted."""
|
||||
reading = json.loads(run(_script(_PS_SWEEP)) or "{}")
|
||||
return [str(b) for b in _as_list(reading.get("busy"))]
|
||||
|
||||
|
||||
def run_script(run_id: str) -> str:
|
||||
"""What the task runs as SYSTEM for the run *run_id*."""
|
||||
return _PS_RUN.replace("__KEY__", f"{RUNS}\\{run_id}")
|
||||
|
||||
|
||||
def _start(run: Run, run_id: str, identities: list[str]) -> None:
|
||||
requested = ",".join(_ps_quote(i) for i in identities)
|
||||
script = _ps_quote(run_script(run_id))
|
||||
run(_script(_PS_START, REQUESTED=requested, SCRIPT=script, **_ids(run_id)))
|
||||
|
||||
|
||||
def _cleanup(run: Run, run_id: str) -> None:
|
||||
run(_script(_PS_CLEANUP, **_ids(run_id)))
|
||||
|
||||
|
||||
def _outcome(result: dict[str, Any], lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
|
||||
refused = len(_as_list(result.get("refused"))) + refused_before
|
||||
failed = len(_as_list(result.get("failed")))
|
||||
if result.get("error"):
|
||||
return lines.result(False, str(result["error"]))
|
||||
if refused or failed:
|
||||
return lines.result(False, f"{refused} update(s) refused, {failed} failed.")
|
||||
return lines.result(True)
|
||||
|
||||
|
||||
def _follow(run: Run, run_id: str, lines: _Lines, refused_before: int) -> ApplyUpdatesResultDict:
|
||||
"""Hand on the run's lines until it ends; its outcome."""
|
||||
seen = 0
|
||||
deadline = time.monotonic() + FOLLOW_SECONDS
|
||||
follow = _script(_PS_FOLLOW, **_ids(run_id))
|
||||
while True:
|
||||
time.sleep(POLL_SECONDS)
|
||||
reading = json.loads(run(follow) or "{}")
|
||||
seen = lines.host(str(reading.get("log") or ""), seen)
|
||||
if reading.get("result"):
|
||||
_cleanup(run, run_id)
|
||||
return _outcome(json.loads(reading["result"]), lines, refused_before)
|
||||
if reading.get("state") != "Running":
|
||||
_cleanup(run, run_id)
|
||||
return lines.result(False, "The update task ended without a result.")
|
||||
if time.monotonic() > deadline:
|
||||
return lines.result(
|
||||
False,
|
||||
"The updates are still installing on the host; the run carries on there, "
|
||||
"and the update history shows what it installed.",
|
||||
)
|
||||
|
||||
|
||||
def install(
|
||||
run: Run, chosen: dict[str, str], missing: list[str], log: Log | None
|
||||
) -> ApplyUpdatesResultDict:
|
||||
"""Install the updates *chosen* (``identity -> title``) in a SYSTEM task, following it.
|
||||
|
||||
*missing* are names the caller asked for that the last search does not offer: each
|
||||
is refused, by name, and the others are installed.
|
||||
"""
|
||||
lines = _Lines(log)
|
||||
for name in missing:
|
||||
lines.say(f"Refused {name}: not offered by the last search")
|
||||
if not chosen:
|
||||
if missing:
|
||||
return lines.result(False, f"{len(missing)} update(s) refused, 0 failed.")
|
||||
lines.say("Nothing to install.")
|
||||
return lines.result(True)
|
||||
busy = _sweep(run)
|
||||
if busy:
|
||||
lines.say(f"An earlier update run is still installing on the host: {', '.join(busy)}")
|
||||
return lines.result(False, "An earlier update run is still installing on the host.")
|
||||
run_id = uuid.uuid4().hex[:12]
|
||||
for identity, title in chosen.items():
|
||||
lines.say(f"Chosen: {title} ({identity})")
|
||||
_start(run, run_id, list(chosen))
|
||||
return _follow(run, run_id, lines, len(missing))
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"wu_reboot_required":false,"cbs_reboot_pending":false,"wu_reboot_key":false,"file_renames":true,"update_exe":"0","computer_name":"WIN01","active_name":"WIN01","no_auto_update":"","au_options":"4","local_au_options":"","product_type":3,"installs":[1763337600,1762732800,1760659200],"au_last_install":1762732800,"legacy_last_install":"","system_drive":{"drive":"C:","size":136363114496,"free":52613349376}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"domain_role":2,"local_accounts":true,"users":[{"name":"Administrator","sid":"S-1-5-21-1004336348-1177238915-682003330-500","home":"C:\\Users\\Administrator"},{"name":"DefaultAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-503","home":null},{"name":"Guest","sid":"S-1-5-21-1004336348-1177238915-682003330-501","home":null},{"name":"WDAGUtilityAccount","sid":"S-1-5-21-1004336348-1177238915-682003330-504","home":null},{"name":"svc-backup","sid":"S-1-5-21-1004336348-1177238915-682003330-1001","home":"C:\\Users\\svc-backup"}],"groups":[{"name":"Administrators","members":["S-1-5-21-1004336348-1177238915-682003330-500","S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-21-3623811015-3361044348-30300820-512"]},{"name":"Backup Operators","members":["S-1-5-21-1004336348-1177238915-682003330-1001"]},{"name":"Guests","members":["S-1-5-21-1004336348-1177238915-682003330-501"]},{"name":"Remote Desktop Users","members":[]},{"name":"System Managed Accounts Group","members":["S-1-5-21-1004336348-1177238915-682003330-503"]},{"name":"Users","members":["S-1-5-21-1004336348-1177238915-682003330-1001","S-1-5-4","S-1-5-11"]}]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
[{"key":"7-Zip","arch":"x64","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"5846"},{"key":"7-Zip","arch":"x86","name":"7-Zip 23.01 (x64)","version":"23.01","publisher":"Igor Pavlov","system":"","parent":"","msi":"","size":"4870"},{"key":"{90160000-008C-0000-1000-0000000FF1CE}","arch":"x64","name":"Office 16 Click-to-Run Extensibility Component","version":"16.0.17126.20132","publisher":"Microsoft Corporation","system":"1","parent":"","msi":"1","size":"0"},{"key":"{AC76BA86-1033-FFFF-7760-BC15014EA700}","arch":"x86","name":"Adobe Acrobat Reader DC","version":"23.008.20470","publisher":"Adobe","system":"","parent":"","msi":"1","size":"1158000"},{"key":"KB5034441","arch":"x64","name":"Security Update for Windows Server (KB5034441)","version":"","publisher":"Microsoft Corporation","system":"","parent":"Windows Server","msi":"","size":""},{"key":"Git_is1","arch":"x64","name":"Git","version":"2.43.0","publisher":"The Git Development Community","system":"","parent":"","msi":"","size":"309000"},{"key":"AddressBook","arch":"x64","name":"","version":"","publisher":"","system":"","parent":"","msi":"","size":""},{"key":"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}","arch":"x64","name":"Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130","version":"14.38.33130.0","publisher":"Microsoft Corporation","system":"","parent":"","msi":"","size":"20532"}]
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"now":1764590400,"cores":4,"memory_kib":8388608,"processes":[{"pid":0,"ppid":0,"name":"System Idle Process","command":"","started":null,"offset":0,"cpu":4000000000000,"ws":8192,"vsz":8192},{"pid":4,"ppid":0,"name":"System","command":"","started":null,"offset":0,"cpu":12000000000,"ws":143360,"vsz":3997696},{"pid":812,"ppid":640,"name":"svchost.exe","command":"C:\\Windows\\system32\\svchost.exe -k DcomLaunch -p","started":1764504000,"offset":60,"cpu":3456000000,"ws":31457280,"vsz":2203318222848},{"pid":4312,"ppid":3988,"name":"powershell.exe","command":"\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoLogo","started":1764589800,"offset":60,"cpu":1200000000,"ws":104857600,"vsz":2203500000000},{"pid":5120,"ppid":812,"name":"WmiPrvSE.exe","command":"C:\\Windows\\system32\\wbem\\wmiprvse.exe","started":1764590395,"offset":60,"cpu":1000000,"ws":10485760,"vsz":2203400000000},{"pid":6000,"ppid":812,"name":"conhost.exe","command":"\\??\\C:\\Windows\\system32\\conhost.exe 0x4","started":1764590370,"offset":60,"cpu":0,"ws":4194304,"vsz":2203300000000}],"owners":[{"pid":0,"user":null,"started":null},{"pid":4,"user":"NT AUTHORITY\\SYSTEM","started":null},{"pid":812,"user":"NT AUTHORITY\\SYSTEM","started":1764504000},{"pid":4312,"user":"WIN01\\admin","started":1764589800},{"pid":6000,"user":"WIN01\\admin","started":1764590398},{"pid":7777,"user":"WIN01\\admin","started":1764590399}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"uuid":"4C4C4544-0042-3510-8051-B4C04F4D3732","product_serial":"4B5QM72","board_serial":".4B5QM72.CNCMS0012345AB.","bios_vendor":"Dell Inc.","bios_version":"2.19.0","bios_date":1692057600}
|
||||
-1
@@ -1 +0,0 @@
|
||||
[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","at":1795603600,"operation":1,"result":2,"hresult":0,"client":"Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)"},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","at":1795590000,"operation":1,"result":4,"hresult":-2145124329,"client":"napalm-windows"},{"id":"aa11bb22-cc33-4d44-8e55-ff6677889900","revision":1,"title":"2026-10 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5066000)","at":1792900000,"operation":1,"result":2,"hresult":0,"client":"UpdateOrchestrator"},{"id":"bb22cc33-dd44-4e55-8f66-0011aabbccdd","revision":2,"title":"Update for Windows Security platform - KB5007651 (Version 1.0.2509.1001)","at":1792800000,"operation":2,"result":2,"hresult":0,"client":"AutomaticUpdates"},{"id":"cc33dd44-ee55-4f66-8a77-1122bbccddee","revision":1,"title":"2026-09 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5063000)","at":1790200000,"operation":1,"result":1,"hresult":0,"client":""}]
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"search":"{\"searched_at\":1795600000,\"finished_at\":1795600094,\"result\":2,\"wsus\":null,\"updates\":[{\"id\":\"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11\",\"revision\":1,\"title\":\"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)\",\"kb\":[\"5070000\"],\"cves\":[\"CVE-2026-21001\",\"CVE-2026-21002\",\"CVE-2026-21003\"],\"severity\":\"Critical\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":2,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4\",\"revision\":200,\"title\":\"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)\",\"kb\":[\"2267602\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"e0789628-ce08-4437-be74-2495b842f43b\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":true},{\"id\":\"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f\",\"revision\":3,\"title\":\"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)\",\"kb\":[\"5070100\"],\"cves\":[\"CVE-2026-21101\"],\"severity\":\"Important\",\"classifications\":[\"0fa1201d-4330-4fa8-8ae9-b877473b6441\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c\",\"revision\":1,\"title\":\"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)\",\"kb\":[\"890830\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"28bc880e-0592-4cbf-8f95-c79b17911d5f\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b\",\"revision\":1,\"title\":\"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)\",\"kb\":[\"5070200\"],\"cves\":[],\"severity\":\"\",\"classifications\":[\"cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83\"],\"browse_only\":true,\"interactive\":false,\"reboot\":0,\"eula_accepted\":true,\"downloaded\":false},{\"id\":\"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d\",\"revision\":1,\"title\":\"Windows Server 2025 upgrade\",\"kb\":[],\"cves\":[],\"severity\":\"\",\"classifications\":[\"3689bdc8-b205-4af4-8d4a-a63924c5e9d5\"],\"browse_only\":false,\"interactive\":false,\"reboot\":0,\"eula_accepted\":false,\"downloaded\":false}]}","installed":[{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"at":1795603600},{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"at":1795500000}],"history_error":null}
|
||||
-1
@@ -1 +0,0 @@
|
||||
{"searched_at":1795600000,"finished_at":1795600094,"result":2,"wsus":null,"updates":[{"id":"8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11","revision":1,"title":"2026-11 Cumulative Update for Microsoft server operating system version 21H2 for x64-based Systems (KB5070000)","kb":["5070000"],"cves":["CVE-2026-21001","CVE-2026-21002","CVE-2026-21003"],"severity":"Critical","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":2,"eula_accepted":true,"downloaded":false},{"id":"d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4","revision":200,"title":"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.441.120.0) - Current Channel (Broad)","kb":["2267602"],"cves":[],"severity":"","classifications":["e0789628-ce08-4437-be74-2495b842f43b"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":true},{"id":"1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f","revision":3,"title":"2026-11 Cumulative Update for .NET Framework 3.5, 4.8 and 4.8.1 for Microsoft server operating system version 21H2 for x64 (KB5070100)","kb":["5070100"],"cves":["CVE-2026-21101"],"severity":"Important","classifications":["0fa1201d-4330-4fa8-8ae9-b877473b6441"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c","revision":1,"title":"Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)","kb":["890830"],"cves":[],"severity":"","classifications":["28bc880e-0592-4cbf-8f95-c79b17911d5f"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"4e3d2c1b-0a9f-4e8d-8c7b-6a5f4e3d2c1b","revision":1,"title":"2026-11 Cumulative Update Preview for Microsoft server operating system version 21H2 for x64-based Systems (KB5070200)","kb":["5070200"],"cves":[],"severity":"","classifications":["cd5ffd1e-e932-4e3a-bf74-18bf0b1bbd83"],"browse_only":true,"interactive":false,"reboot":0,"eula_accepted":true,"downloaded":false},{"id":"9b8a7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d","revision":1,"title":"Windows Server 2025 upgrade","kb":[],"cves":[],"severity":"","classifications":["3689bdc8-b205-4af4-8d4a-a63924c5e9d5"],"browse_only":false,"interactive":false,"reboot":0,"eula_accepted":false,"downloaded":false}]}
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Whether a Windows host needs a restart, and whether it updates itself (NetOrk/netork#2891).
|
||||
|
||||
One script reads Windows Update's own answer (``Microsoft.Update.SystemInfo``), the
|
||||
registry's restart markers, the Windows Update policy and history, and the system
|
||||
drive; a fake transport answers it from tests/fixtures/synthetic/host_status.json: a
|
||||
member server whose policy installs updates automatically, with file renames pending
|
||||
from an installer and nothing else.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types.models import HostStatusDict
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import host_status as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "host_status.json"
|
||||
MONTH = 31 * 86400
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _status(**changes: Any) -> HostStatusDict:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
reading = {**json.loads(FIXTURE.read_text()), **changes}
|
||||
d._transport = FakeTransport(json.dumps(reading))
|
||||
return d.get_host_status()
|
||||
|
||||
|
||||
def test_reads_the_host_status():
|
||||
assert _status() == {
|
||||
"reboot_required": False,
|
||||
"reboot_reason": "files wait to be replaced at the next restart "
|
||||
"(PendingFileRenameOperations)",
|
||||
"auto_updates": True,
|
||||
"auto_updates_last_success": 1763337600,
|
||||
"auto_updates_interval": MONTH,
|
||||
"filesystems": [
|
||||
{
|
||||
"mountpoint": "C:\\",
|
||||
"total": 136363114496,
|
||||
"used": 136363114496 - 52613349376,
|
||||
"available": 52613349376,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ── restart ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_pending_file_renames_alone_need_no_restart():
|
||||
# Antivirus and installers set them routinely; as a trigger they would keep the flag up.
|
||||
status = _status()
|
||||
assert status["reboot_required"] is False
|
||||
assert "PendingFileRenameOperations" in (status["reboot_reason"] or "")
|
||||
|
||||
|
||||
def test_windows_update_saying_so_needs_a_restart():
|
||||
status = _status(wu_reboot_required=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "Windows Update needs a restart to finish installing updates"
|
||||
|
||||
|
||||
def test_component_servicing_pending_needs_a_restart():
|
||||
status = _status(cbs_reboot_pending=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
assert status["reboot_reason"] == "component-based servicing has a restart pending"
|
||||
|
||||
|
||||
def test_windows_updates_registry_marker_stands_in_where_its_com_object_did_not_answer():
|
||||
status = _status(wu_reboot_required=None, wu_reboot_key=True, file_renames=False)
|
||||
assert status["reboot_required"] is True
|
||||
|
||||
|
||||
def test_nothing_pending_needs_no_restart_and_gives_no_reason():
|
||||
status = _status(file_renames=False)
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] is None
|
||||
|
||||
|
||||
def test_every_marker_found_is_named():
|
||||
status = _status(
|
||||
wu_reboot_required=True,
|
||||
cbs_reboot_pending=True,
|
||||
update_exe="1",
|
||||
computer_name="WIN02",
|
||||
)
|
||||
assert status["reboot_reason"] == "; ".join(
|
||||
[
|
||||
"Windows Update needs a restart to finish installing updates",
|
||||
"component-based servicing has a restart pending",
|
||||
"files wait to be replaced at the next restart (PendingFileRenameOperations)",
|
||||
"an update waits for a restart (UpdateExeVolatile)",
|
||||
"the computer takes its new name WIN02 at the next restart",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_a_rename_alone_needs_no_restart_for_updates():
|
||||
status = _status(file_renames=False, computer_name="WIN02")
|
||||
assert status["reboot_required"] is False
|
||||
assert status["reboot_reason"] == "the computer takes its new name WIN02 at the next restart"
|
||||
|
||||
|
||||
# ── automatic updates ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("au_options", "expected"),
|
||||
[("2", False), ("3", False), ("4", True), ("7", False)],
|
||||
ids=["notify", "download-only", "install", "server-notify-install-and-restart"],
|
||||
)
|
||||
def test_the_policys_au_options(au_options, expected):
|
||||
assert _status(au_options=au_options)["auto_updates"] is expected
|
||||
|
||||
|
||||
def test_a_policy_that_turns_automatic_updates_off():
|
||||
assert _status(no_auto_update="1")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_policy_that_leaves_it_to_the_local_administrator():
|
||||
assert _status(au_options="5", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="5", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_client_without_a_policy_installs_updates_itself():
|
||||
assert _status(au_options="", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_client_ignores_a_leftover_local_setting():
|
||||
# Windows 10 and 11 honour only the policy; an old AUOptions left from an upgrade stays.
|
||||
assert _status(au_options="", local_au_options="2", product_type=1)["auto_updates"] is True
|
||||
|
||||
|
||||
def test_a_server_follows_its_local_setting_without_a_policy():
|
||||
assert _status(au_options="", local_au_options="4")["auto_updates"] is True
|
||||
assert _status(au_options="", local_au_options="3")["auto_updates"] is False
|
||||
|
||||
|
||||
def test_a_server_without_any_setting_cannot_tell():
|
||||
status = _status(au_options="", local_au_options="")
|
||||
assert status["auto_updates"] is None
|
||||
assert status["auto_updates_interval"] is None
|
||||
|
||||
|
||||
def test_without_automatic_updates_there_is_no_interval():
|
||||
status = _status(au_options="3")
|
||||
assert status["auto_updates_interval"] is None
|
||||
assert status["auto_updates_last_success"] == 1763337600
|
||||
|
||||
|
||||
def test_the_last_success_is_the_latest_any_source_knows():
|
||||
status = _status(installs=[], au_last_install=None, legacy_last_install="2025-11-20 03:12:44")
|
||||
assert status["auto_updates_last_success"] == 1763608364
|
||||
status = _status(installs=[1760659200], au_last_install=1762732800)
|
||||
assert status["auto_updates_last_success"] == 1762732800
|
||||
|
||||
|
||||
def test_no_installation_known_has_no_last_success():
|
||||
status = _status(installs=None, au_last_install=None, legacy_last_install="")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
def test_an_unset_com_date_is_no_installation():
|
||||
# WUA's DATE zero is 1899-12-30, which travels as a negative Unix time.
|
||||
status = _status(installs=[], au_last_install=-2209161600, legacy_last_install="garbage")
|
||||
assert status["auto_updates_last_success"] is None
|
||||
|
||||
|
||||
# ── the system drive ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_an_unread_system_drive_is_no_filesystem_reading():
|
||||
assert _status(system_drive=None)["filesystems"] is None
|
||||
|
||||
|
||||
def test_one_script_reads_it_all_each_part_on_its_own():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(FIXTURE.read_text())
|
||||
d.get_host_status()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_HOST_STATUS
|
||||
for part in (
|
||||
"Microsoft.Update.SystemInfo",
|
||||
r"Component Based Servicing\RebootPending",
|
||||
"PendingFileRenameOperations",
|
||||
r"Policies\Microsoft\Windows\WindowsUpdate\AU",
|
||||
"QueryHistory",
|
||||
"Win32_LogicalDisk",
|
||||
):
|
||||
assert part in script
|
||||
# Each COM object is asked inside its own try, so one that does not answer over
|
||||
# WinRM leaves the rest of the reading standing.
|
||||
assert script.count("try {") >= 4
|
||||
# No update search in the poll: that is the update reading's, and slow.
|
||||
assert "Search(" not in script
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Local accounts on Windows as ``UserDict`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads ``Get-LocalUser``, ``Get-LocalGroup`` with their members and the
|
||||
profiles' paths; a fake transport answers it from tests/fixtures/synthetic/os_users.json,
|
||||
a member server as Windows installs it plus one account created (``svc-backup``).
|
||||
Windows names an account by its SID: ``uid`` is its relative identifier, ``sid`` the
|
||||
whole of it (napalm-device-types' ``UserDict.sid``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import os_users as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "os_users.json"
|
||||
BASE = "S-1-5-21-1004336348-1177238915-682003330"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading(**changes: Any) -> dict[str, Any]:
|
||||
return {**json.loads(FIXTURE.read_text()), **changes}
|
||||
|
||||
|
||||
def _users(reading: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return {u["username"]: u for u in d.get_os_users()}
|
||||
|
||||
|
||||
def test_an_account_created_reads_like_a_posix_one():
|
||||
assert _users()["svc-backup"] == {
|
||||
"username": "svc-backup",
|
||||
"uid": 1001,
|
||||
"gid": 513,
|
||||
"home": "C:\\Users\\svc-backup",
|
||||
"shell": "",
|
||||
"groups": ["Administrators", "Backup Operators", "Users"],
|
||||
"sid": f"{BASE}-1001",
|
||||
}
|
||||
|
||||
|
||||
def test_the_built_in_accounts_keep_their_well_known_rids():
|
||||
users = _users()
|
||||
assert users["Administrator"]["uid"] == 500
|
||||
assert users["Guest"]["uid"] == 501
|
||||
assert users["Guest"]["groups"] == ["Guests"]
|
||||
|
||||
|
||||
def test_an_account_that_never_logged_on_has_no_home():
|
||||
assert _users()["Guest"]["home"] == ""
|
||||
|
||||
|
||||
def test_a_group_whose_members_could_not_be_read_names_nobody():
|
||||
# Get-LocalGroupMember and the ADSI fallback both failed: the script sends null.
|
||||
reading = _reading()
|
||||
reading["groups"][0]["members"] = None
|
||||
assert "Administrators" not in _users(reading)["svc-backup"]["groups"]
|
||||
|
||||
|
||||
def test_a_single_account_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["users"] = reading["users"][0]
|
||||
reading["groups"] = reading["groups"][0]
|
||||
assert _users(reading)["Administrator"]["groups"] == ["Administrators"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [4, 5])
|
||||
def test_a_domain_controller_has_no_local_accounts_to_list(role):
|
||||
with pytest.raises(NotImplementedError, match="domain controller"):
|
||||
_users(_reading(domain_role=role, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_a_host_without_the_local_accounts_cmdlets_cannot_list_them():
|
||||
with pytest.raises(NotImplementedError, match="Get-LocalUser"):
|
||||
_users(_reading(local_accounts=False, users=[], groups=[]))
|
||||
|
||||
|
||||
def test_one_script_reads_accounts_groups_and_profiles():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading()))
|
||||
d.get_os_users()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_OS_USERS
|
||||
for part in ("Get-LocalUser", "Get-LocalGroupMember", "Win32_UserProfile", "DomainRole"):
|
||||
assert part in script
|
||||
# Probed first, so a host without the module says so instead of failing.
|
||||
assert "Get-Command -Name Get-LocalUser" in script
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Installed software on Windows: the machine-wide Uninstall keys (NetOrk/netork#2890).
|
||||
|
||||
One script reads the native and the 32-bit (``WOW6432Node``) Uninstall key of HKLM; a
|
||||
fake transport answers it from tests/fixtures/synthetic/packages.json. The fixture holds
|
||||
the cases the issue names: 7-Zip installed both as a 64-bit and a 32-bit program, a
|
||||
``SystemComponent`` entry, and an update listed under its product (``ParentKeyName``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import packages as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "packages.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading() -> list[dict[str, Any]]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: Any = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(_reading() if reading is None else reading))
|
||||
return d
|
||||
|
||||
|
||||
def _packages(reading: Any = None) -> list[Any]:
|
||||
return list(_driver(reading).get_packages())
|
||||
|
||||
|
||||
def test_a_program_reads_as_a_package():
|
||||
git = next(p for p in _packages() if p["name"] == "Git")
|
||||
assert git == {
|
||||
"name": "Git",
|
||||
"version": "2.43.0",
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": 309000 * 1024,
|
||||
"source": "exe",
|
||||
"publisher": "The Git Development Community",
|
||||
"architecture": "x64",
|
||||
}
|
||||
|
||||
|
||||
def test_a_windows_installer_package_is_msi():
|
||||
acrobat = next(p for p in _packages() if p["name"] == "Adobe Acrobat Reader DC")
|
||||
assert acrobat["source"] == "msi"
|
||||
assert acrobat["architecture"] == "x86"
|
||||
|
||||
|
||||
def test_a_32_and_a_64_bit_install_of_one_program_stay_two_packages():
|
||||
zips = [p for p in _packages() if p["name"].startswith("7-Zip")]
|
||||
assert sorted(p["architecture"] for p in zips) == ["x64", "x86"]
|
||||
|
||||
|
||||
def test_system_components_updates_and_unnamed_keys_are_no_packages():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert "Office 16 Click-to-Run Extensibility Component" not in names
|
||||
assert "Security Update for Windows Server (KB5034441)" not in names
|
||||
assert "" not in names
|
||||
assert len(names) == 5
|
||||
|
||||
|
||||
def test_packages_come_sorted_by_name():
|
||||
names = [p["name"] for p in _packages()]
|
||||
assert names == sorted(names, key=str.lower)
|
||||
|
||||
|
||||
def test_a_missing_size_is_zero():
|
||||
reading = _reading()
|
||||
reading[5]["size"] = ""
|
||||
assert next(p for p in _packages(reading) if p["name"] == "Git")["size"] == 0
|
||||
|
||||
|
||||
def test_a_single_package_survives_powershells_unwrapping():
|
||||
assert [p["name"] for p in _packages(_reading()[5])] == ["Git"]
|
||||
|
||||
|
||||
def test_a_host_with_nothing_installed_has_no_packages():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("[]")
|
||||
assert d.get_packages() == []
|
||||
|
||||
|
||||
def test_one_script_reads_both_machine_wide_keys_and_no_users_hive():
|
||||
d = _driver()
|
||||
d.get_packages()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PACKAGES
|
||||
assert r"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
assert r"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" in script
|
||||
# The connecting account's own hive says nothing about the host.
|
||||
assert "HKCU" not in script
|
||||
assert "winget" not in script
|
||||
|
||||
|
||||
def test_installing_and_removing_stay_not_offered():
|
||||
assert not hasattr(WindowsDriver, "install_package")
|
||||
assert not hasattr(WindowsDriver, "uninstall_package")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", ["", "null"])
|
||||
def test_an_empty_answer_has_no_packages(answer):
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(answer)
|
||||
assert d.get_packages() == []
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Processes on Windows: ``Win32_Process`` joined with ``Get-Process`` (NetOrk/netork#2889).
|
||||
|
||||
One script reads both; a fake transport answers it from
|
||||
tests/fixtures/synthetic/processes.json. ``Win32_Process`` gives the parent, the command
|
||||
line, the start and the CPU and memory counters, ``Get-Process -IncludeUserName`` the
|
||||
owner. The fixture holds the cases the join decides:
|
||||
|
||||
* 0, the System Idle Process: no process, left out as ``ps`` leaves it out;
|
||||
* 5120, gone by the time ``Get-Process`` ran: dropped, not half-filled;
|
||||
* 6000, a PID ``Get-Process`` reports with another start: a new process under a PID
|
||||
that was reused between the two reads, dropped;
|
||||
* 7777, started after ``Win32_Process`` was read: not part of the reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import processes as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "processes.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _reading() -> dict[str, Any]:
|
||||
return json.loads(FIXTURE.read_text())
|
||||
|
||||
|
||||
def _driver(reading: dict[str, Any] | None = None) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps(reading if reading is not None else _reading()))
|
||||
return d
|
||||
|
||||
|
||||
def _by_pid(reading: dict[str, Any] | None = None) -> dict[int, Any]:
|
||||
return {p["pid"]: p for p in _driver(reading).get_processes()}
|
||||
|
||||
|
||||
def test_the_join_keeps_the_processes_both_reads_saw():
|
||||
assert sorted(_by_pid()) == [4, 812, 4312]
|
||||
|
||||
|
||||
def test_a_process_reads_like_ps():
|
||||
assert _by_pid()[4312] == {
|
||||
"pid": 4312,
|
||||
"ppid": 3988,
|
||||
"user": "WIN01\\admin",
|
||||
# 120 CPU seconds in 600 s on 4 logical processors
|
||||
"cpu": 5.0,
|
||||
# 100 MiB of 8 GiB
|
||||
"memory": 1.2,
|
||||
"vsz": 2203500000000 // 1024,
|
||||
"rss": 102400,
|
||||
"tty": "",
|
||||
"state": "",
|
||||
# 11:50 UTC, an hour east of it
|
||||
"started": "Mon Dec 1 12:50:00 2025",
|
||||
"command": '"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoLogo',
|
||||
}
|
||||
|
||||
|
||||
def test_a_process_without_a_command_line_shows_its_name():
|
||||
system = _by_pid()[4]
|
||||
assert system["command"] == "System"
|
||||
assert system["started"] == ""
|
||||
assert system["cpu"] == 0.0
|
||||
|
||||
|
||||
def test_a_start_one_second_apart_is_the_same_process():
|
||||
# Get-Process and CIM round the start differently.
|
||||
reading = _reading()
|
||||
reading["owners"][2]["started"] += 1
|
||||
assert 812 in _by_pid(reading)
|
||||
|
||||
|
||||
def test_without_elevation_the_owner_is_unknown():
|
||||
# Get-Process -IncludeUserName needs an elevated session; the script falls back.
|
||||
reading = _reading()
|
||||
for owner in reading["owners"]:
|
||||
owner.pop("user")
|
||||
assert {p["user"] for p in _by_pid(reading).values()} == {""}
|
||||
|
||||
|
||||
def test_cpu_stays_within_a_hundred_percent():
|
||||
reading = _reading()
|
||||
reading["processes"][3]["cpu"] = 10**13
|
||||
assert _by_pid(reading)[4312]["cpu"] == 100.0
|
||||
|
||||
|
||||
def test_a_single_process_survives_powershells_unwrapping():
|
||||
reading = _reading()
|
||||
reading["processes"] = reading["processes"][2]
|
||||
reading["owners"] = reading["owners"][2]
|
||||
assert sorted(_by_pid(reading)) == [812]
|
||||
|
||||
|
||||
def test_one_script_reads_both_sources():
|
||||
d = _driver()
|
||||
d.get_processes()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_PROCESSES
|
||||
assert "Win32_Process" in script
|
||||
assert "Get-Process -IncludeUserName" in script
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_processes()
|
||||
@@ -637,16 +637,3 @@ def test_a_written_task_reads_back_as_the_spec():
|
||||
spec["description"],
|
||||
)
|
||||
assert f"<Command>{execute}</Command>" in xml
|
||||
|
||||
|
||||
def test_an_update_run_task_is_the_drivers_own_and_offers_nothing() -> None:
|
||||
"""A run's SYSTEM task (``windows_update_run``) is no administrator's job, and while it
|
||||
exists it is not to be switched or started again (netork#2892)."""
|
||||
reading = _reading()
|
||||
task = copy.deepcopy(reading["tasks"][0])
|
||||
task.update(path="\\napalm-windows\\", name="update-run-0123456789ab", description="")
|
||||
reading["tasks"].append(task)
|
||||
reading["count"] += 1
|
||||
job = _jobs(reading)["task:\\napalm-windows\\update-run-0123456789ab"]
|
||||
assert job["managed_by"] == "application"
|
||||
assert job["actions"] == []
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The SMBIOS identity on Windows: CIM classes instead of the DMI files (NetOrk/netork#2888).
|
||||
|
||||
One script reads ``Win32_ComputerSystemProduct``, ``Win32_BaseBoard`` and ``Win32_BIOS``;
|
||||
a fake transport answers it from tests/fixtures/synthetic/system_identity.json, a Dell
|
||||
server as the classes describe it. The placeholders are napalm-device-types' own
|
||||
(``clean_system_identity``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import system_identity as mod
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "system_identity.json"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
def __init__(self, answer: str) -> None:
|
||||
self.answer = answer
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
return self.answer
|
||||
|
||||
|
||||
def _driver(**changes: Any) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport(json.dumps({**json.loads(FIXTURE.read_text()), **changes}))
|
||||
return d
|
||||
|
||||
|
||||
def test_reads_the_identity_and_the_firmware():
|
||||
assert _driver().get_system_identity() == {
|
||||
"system_uuid": "4c4c4544-0042-3510-8051-b4c04f4d3732",
|
||||
"product_serial": "4B5QM72",
|
||||
"board_serial": ".4B5QM72.CNCMS0012345AB.",
|
||||
"bios_vendor": "Dell Inc.",
|
||||
"bios_version": "2.19.0",
|
||||
"bios_date": "2023-08-15",
|
||||
}
|
||||
|
||||
|
||||
def test_one_script_reads_the_three_classes():
|
||||
d = _driver()
|
||||
d.get_system_identity()
|
||||
(script,) = d._transport.sent # type: ignore[union-attr]
|
||||
assert script == mod._PS_SYSTEM_IDENTITY
|
||||
for cls in ("Win32_ComputerSystemProduct", "Win32_BaseBoard", "Win32_BIOS"):
|
||||
assert cls in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("product_serial", "To be filled by O.E.M."),
|
||||
("board_serial", "Default string"),
|
||||
("uuid", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"),
|
||||
("uuid", "03000200-0400-0500-0006-000700080009"),
|
||||
("bios_vendor", "To be filled by O.E.M."),
|
||||
],
|
||||
)
|
||||
def test_oem_placeholders_read_as_empty(field, value):
|
||||
identity = _driver(**{field: value}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["uuid", "product_serial", "board_serial", "bios_date"])
|
||||
def test_a_value_the_host_did_not_give_reads_as_empty(field):
|
||||
# A VM without a base board, a firmware without a release date: null in the JSON.
|
||||
identity = _driver(**{field: None}).get_system_identity()
|
||||
key = {"uuid": "system_uuid"}.get(field, field)
|
||||
assert identity[key] == "" # type: ignore[literal-required]
|
||||
|
||||
|
||||
def test_the_release_date_is_the_utc_day():
|
||||
# CIM gives the SMBIOS date as midnight UTC; the script sends it as Unix time.
|
||||
assert _driver(bios_date=1692057600 + 86399).get_system_identity()["bios_date"] == "2023-08-15"
|
||||
|
||||
|
||||
def test_an_empty_answer_is_no_reading():
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport("")
|
||||
with pytest.raises(ValueError):
|
||||
d.get_system_identity()
|
||||
@@ -1,329 +0,0 @@
|
||||
"""Windows Update: the search, the pending list read from it, and the history (netork#2892).
|
||||
|
||||
A fake transport answers each script from tests/fixtures/synthetic/wu_*.json, the JSON
|
||||
the scripts are written to emit. What a real host emits the fixtures cannot prove --
|
||||
see the README there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import PackageIndexMissing
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import windows_update as mod
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
||||
|
||||
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
|
||||
DEFENDER = "Security-Intelligence-Update-for-Microsoft-Defender-Antivirus-Current-Channel-Broad"
|
||||
DOTNET = (
|
||||
"Cumulative-Update-for-.NET-Framework-3.5-4.8-and-4.8.1-for-Microsoft-server-operating-"
|
||||
"system-version-21H2-for-x64"
|
||||
)
|
||||
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
|
||||
|
||||
|
||||
def _fixture(name: str) -> Any:
|
||||
return json.loads((FIXTURES / f"wu_{name}.json").read_text())
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""Answers each Windows Update script with its canned output; records them all."""
|
||||
|
||||
def __init__(self, answers: dict[str, Any]):
|
||||
self.answers = answers
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
self.sent.append(script)
|
||||
answer = self.answers[script]
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
return answer if isinstance(answer, str) else json.dumps(answer)
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _driver(**answers: Any) -> WindowsDriver:
|
||||
scripts = {
|
||||
"search": mod._PS_WU_SEARCH,
|
||||
"pending": mod._PS_WU_PENDING,
|
||||
"history": mod._PS_WU_HISTORY,
|
||||
}
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = FakeTransport({scripts[k]: v for k, v in answers.items()}) # type: ignore[assignment]
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Names
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("title", "name"),
|
||||
[
|
||||
(
|
||||
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
|
||||
"for x64-based Systems (KB5070000)",
|
||||
CU,
|
||||
),
|
||||
(
|
||||
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
|
||||
"(Version 1.441.120.0) - Current Channel (Broad)",
|
||||
DEFENDER,
|
||||
),
|
||||
("Windows Malicious Software Removal Tool x64 - v5.141 (KB890830)", MSRT),
|
||||
(
|
||||
"2026-01 Cumulative Update for Windows 11, version 24H2 for x64-based Systems "
|
||||
"(KB5050009) (26100.2894)",
|
||||
"Cumulative-Update-for-Windows-11-version-24H2-for-x64-based-Systems",
|
||||
),
|
||||
(
|
||||
"2026-11 Kumulatives Update für Microsoft Server Operating System, Version 21H2 "
|
||||
"für x64-basierte Systeme (KB5070000)",
|
||||
"Kumulatives-Update-fur-Microsoft-Server-Operating-System-Version-21H2-fur-"
|
||||
"x64-basierte-Systeme",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_an_update_is_named_by_what_it_keeps_from_month_to_month(title: str, name: str) -> None:
|
||||
"""Next month's cumulative update replaces this one under the same name, so the time
|
||||
the host has been waiting for it is not reset each month: the date, the KB article
|
||||
and the version are left out of the name."""
|
||||
assert mod.update_name(title, ["5070000"], "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11") == name
|
||||
assert mod.NAME.fullmatch(name)
|
||||
|
||||
|
||||
def test_a_title_with_nothing_left_is_named_by_its_kb_then_by_its_id() -> None:
|
||||
assert mod.update_name("(KB5070000)", ["5070000"], "x") == "KB5070000"
|
||||
assert mod.update_name("", [], "8f5c0d55-3b0f") == "8f5c0d55-3b0f"
|
||||
|
||||
|
||||
def test_a_long_title_is_cut_to_a_name_a_store_keeps() -> None:
|
||||
name = mod.update_name("Update " * 80, [], "x")
|
||||
assert len(name) <= mod.NAME_MAX
|
||||
assert not name.endswith("-")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pending updates: read from the last search, never searching in the poll
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _pending(**kw: Any) -> dict[str, dict[str, Any]]:
|
||||
answers = {"pending": _fixture("pending"), **kw}
|
||||
return {u["name"]: dict(u) for u in _driver(**answers).get_available_updates()}
|
||||
|
||||
|
||||
def test_the_pending_list_is_the_last_search_without_what_was_installed_since() -> None:
|
||||
"""The Defender update was installed an hour after the search; the cumulative update
|
||||
has an install in the history, but from before the search -- it is offered again."""
|
||||
pending = _pending()
|
||||
assert sorted(pending) == sorted([CU, DOTNET, MSRT])
|
||||
|
||||
|
||||
def test_a_pending_update_says_what_it_fixes() -> None:
|
||||
cu = _pending()[CU]
|
||||
assert cu == {
|
||||
"name": CU,
|
||||
"current_version": "",
|
||||
"new_version": "KB5070000",
|
||||
"origin": "Windows Update",
|
||||
"security": True,
|
||||
"title": (
|
||||
"2026-11 Cumulative Update for Microsoft server operating system version 21H2 "
|
||||
"for x64-based Systems (KB5070000)"
|
||||
),
|
||||
"advisories": ["KB5070000"],
|
||||
"cves": ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003"],
|
||||
"vendor_severity": "Critical",
|
||||
}
|
||||
|
||||
|
||||
def test_security_is_what_windows_classifies_so() -> None:
|
||||
pending = _pending()
|
||||
assert pending[DOTNET]["security"] is True
|
||||
assert pending[DOTNET]["vendor_severity"] == "Important"
|
||||
# The removal tool is an update rollup: known, and not a security update.
|
||||
assert pending[MSRT]["security"] is False
|
||||
assert pending[MSRT]["vendor_severity"] is None
|
||||
assert pending[MSRT]["cves"] == []
|
||||
|
||||
|
||||
def test_optional_updates_and_feature_upgrades_are_not_pending() -> None:
|
||||
"""A preview Windows does not install by itself, and an in-place upgrade of the OS,
|
||||
are no pending updates: this path installs neither."""
|
||||
names = set(_pending())
|
||||
assert not any("Preview" in n for n in names)
|
||||
assert not any("upgrade" in n for n in names)
|
||||
|
||||
|
||||
def test_definition_updates_count_as_security() -> None:
|
||||
search = _fixture("search")
|
||||
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
||||
assert _pending(pending=reading)[DEFENDER]["security"] is True
|
||||
|
||||
|
||||
def test_updates_of_the_same_name_are_one_entry() -> None:
|
||||
search = _fixture("search")
|
||||
twin = dict(search["updates"][0], id="00000000-0000-4000-8000-000000000001")
|
||||
twin.update(kb=["5070001"], cves=["CVE-2026-21009"], severity="Moderate")
|
||||
search["updates"].append(twin)
|
||||
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
||||
cu = _pending(pending=reading)[CU]
|
||||
assert cu["new_version"] == "KB5070000 KB5070001"
|
||||
assert cu["advisories"] == ["KB5070000", "KB5070001"]
|
||||
assert cu["cves"] == ["CVE-2026-21001", "CVE-2026-21002", "CVE-2026-21003", "CVE-2026-21009"]
|
||||
assert cu["vendor_severity"] == "Critical" # the higher of the two
|
||||
|
||||
|
||||
def test_an_update_without_a_kb_shows_its_revision() -> None:
|
||||
search = _fixture("search")
|
||||
search["updates"][3]["kb"] = []
|
||||
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
||||
assert _pending(pending=reading)[MSRT]["new_version"] == "rev 1"
|
||||
|
||||
|
||||
def test_a_wsus_client_names_its_server() -> None:
|
||||
search = dict(_fixture("search"), wsus="https://wsus.example.lan:8531")
|
||||
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
||||
assert _pending(pending=reading)[CU]["origin"] == "WSUS https://wsus.example.lan:8531"
|
||||
|
||||
|
||||
def test_no_search_yet_is_a_missing_index_that_a_refresh_cures() -> None:
|
||||
with pytest.raises(PackageIndexMissing, match="refresh"):
|
||||
_pending(pending={"search": None, "installed": [], "history_error": None})
|
||||
|
||||
|
||||
def test_a_failed_history_read_keeps_the_search_as_it_was() -> None:
|
||||
reading = dict(_fixture("pending"), installed=[], history_error="0x8024000C")
|
||||
assert DEFENDER in _pending(pending=reading)
|
||||
|
||||
|
||||
def test_a_reading_that_is_no_search_raises() -> None:
|
||||
with pytest.raises(ValueError, match="Windows Update"):
|
||||
_pending(pending={"search": "[1, 2]", "installed": [], "history_error": None})
|
||||
|
||||
|
||||
def test_the_poll_does_not_search() -> None:
|
||||
"""The search takes minutes: the poll reads what the refresh found."""
|
||||
d = _driver(pending=_fixture("pending"))
|
||||
d.get_available_updates()
|
||||
assert d._transport.sent == [mod._PS_WU_PENDING] # type: ignore[union-attr]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Refresh: the search itself
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_refresh_searches_and_says_what_it_found() -> None:
|
||||
result = _driver(search=_fixture("search")).refresh_available_updates()
|
||||
assert result["success"] is True
|
||||
assert result["output"] == (
|
||||
"Windows Update offers 4 updates, 3 of them for security, searched in 94 s."
|
||||
)
|
||||
|
||||
|
||||
def test_a_refresh_windows_refuses_is_a_failed_refresh() -> None:
|
||||
d = _driver(search=PowerShellError("Exception from HRESULT: 0x8024402C"))
|
||||
assert d.refresh_available_updates() == {
|
||||
"success": False,
|
||||
"output": "Exception from HRESULT: 0x8024402C",
|
||||
}
|
||||
|
||||
|
||||
def test_a_search_script_keeps_what_it_found_for_the_poll() -> None:
|
||||
"""The search writes its reading where only administrators can write, and the poll's
|
||||
script reads it there."""
|
||||
assert "Set-ItemProperty" in mod._PS_WU_SEARCH
|
||||
assert mod.STORE in mod._PS_WU_SEARCH and mod.STORE in mod._PS_WU_PENDING
|
||||
assert mod.STORE.startswith("HKLM:\\SOFTWARE\\napalm-windows\\")
|
||||
assert "Type='Software'" in mod._PS_WU_SEARCH # no drivers
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# History
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _history(since: int | None = None, reading: Any = None) -> list[dict[str, Any]]:
|
||||
d = _driver(history=_fixture("history") if reading is None else reading)
|
||||
return [dict(t) for t in d.get_update_history(since)]
|
||||
|
||||
|
||||
def test_each_history_entry_is_a_transaction_newest_first() -> None:
|
||||
history = _history()
|
||||
assert [t["start"] for t in history] == sorted((t["start"] for t in history), reverse=True)
|
||||
first = history[0]
|
||||
assert first == {
|
||||
"id": "d2b5e0a8-6c3e-4c9b-8a55-0f6b5bb2a1c4:200:1:1795603600",
|
||||
"start": 1795603600,
|
||||
"end": 1795603600,
|
||||
"packages": [
|
||||
{
|
||||
"name": DEFENDER,
|
||||
"action": "install",
|
||||
"old_version": None,
|
||||
"new_version": "KB2267602",
|
||||
"title": (
|
||||
"Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 "
|
||||
"(Version 1.441.120.0) - Current Channel (Broad)"
|
||||
),
|
||||
}
|
||||
],
|
||||
"requested_by": "Windows Defender (77BDAF73-B396-481F-9042-AD358843EC24)",
|
||||
"command": None,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
|
||||
def test_a_failed_install_names_its_error() -> None:
|
||||
failed = next(t for t in _history() if t["requested_by"] == "napalm-windows")
|
||||
assert failed["error"] == "failed (0x80240017)"
|
||||
|
||||
|
||||
def test_an_uninstall_removes_its_kb() -> None:
|
||||
removed = next(t for t in _history() if t["packages"][0]["action"] == "remove")
|
||||
assert removed["packages"][0]["old_version"] == "KB5007651"
|
||||
assert removed["packages"][0]["new_version"] is None
|
||||
|
||||
|
||||
def test_an_install_still_running_has_no_end_and_an_unknown_requester() -> None:
|
||||
running = _history()[-1]
|
||||
assert running["end"] is None
|
||||
assert running["requested_by"] is None
|
||||
assert running["error"] is None
|
||||
|
||||
|
||||
def test_the_history_since_a_moment() -> None:
|
||||
assert [t["start"] for t in _history(since=1795590000)] == [1795603600, 1795590000]
|
||||
|
||||
|
||||
def test_an_empty_history() -> None:
|
||||
assert _history(reading="") == []
|
||||
|
||||
|
||||
def test_other_results_are_named() -> None:
|
||||
entry = dict(_fixture("history")[0], result=5, hresult=0)
|
||||
assert _history(reading=[entry])[0]["error"] == "aborted"
|
||||
entry = dict(entry, result=3, hresult=-2145124329)
|
||||
assert _history(reading=[entry])[0]["error"] == "succeeded with errors (0x80240017)"
|
||||
|
||||
|
||||
def test_one_name_is_unknown_security_when_one_of_its_updates_does_not_say() -> None:
|
||||
search = _fixture("search")
|
||||
twin = dict(search["updates"][3], id="00000000-0000-4000-8000-000000000002")
|
||||
twin["classifications"] = []
|
||||
search["updates"].append(twin)
|
||||
reading = {"search": json.dumps(search), "installed": [], "history_error": None}
|
||||
assert _pending(pending=reading)[MSRT]["security"] is None
|
||||
@@ -1,271 +0,0 @@
|
||||
"""Installing Windows updates in a one-shot SYSTEM task (netork#2892).
|
||||
|
||||
The transport is faked: each script the run sends is recognised by what it does and
|
||||
answered as the host would. The SYSTEM script itself is read here as text; what Windows
|
||||
Update does with it only a real host can show.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_windows import WindowsDriver
|
||||
from napalm_windows import windows_update as wu
|
||||
from napalm_windows import windows_update_run as mod
|
||||
from napalm_windows.transport import PowerShellError
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures" / "synthetic"
|
||||
|
||||
CU_ID = "8f5c0d55-3b0f-4ad0-9a3e-1a8a0d7f6e11:1"
|
||||
DOTNET_ID = "1c7f9e2a-5b4d-4e0f-9d8c-3a2b1c0d9e8f:3"
|
||||
MSRT_ID = "6a0d3c1e-9f8b-4d7a-8e6c-5b4a3f2e1d0c:1"
|
||||
CU = "Cumulative-Update-for-Microsoft-server-operating-system-version-21H2-for-x64-based-Systems"
|
||||
MSRT = "Windows-Malicious-Software-Removal-Tool-x64"
|
||||
|
||||
|
||||
class Host:
|
||||
"""The host's side of a run: what the sweep finds, and what each look shows."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
looks: list[dict[str, Any]] | None = None,
|
||||
busy: list[str] | None = None,
|
||||
start_fails: str | None = None,
|
||||
):
|
||||
self.looks = list(looks or [])
|
||||
self.busy = busy or []
|
||||
self.start_fails = start_fails
|
||||
self.sent: list[str] = []
|
||||
self.is_open = True
|
||||
|
||||
def kind(self, script: str) -> str:
|
||||
if script == wu._PS_WU_PENDING:
|
||||
return "pending"
|
||||
if "busy" in script and "Unregister-ScheduledTask" in script:
|
||||
return "sweep"
|
||||
if "Register-ScheduledTask" in script:
|
||||
return "start"
|
||||
if "$state = 'gone'" in script:
|
||||
return "follow"
|
||||
if "Remove-Item -LiteralPath $key" in script:
|
||||
return "cleanup"
|
||||
raise AssertionError(f"unexpected script: {script[:80]}")
|
||||
|
||||
def run(self, script: str) -> str:
|
||||
kind = self.kind(script)
|
||||
self.sent.append(kind)
|
||||
if kind == "pending":
|
||||
return (FIXTURES / "wu_pending.json").read_text()
|
||||
if kind == "sweep":
|
||||
return json.dumps({"busy": self.busy, "swept": ["update-run-0123456789ab"]})
|
||||
if kind == "start":
|
||||
self.start_script = script
|
||||
if self.start_fails:
|
||||
raise PowerShellError(self.start_fails)
|
||||
return ""
|
||||
if kind == "follow":
|
||||
return json.dumps(self.looks.pop(0))
|
||||
return ""
|
||||
|
||||
def close(self) -> None:
|
||||
self.is_open = False
|
||||
|
||||
|
||||
def _look(state: str, log: list[str], result: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
return {"state": state, "log": "\n".join(log), "result": json.dumps(result) if result else ""}
|
||||
|
||||
|
||||
def _result(**kw: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"reboot_required": False,
|
||||
"installed": [],
|
||||
"refused": [],
|
||||
"failed": [],
|
||||
"error": None,
|
||||
**kw,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_waiting(monkeypatch: pytest.MonkeyPatch) -> list[float]:
|
||||
slept: list[float] = []
|
||||
monkeypatch.setattr(mod.time, "sleep", slept.append)
|
||||
return slept
|
||||
|
||||
|
||||
def _driver(host: Host) -> WindowsDriver:
|
||||
d = WindowsDriver("win01", "admin", "secret")
|
||||
d._transport = host # type: ignore[assignment]
|
||||
return d
|
||||
|
||||
|
||||
def test_a_run_installs_in_a_system_task_and_hands_on_each_line() -> None:
|
||||
host = Host(
|
||||
[
|
||||
_look("Running", ["Searching Windows Update again for the chosen updates"]),
|
||||
_look(
|
||||
"Ready",
|
||||
[
|
||||
"Searching Windows Update again for the chosen updates",
|
||||
"Downloading 1 update(s)",
|
||||
"Installing 1 update(s); the host is not restarted",
|
||||
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
|
||||
"A restart finishes the installation.",
|
||||
],
|
||||
_result(installed=[CU_ID], reboot_required=True),
|
||||
),
|
||||
]
|
||||
)
|
||||
seen: list[str] = []
|
||||
result = _driver(host).apply_updates([CU], log=seen.append)
|
||||
|
||||
assert result["success"] is True
|
||||
assert "error" not in result
|
||||
assert host.sent == ["pending", "sweep", "start", "follow", "follow", "cleanup"]
|
||||
assert seen[0].startswith("Chosen: 2026-11 Cumulative Update")
|
||||
assert seen[1:] == [
|
||||
"Searching Windows Update again for the chosen updates",
|
||||
"Downloading 1 update(s)",
|
||||
"Installing 1 update(s); the host is not restarted",
|
||||
"Installed: 2026-11 Cumulative Update ... (KB5070000) (" + CU_ID + ")",
|
||||
"A restart finishes the installation.",
|
||||
]
|
||||
assert result["output"] == "\n".join(seen)
|
||||
|
||||
|
||||
def test_the_task_gets_exactly_the_updates_chosen_and_runs_as_system() -> None:
|
||||
host = Host([_look("Ready", [], _result(installed=[CU_ID]))])
|
||||
_driver(host).apply_updates([CU])
|
||||
start = host.start_script
|
||||
assert f"@('{CU_ID}')" in start
|
||||
assert DOTNET_ID not in start
|
||||
assert "-UserId 'SYSTEM'" in start and "-RunLevel Highest" in start
|
||||
assert "Register-ScheduledTask -TaskPath '\\napalm-windows\\'" in start
|
||||
# The script travels in the run's registry key, never as a file.
|
||||
assert "-Name Script" in start and ".ps1" not in start
|
||||
|
||||
|
||||
def test_every_pending_update_when_none_is_named() -> None:
|
||||
host = Host([_look("Ready", [], _result(installed=[CU_ID, DOTNET_ID, MSRT_ID]))])
|
||||
assert _driver(host).apply_updates([])["success"] is True
|
||||
for identity in (CU_ID, DOTNET_ID, MSRT_ID):
|
||||
assert f"'{identity}'" in host.start_script
|
||||
|
||||
|
||||
def test_a_name_the_last_search_does_not_offer_is_refused_and_the_rest_installed() -> None:
|
||||
host = Host([_look("Ready", ["Installed: x"], _result(installed=[MSRT_ID]))])
|
||||
seen: list[str] = []
|
||||
result = _driver(host).apply_updates([MSRT, "Gone-Update"], log=seen.append)
|
||||
assert seen[0] == "Refused Gone-Update: not offered by the last search"
|
||||
assert result["success"] is False
|
||||
assert result["error"] == "1 update(s) refused, 0 failed."
|
||||
|
||||
|
||||
def test_only_names_the_search_does_not_offer_start_nothing() -> None:
|
||||
host = Host()
|
||||
result = _driver(host).apply_updates(["Gone-Update"])
|
||||
assert result["success"] is False
|
||||
assert host.sent == ["pending"]
|
||||
|
||||
|
||||
def test_nothing_pending_is_nothing_to_install() -> None:
|
||||
result = mod.install(lambda s: "", {}, [], None)
|
||||
assert result == {"success": True, "output": "Nothing to install."}
|
||||
|
||||
|
||||
def test_a_name_that_is_no_package_name_is_refused_before_anything_runs() -> None:
|
||||
host = Host()
|
||||
with pytest.raises(ValueError, match="Invalid update name"):
|
||||
_driver(host).apply_updates(["KB1; Restart-Computer"])
|
||||
assert host.sent == []
|
||||
|
||||
|
||||
def test_what_the_task_refused_or_failed_makes_the_run_fail() -> None:
|
||||
refused = {"id": CU_ID, "reason": "it asks for input while it installs"}
|
||||
failed = {"id": DOTNET_ID, "step": "Install", "result": 4, "hresult": -2145124329}
|
||||
host = Host([_look("Ready", [], _result(refused=[refused], failed=[failed]))])
|
||||
result = _driver(host).apply_updates([])
|
||||
assert result["success"] is False
|
||||
assert result["error"] == "1 update(s) refused, 1 failed."
|
||||
|
||||
|
||||
def test_a_pending_restart_installs_nothing_and_says_so() -> None:
|
||||
error = "A restart is pending on the host: nothing is installed until it has restarted."
|
||||
host = Host([_look("Ready", [error], _result(error=error))])
|
||||
result = _driver(host).apply_updates([CU])
|
||||
assert result["success"] is False
|
||||
assert result["error"] == error
|
||||
|
||||
|
||||
def test_a_task_that_ends_without_a_result_failed_and_is_cleaned_up() -> None:
|
||||
host = Host([_look("Ready", ["Downloading 1 update(s)"])])
|
||||
result = _driver(host).apply_updates([CU])
|
||||
assert result["success"] is False
|
||||
assert result["error"] == "The update task ended without a result."
|
||||
assert host.sent[-1] == "cleanup"
|
||||
|
||||
|
||||
def test_an_earlier_run_still_installing_refuses_this_one() -> None:
|
||||
host = Host(busy=["update-run-0123456789ab"])
|
||||
result = _driver(host).apply_updates([CU])
|
||||
assert result["success"] is False
|
||||
assert "still installing" in result["error"]
|
||||
assert host.sent == ["pending", "sweep"]
|
||||
|
||||
|
||||
def test_a_run_followed_too_long_is_left_to_finish_on_the_host(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
clock = iter([0.0, 10.0, mod.FOLLOW_SECONDS + 1.0])
|
||||
monkeypatch.setattr(mod.time, "monotonic", lambda: next(clock))
|
||||
host = Host([_look("Running", ["Downloading 1 update(s)"]), _look("Running", [])])
|
||||
result = _driver(host).apply_updates([CU])
|
||||
assert result["success"] is False
|
||||
assert "carries on there" in result["error"]
|
||||
assert "cleanup" not in host.sent # the next run's sweep deletes it once it ended
|
||||
|
||||
|
||||
def test_a_task_windows_refuses_to_register_raises() -> None:
|
||||
host = Host(start_fails="Access is denied.")
|
||||
with pytest.raises(PowerShellError, match="Access is denied"):
|
||||
_driver(host).apply_updates([CU])
|
||||
|
||||
|
||||
def test_the_follower_waits_between_looks(no_waiting: list[float]) -> None:
|
||||
host = Host([_look("Running", []), _look("Ready", [], _result(installed=[CU_ID]))])
|
||||
_driver(host).apply_updates([CU])
|
||||
assert no_waiting == [mod.POLL_SECONDS, mod.POLL_SECONDS]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The SYSTEM script, read as text
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_system_script_guards_what_it_installs() -> None:
|
||||
script = mod.run_script("0123456789ab")
|
||||
assert "HKLM:\\SOFTWARE\\napalm-windows\\WindowsUpdate\\Runs\\0123456789ab" in script
|
||||
# A pending restart refuses everything before any download.
|
||||
assert script.index("$pending -or $installer.RebootRequiredBeforeInstallation") < (
|
||||
script.index("CreateUpdateDownloader")
|
||||
)
|
||||
# Exactly the ID and revision, offered once, quiet, licence accepted on the host.
|
||||
assert "no longer offered" in script
|
||||
assert "offered more than once" in script
|
||||
assert "CanRequestUserInput" in script
|
||||
assert "EulaAccepted" in script
|
||||
assert "AcceptEula" not in script
|
||||
# Never restarts, and Windows Update's history names the run.
|
||||
assert "Restart-Computer" not in script and "shutdown" not in script.lower()
|
||||
assert "ClientApplicationID = 'napalm-windows'" in script
|
||||
|
||||
|
||||
def test_the_scripts_quote_what_they_are_given() -> None:
|
||||
start = mod._script(mod._PS_START, RUN="'x'", TASK="'t'", REQUESTED="'a'", SCRIPT="'s'")
|
||||
assert "__" not in start
|
||||
for template in (mod._PS_SWEEP, mod._PS_FOLLOW, mod._PS_CLEANUP):
|
||||
assert "__" not in mod._script(template, RUN="'x'", TASK="'t'")
|
||||
+15
-6
@@ -14,7 +14,16 @@ import argparse
|
||||
import getpass
|
||||
import pathlib
|
||||
|
||||
from napalm_windows import WindowsDriver, scheduled_tasks, time_sync, windows_update
|
||||
from napalm_windows import (
|
||||
WindowsDriver,
|
||||
host_status,
|
||||
os_users,
|
||||
packages,
|
||||
processes,
|
||||
scheduled_tasks,
|
||||
system_identity,
|
||||
time_sync,
|
||||
)
|
||||
from napalm_windows import windows as mod
|
||||
|
||||
SCRIPTS = {
|
||||
@@ -27,11 +36,11 @@ SCRIPTS = {
|
||||
"listening": mod._PS_LISTENING,
|
||||
"scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS,
|
||||
"time_sync": time_sync._PS_TIME_SYNC,
|
||||
# The search takes minutes and keeps its reading under HKLM\SOFTWARE\napalm-windows,
|
||||
# which the pending reading after it reads back. Nothing is installed.
|
||||
"wu_search": windows_update._PS_WU_SEARCH,
|
||||
"wu_pending": windows_update._PS_WU_PENDING,
|
||||
"wu_history": windows_update._PS_WU_HISTORY,
|
||||
"system_identity": system_identity._PS_SYSTEM_IDENTITY,
|
||||
"processes": processes._PS_PROCESSES,
|
||||
"os_users": os_users._PS_OS_USERS,
|
||||
"packages": packages._PS_PACKAGES,
|
||||
"host_status": host_status._PS_HOST_STATUS,
|
||||
}
|
||||
|
||||
OUT = pathlib.Path(__file__).parent / "harvest-out"
|
||||
|
||||
Reference in new issue
Block a user