refresh_available_updates runs the Windows Update Agent's search against the configured source and keeps its reading under HKLM\SOFTWARE\napalm-windows; get_available_updates reads it back without a search, leaving out what the history shows installed since, and raises PackageIndexMissing before the first search. Each update carries its title, KB articles, CveIDs and MsrcSeverity, and is named by its title without month, KB and version, so next month's cumulative update keeps the name. Previews, feature upgrades and drivers are left out. apply_updates installs in a one-shot task running as SYSTEM, since Windows refuses downloads and installs to a network logon. The task's script and the exact UpdateID:revision chosen travel in the run's registry key; it searches again, refuses what no longer matches exactly, what asks for input or has unaccepted licence terms, installs nothing while a restart is pending and never restarts. Its log is followed line by line; the next run sweeps what a dead run left. get_scheduled_jobs shows these tasks as an application's. get_update_history reads QueryHistory, one transaction per entry, with the ClientApplicationID as requested_by.
342 lines
14 KiB
Python
342 lines
14 KiB
Python
"""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))
|