From a508b872b017e6840f2a359207a8ed271f969eb3 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 3 Nov 2026 05:49:12 +0100 Subject: [PATCH 1/2] feat(scheduled-jobs): the Task Scheduler as scheduled jobs (#8) netOrk shows and controls every scheduled job of a host; on Windows that is the Task Scheduler. The driver now implements napalm-device-types' ScheduledJobsMixin over PowerShell Remoting, one script per call as every getter does. get_scheduled_jobs reads every task with its run info in one script (Get-ScheduledTask, Get-ScheduledTaskInfo) as task:, its triggers summarised. Tasks under \Microsoft\ are the platform's, others the admin's: Windows does not record which software installed a task. The time zone is mapped to IANA for the common Windows zones, else None. A reading cut short, or holding fewer tasks than it counted, raises. manage_scheduled_job switches the task's own flag or starts it; Start-ScheduledTask returns once the task has started, so the result says that and no more. A disabled task, or one that refuses a start on demand, is not offered run. put_scheduled_job registers an application's task \ in the root folder from XML, so a create and a change write the whole definition the same way: the command runs in cmd.exe /d /s /c, the principal is SYSTEM or a local user without a stored password (S4U), and the cron expression becomes triggers only where Task Scheduler can say it exactly; any other shape is refused, naming why. The description keeps the job's name and cron expression, so the reading gives back what was written, and the digest also covers the triggers, so a change by hand is seen. delete_scheduled_job unregisters such a task and no other. Every write reads the task again first, and every value goes into PowerShell single-quoted with its quotes doubled. Requires napalm-device-types 4.26.0. Closes #8 --- CHANGELOG.md | 16 + README.md | 29 +- napalm_windows/_powershell.py | 24 + napalm_windows/scheduled_tasks.py | 461 +++++++++++++ napalm_windows/task_xml.py | 249 +++++++ napalm_windows/time_zones.py | 115 ++++ napalm_windows/windows.py | 23 +- pyproject.toml | 2 +- tests/fixtures/synthetic/scheduled_tasks.json | 100 +++ tests/test_scheduled_jobs.py | 639 ++++++++++++++++++ tests/test_task_xml.py | 260 +++++++ tools/harvest.py | 3 +- 12 files changed, 1898 insertions(+), 23 deletions(-) create mode 100644 napalm_windows/_powershell.py create mode 100644 napalm_windows/scheduled_tasks.py create mode 100644 napalm_windows/task_xml.py create mode 100644 napalm_windows/time_zones.py create mode 100644 tests/fixtures/synthetic/scheduled_tasks.json create mode 100644 tests/test_scheduled_jobs.py create mode 100644 tests/test_task_xml.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c90bfc6..5c371e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,23 @@ All notable changes to this driver. The format follows ## [Unreleased] +### Added +- Scheduled jobs: the Task Scheduler as napalm-device-types' `ScheduledJobsMixin` (#8). + `get_scheduled_jobs` reads every task with its last and next run in one script + (`Get-ScheduledTask`, `Get-ScheduledTaskInfo`) as `task:`: a task under + `\Microsoft\` is the `platform`'s, any other the `admin`'s, and a task in the root + folder whose description starts with `napalm-scheduled-job: ` an `application`'s. + The time zone comes as an IANA name for the common Windows zones, else `None`. + `manage_scheduled_job` enables, disables (`Enable-`/`Disable-ScheduledTask`) or starts + one (`Start-ScheduledTask`, which returns once the task has started). `put_scheduled_job` + registers an application's task `\` from XML: the command runs in + `cmd.exe /d /s /c`, `SYSTEM` or a local user without a stored password (S4U), and the + cron expression becomes triggers where Task Scheduler can express it exactly; any other + shape is refused, naming why. `delete_scheduled_job` unregisters it. Every write reads + the task again first and refuses over a change it did not see. Fixture synthetic. + ### Changed +- The floor on napalm-device-types is 4.26.0, which declares the scheduled-jobs contract. - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6). - The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python diff --git a/README.md b/README.md index 61735b9..c5c72ad 100644 --- a/README.md +++ b/README.md @@ -38,12 +38,39 @@ handshake once. | `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) | | `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` | | `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) | +| `get_scheduled_jobs` | `Get-ScheduledTask` + `Get-ScheduledTaskInfo`, one script; `\Microsoft\*` is `platform`, other tasks `admin`, the root task an application wrote `application`; time zone mapped to IANA for the common zones | +| `manage_scheduled_job` | `Enable-`/`Disable-ScheduledTask`, `Start-ScheduledTask` (returns once started; the result shows in the next reading) | +| `put_scheduled_job` / `delete_scheduled_job` | `Register-ScheduledTask -Xml -Force` in the root folder, `Unregister-ScheduledTask`; an application's tasks only | `running_kernel` carries the full build including the update revision (`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE matching has to compare against. -Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V. +### Scheduled tasks + +An application's own job is the task `\` in the root folder, never a folder of +its own. Its description is `napalm-scheduled-job: ` and a second +line `schedule: `, so the reading gives back the cron expression and +the command it was written with; its digest also covers the triggers, so triggers +changed by hand count as a change. + +* **Command:** `cmd.exe /d /s /c ""` — one line, as a Windows command line. +* **Principal:** `SYSTEM`, or a local user who runs it whether logged on or not + without a stored password (`S4U`). Such a run has no network credentials, and the + user needs the "Log on as a batch job" right. +* **Schedule:** a cron expression becomes triggers only where Task Scheduler can + express it exactly — daily, weekly on weekdays, or monthly on days of the month (in + some months); at one or more times, or evenly spaced times as one repetition + (`*/5`, `*/15 8-17`, `0 */6`), or one repeating trigger per hour (`*/7`); at most 48 + triggers. `@reboot` is a boot trigger. Refused, naming why: both a day of the month + and a weekday (cron's *either* rule), a weekday together with days or months, and + times needing more than 48 triggers. A repetition counts elapsed time, so on the day + summer time starts or ends its later runs shift by the hour. +* **Not read:** which software installed a task (Windows does not record it), so a + vendor's updater is `admin`; and the days of a monthly trigger, which + `Get-ScheduledTask` does not expose. + +Not yet: packages, Windows Update, health metrics, Hyper-V. See netork#300 for the plan. ## Preparing a host diff --git a/napalm_windows/_powershell.py b/napalm_windows/_powershell.py new file mode 100644 index 0000000..9271f69 --- /dev/null +++ b/napalm_windows/_powershell.py @@ -0,0 +1,24 @@ +"""What every script and every parse of this driver shares: quoting and the JSON quirk.""" + +from __future__ import annotations + +from typing import Any + +# PowerShell accepts these as single-quote delimiters alongside the ASCII one. +_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛") + + +def _as_list(value: Any) -> list[Any]: + """Undo ConvertTo-Json unwrapping a one-element array into a bare value.""" + if value is None: + return [] + if isinstance(value, list): + return value + return [value] + + +def _ps_quote(value: str) -> str: + """Quote ``value`` as a PowerShell single-quoted (verbatim) string.""" + for q in _PS_SINGLE_QUOTES: + value = value.replace(q, q + q) + return f"'{value}'" diff --git a/napalm_windows/scheduled_tasks.py b/napalm_windows/scheduled_tasks.py new file mode 100644 index 0000000..07e8c8b --- /dev/null +++ b/napalm_windows/scheduled_tasks.py @@ -0,0 +1,461 @@ +"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8). + +:class:`WindowsScheduledJobsMixin` implements napalm-device-types' +:class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` for the driver, +which carries each script across ``PsrpTransport.run``. + +**Reading** is one script: every task (``Get-ScheduledTask``) with what the host +says of its runs (``Get-ScheduledTaskInfo``), projected onto flat fields, and the +host's time zone; Python only normalises. Every task is a job ``task:`` +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 -- and a task in the root folder whose description starts with +``napalm-scheduled-job: `` 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. + +**Switching** is the task's own flag (``Enable-`` / ``Disable-ScheduledTask``); +**running** is ``Start-ScheduledTask``, which returns once the task has started: how +the run ends shows in the next reading. A disabled task, or one that does not allow a +start on demand, is not offered ``run``. A task is addressed by its exact path and +name, never by ``-TaskName``, which takes wildcards. + +**An application's own job** is registered from XML (``Register-ScheduledTask -Xml +-Force``), so creating it and changing it write the whole definition the same way; +``delete_scheduled_job`` unregisters it. Before every write the job is read again +and compared with the digest the caller saw; a task of the same name that an +application did not write is never overwritten. Every value goes into PowerShell +single-quoted, its quotes doubled. +""" + +from __future__ import annotations + +import json +import re +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any, NamedTuple + +from napalm_device_types import ( + ScheduledJobChanged, + ScheduledJobDict, + ScheduledJobRefused, + ScheduledJobResultDict, + ScheduledJobsMixin, + ScheduledJobSpecDict, + ScheduledJobsReadingDict, + job_digest, +) +from napalm_device_types.scheduled_jobs import ACTIONS, DELETE, EDIT, check_spec + +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 + +# 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. +_PS_SCHEDULED_TASKS = r""" +$ErrorActionPreference = 'Stop' +function U($d) { if ($d) { ([datetime]$d).ToUniversalTime().ToString('o') } } +$tasks = @(Get-ScheduledTask) +$rows = @($tasks | ForEach-Object { + $t = $_ + $i = $t | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue + [pscustomobject]@{ + path = $t.TaskPath + name = $t.TaskName + state = [string]$t.State + user = $t.Principal.UserId + group = $t.Principal.GroupId + on_demand = $t.Settings.AllowDemandStart + description = $t.Description + actions = @($t.Actions | ForEach-Object { + [pscustomobject]@{ + class = $_.CimClass.CimClassName + execute = $_.Execute + arguments = $_.Arguments + class_id = $_.ClassId + } + }) + triggers = @($t.Triggers | ForEach-Object { + [pscustomobject]@{ + class = $_.CimClass.CimClassName + enabled = $_.Enabled + start = [string]$_.StartBoundary + days_interval = $_.DaysInterval + weeks_interval = $_.WeeksInterval + days_of_week = $_.DaysOfWeek + interval = [string]$_.Repetition.Interval + duration = [string]$_.Repetition.Duration + delay = [string]$_.Delay + } + }) + last_run = U $i.LastRunTime + last_result = $i.LastTaskResult + next_run = U $i.NextRunTime + } +}) +ConvertTo-Json -Compress -Depth 5 -InputObject ([pscustomobject]@{ + time_zone = [System.TimeZoneInfo]::Local.Id + count = $tasks.Count + tasks = $rows +}) +""" + +# One task by its exact path and name, handed to a cmdlet. +_PS_TASK_CMDLET = r""" +$ErrorActionPreference = 'Stop' +$task = @(Get-ScheduledTask | Where-Object {{ $_.TaskPath -eq {path} -and $_.TaskName -eq {name} }}) +if ($task.Count -ne 1) {{ throw ('no single scheduled task ' + {path} + {name}) }} +$task[0] | {cmdlet} | Out-Null +""" + +_PS_REGISTER = r""" +$ErrorActionPreference = 'Stop' +Register-ScheduledTask -TaskPath {path} -TaskName {name} -Xml {xml} -Force | Out-Null +""" + +_PS_UNREGISTER = r""" +$ErrorActionPreference = 'Stop' +Unregister-ScheduledTask -TaskPath {path} -TaskName {name} -Confirm:$false +""" + +_CMDLETS = { + "enable": ("Enable-ScheduledTask", "enabled"), + "disable": ("Disable-ScheduledTask", "disabled"), + "run": ( + "Start-ScheduledTask", + "started; Start-ScheduledTask returns once it has started, so how the run " + "ends shows in the next reading", + ), +} + +_ROOT = "\\" +_JOB_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}") +_DOTNET_DATE = re.compile(r"^/Date\((-?\d+)(?:[+-]\d{4})?\)/$") +_BOUNDARY = re.compile(r"^(\d{4}-\d\d-\d\d)T(\d\d:\d\d)(?::\d\d(?:\.\d+)?)?(Z|[+-]\d\d:\d\d)?$") +_DURATION = re.compile(r"^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$") +_DURATION_UNITS = ("day", "hour", "minute", "second") + +#: LastTaskResult: SCHED_S_TASK_RUNNING and SCHED_S_TASK_HAS_NOT_RUN. +_RUNNING = 0x41301 +_NEVER_RAN = 0x41303 + +_WEEKDAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") +_EVENT_TRIGGERS = { + "MSFT_TaskBootTrigger": "at startup", + "MSFT_TaskLogonTrigger": "at logon", + "MSFT_TaskIdleTrigger": "on idle", + "MSFT_TaskEventTrigger": "on an event", + "MSFT_TaskSessionStateChangeTrigger": "session state change", + "MSFT_TaskRegistrationTrigger": "at registration", +} + + +# --------------------------------------------------------------------------- +# Reading +# --------------------------------------------------------------------------- + + +def _timestamp(value: Any) -> str | None: + """A time as the host gave it -- ISO 8601, ``/Date(ms)/`` or epoch seconds -- as + ISO 8601 in UTC; None for none, and for Task Scheduler's never (30 November 1999).""" + if value is None or value == "": + return None + if isinstance(value, int | float): + at = datetime.fromtimestamp(value, UTC) + elif match := _DOTNET_DATE.match(str(value).strip()): + at = datetime.fromtimestamp(int(match[1]) / 1000, UTC) + else: + try: + at = datetime.fromisoformat(str(value).strip()) + except ValueError: + return None + at = (at if at.tzinfo else at.replace(tzinfo=UTC)).astimezone(UTC) + return None if at.year < 2000 else at.isoformat() + + +def _last_result(code: Any, last_run: str | None) -> str | None: + if last_run is None or code is None: + return None + code = int(code) & 0xFFFFFFFF + if code == _NEVER_RAN: + return None + if code == _RUNNING: + return "running" + return "success" if code == 0 else f"0x{code:X}" + + +def _readable_duration(value: str) -> str: + """``PT1H30M`` → ``1 hour 30 minutes``; anything else as it is.""" + match = _DURATION.match(value) + if not match or not any(match.groups()): + return value + parts = [ + f"{n} {unit}{'' if n == '1' else 's'}" + for n, unit in zip(match.groups(), _DURATION_UNITS, strict=True) + if n + ] + return " ".join(parts) + + +def _clock(start: str) -> tuple[str, str]: + """A trigger's start boundary as its date and its time of day (with its offset).""" + match = _BOUNDARY.match(start) + if not match: + return "", start + return match[1], match[2] + (match[3] or "") + + +def _every(count: Any, unit: str) -> str: + return f"{unit}ly" if count in (None, 0, 1) else f"every {count} {unit}s" + + +def _calendar(trigger: dict[str, Any], cls: str) -> str: + date, time = _clock(str(trigger.get("start") or "")) + at = f" at {time}" if time else "" + if cls == "MSFT_TaskDailyTrigger": + days = trigger.get("days_interval") + return ("daily" if days in (None, 0, 1) else f"every {days} days") + at + if cls == "MSFT_TaskWeeklyTrigger": + mask = int(trigger.get("days_of_week") or 0) + days = ",".join(d for i, d in enumerate(_WEEKDAYS) if mask & (1 << i)) + return f"{_every(trigger.get('weeks_interval'), 'week')} on {days}{at}" + if cls == "MSFT_TaskTimeTrigger": + return f"once at {date} {time}".rstrip() + return f"trigger{at}" + + +def _trigger(trigger: dict[str, Any]) -> str: + """One trigger as a short sentence: its kind, when, how it repeats.""" + cls = str(trigger.get("class") or "") + text = _EVENT_TRIGGERS.get(cls) or _calendar(trigger, cls) + if trigger.get("delay"): + text += f" after {_readable_duration(str(trigger['delay']))}" + if trigger.get("interval"): + text += f", every {_readable_duration(str(trigger['interval']))}" + if trigger.get("duration"): + text += f" for {_readable_duration(str(trigger['duration']))}" + if trigger.get("enabled") is False: + text += " (disabled)" + return text + + +def _action(action: dict[str, Any]) -> str: + if action.get("execute"): + return " ".join(str(p) for p in (action["execute"], action.get("arguments")) if p) + if action.get("class_id"): + return f"COM handler {action['class_id']}" + return str(action.get("class") or "") + + +class _Own(NamedTuple): + """What an application's task description and action say of the job.""" + + name: str + description: str + schedule: str | None + command: str | None + + +def _own(path: str, name: str, task: dict[str, Any]) -> _Own | None: + """The application's job this task is; None for any other task.""" + lines = str(task.get("description") or "").splitlines() + if path != _ROOT or not lines or not lines[0].startswith(JOB_MARKER): + return None + job_name, _, description = lines[0][len(JOB_MARKER) :].partition(" ") + if job_name != name or not _JOB_NAME.fullmatch(name): + return None + schedule = next( + (ln[len(SCHEDULE_LINE) :] for ln in lines[1:] if ln.startswith(SCHEDULE_LINE)), None + ) + actions = _as_list(task.get("actions")) + command = ( + own_command(actions[0].get("execute"), actions[0].get("arguments")) + if len(actions) == 1 + else None + ) + return _Own(name, description.strip(), schedule, command) + + +def _verbs(task: dict[str, Any], enabled: bool, own: bool) -> list[str]: + verbs = ["enable", "disable"] + if enabled and task.get("on_demand") is not False: + verbs.append("run") + return [*verbs, EDIT, DELETE] if own else verbs + + +class _Definition(NamedTuple): + """What a task's fields say it does, as the job shows it.""" + + schedule: str + schedule_kind: str + command: str + managed_by: str + description: str + + +def _definition(path: str, task: dict[str, Any], triggers: str, own: _Own | None) -> _Definition: + command = "\n".join(_action(a) for a in _as_list(task.get("actions"))) + if own is not None: + kind = "cron" if own.schedule else "triggers" + return _Definition( + own.schedule or triggers, kind, own.command or command, "application", own.description + ) + platform = path.lower().startswith("\\microsoft\\") + return _Definition( + triggers, + "triggers", + command, + "platform" if platform else "admin", + str(task.get("description") or "").strip(), + ) + + +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"))) + enabled = str(task.get("state") or "").lower() != "disabled" + own = _own(path, name, task) + found = _definition(path, task, triggers, own) + last_run = _timestamp(task.get("last_run")) + job: ScheduledJobDict = { + "key": f"task:{path}{name}", + "kind": "task", + "source": f"{path}{name}", + "run_as": str(task.get("user") or task.get("group") or ""), + "schedule": found.schedule, + "schedule_kind": found.schedule_kind, + "command": found.command, + "enabled": enabled, + "managed_by": found.managed_by, + "digest": "", + "actions": _verbs(task, enabled, own is not None), + "last_run": last_run, + "last_result": _last_result(task.get("last_result"), last_run), + "next_run": _timestamp(task.get("next_run")), + } + # An application's task shows its cron line; its triggers are what runs. + job["digest"] = job_digest(dict(job), content=triggers if own else "") + if own is not None: + job["name"] = own.name + if found.description: + job["description"] = found.description + return job + + +def parse_reading(output: str) -> tuple[list[ScheduledJobDict], str | None]: + """The jobs and the IANA time zone in what :data:`_PS_SCHEDULED_TASKS` printed. + + :raises ValueError: when the reading is cut short or holds fewer tasks than counted. + """ + raw = json.loads(output) + if not isinstance(raw, dict): + raise ValueError("not a scheduled-tasks reading") + tasks = _as_list(raw.get("tasks")) + count = int(raw.get("count") or 0) + if len(tasks) != count: + raise ValueError(f"the reading holds {len(tasks)} of {count} scheduled tasks") + return [_task_job(t) for t in tasks], iana_time_zone(raw.get("time_zone")) + + +def _path_and_name(source: str) -> tuple[str, str]: + path, _, name = source.rpartition("\\") + return path + "\\", name + + +# --------------------------------------------------------------------------- +# The mixin +# --------------------------------------------------------------------------- + + +class WindowsScheduledJobsMixin(ScheduledJobsMixin): + """The Task Scheduler as scheduled jobs; the driver carries the scripts.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_raw(self, script: str) -> str: ... + + def _sj_read(self) -> tuple[list[ScheduledJobDict], str | None]: + return parse_reading(self._run_raw(_PS_SCHEDULED_TASKS)) + + def get_scheduled_jobs(self) -> ScheduledJobsReadingDict: + """Every task of the host, in one round trip. + + :raises ValueError: when the reading came back cut short. + """ + jobs, time_zone = self._sj_read() + return {"jobs": jobs, "time_zone": time_zone} + + def _sj_job(self, key: str, digest: str) -> ScheduledJobDict: + jobs, _ = self._sj_read() + job = next((j for j in jobs if j["key"] == key), None) + if job is None: + raise LookupError(f"no scheduled job {key}") + if job["digest"] != digest: + raise ScheduledJobChanged(f"{key} changed on the host since it was read") + return job + + def _sj_send(self, script: str, done: str) -> ScheduledJobResultDict: + try: + self._run_raw(script) + except PowerShellError as exc: + return {"success": False, "output": str(exc)} + return {"success": True, "output": done} + + def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict: + """Enable, disable or start the task *key*; see :class:`ScheduledJobsMixin`.""" + if action not in ACTIONS: + raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}") + job = self._sj_job(key, digest) + if action not in job["actions"]: + raise ScheduledJobRefused( + f"{key} cannot be told to {action}: it is disabled or " + "does not allow a start on demand" + ) + cmdlet, done = _CMDLETS[action] + path, name = _path_and_name(job["source"]) + script = _PS_TASK_CMDLET.format(path=_ps_quote(path), name=_ps_quote(name), cmdlet=cmdlet) + return self._sj_send(script, f"{key} {done}") + + def _sj_own(self, spec: ScheduledJobSpecDict, digest: str | None) -> ScheduledJobDict | None: + key = f"task:{_ROOT}{spec['name']}" + jobs, _ = self._sj_read() + # Task names are case-insensitive: Register -Force would replace "\Name" too. + current = next((j for j in jobs if j["key"].lower() == key), None) + if digest is None: + if current is not None: + raise ScheduledJobChanged(f"a task {current['source']} is there already") + return None + if current is None: + raise LookupError(f"no scheduled job {key}") + if current["managed_by"] != "application": + raise ScheduledJobRefused(f"{current['key']} was not written by an application") + if current["digest"] != digest: + raise ScheduledJobChanged(f"{key} changed on the host since it was read") + return current + + def put_scheduled_job( + self, spec: ScheduledJobSpecDict, *, digest: str | None = None + ) -> ScheduledJobResultDict: + """Register or change the application's own task; see :class:`ScheduledJobsMixin`.""" + check_spec(spec) + xml = task_xml(spec) + current = self._sj_own(spec, digest) + script = _PS_REGISTER.format( + path=_ps_quote(_ROOT), name=_ps_quote(spec["name"]), xml=_ps_quote(xml) + ) + verb = "changed" if current else "created" + return self._sj_send(script, f"task:{_ROOT}{spec['name']} {verb}") + + def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict: + """Unregister the application's task *key*; see :class:`ScheduledJobsMixin`.""" + job = self._sj_job(key, digest) + if job["managed_by"] != "application": + raise ScheduledJobRefused( + f"{key} was not written by an application; it is only switched" + ) + path, name = _path_and_name(job["source"]) + script = _PS_UNREGISTER.format(path=_ps_quote(path), name=_ps_quote(name)) + return self._sj_send(script, f"{key} deleted") diff --git a/napalm_windows/task_xml.py b/napalm_windows/task_xml.py new file mode 100644 index 0000000..14b2361 --- /dev/null +++ b/napalm_windows/task_xml.py @@ -0,0 +1,249 @@ +"""An application's scheduled job as Task Scheduler XML (#8). Pure: no I/O. + +:meth:`~napalm_windows.scheduled_tasks.WindowsScheduledJobsMixin.put_scheduled_job` +registers the task this module writes, in the root folder ``\\``, named by the job. + +**The cron expression becomes triggers, exactly or not at all.** A day schedule is +one of Task Scheduler's: every day (``ScheduleByDay``), weekdays +(``ScheduleByWeek``), or days of the month in some months (``ScheduleByMonth``). +The times of day become one trigger at the first time with a repetition when they +are three or more evenly spaced (``*/5``, ``*/15 8-17``, ``0 */6``), else one trigger per time, +else one repeating trigger per hour when the minutes are evenly spaced (``*/7``) -- +at most 48 triggers, Task Scheduler's limit. ``@reboot`` is a boot trigger. What +Task Scheduler cannot say is refused, naming why: cron's *either* rule (both day +fields set), a weekday together with days of the month or with months, and times +that need more than 48 triggers. A trigger's start is a local time without an +offset, so it follows the host's clock as cron does; a repetition counts elapsed +time, so on the day summer time starts or ends its later runs shift by the hour. + +**The command runs in ``cmd.exe``**: ``cmd.exe /d /s /c ""`` -- ``/d`` +skips AutoRun, ``/s`` keeps the command as it is between the outer quotes. One line, +as a command line is; the reading gives it back as it was written. + +**The principal** is ``SYSTEM`` (the local system account) or a local user, who +runs it whether logged on or not without a stored password (``S4U``): such a run +has no network credentials, so a share needs the computer's access. + +**The description** is ``napalm-scheduled-job: `` and a second +line ``schedule: ``: the job's name, and its schedule as the +application gave it. +""" + +from __future__ import annotations + +import html +from itertools import pairwise + +from napalm_device_types import ScheduledJobRefused, ScheduledJobSpecDict +from napalm_device_types.cron import CronSchedule, is_reboot, parse_cron + +#: The first line of an application's task description, before its name. +JOB_MARKER = "napalm-scheduled-job: " +#: The line of an application's task description that holds its cron expression. +SCHEDULE_LINE = "schedule: " + +CMD = "%SystemRoot%\\System32\\cmd.exe" +_CMD_PREFIX = '/d /s /c "' + +#: Task Scheduler's limit of triggers on one task. +MAX_TRIGGERS = 48 +_START_DATE = "2020-01-01" +_SYSTEM_SID = "S-1-5-18" +_NAMESPACE = "http://schemas.microsoft.com/windows/2004/02/mit/task" + +_WEEKDAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") +_MONTHS = ( + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +) +_ALL_DAYS = frozenset(range(1, 32)) +_ALL_MONTHS = frozenset(range(1, 13)) +_ALL_WEEKDAYS = frozenset(range(7)) + +#: (minute of the day it starts, repetition interval, repetition duration) in minutes. +_Clock = tuple[int, int | None, int | None] + + +# -- the command --------------------------------------------------------------------------------- + + +def _escape(text: str) -> str: + """*text* as XML character data.""" + return html.escape(text, quote=False) + + +def _check_text(what: str, text: str) -> None: + if "\n" in text or "\r" in text: + raise ScheduledJobRefused(f"a task's {what} is one line") + if any(ord(c) < 32 and c != "\t" for c in text): + raise ScheduledJobRefused(f"a task's {what} cannot hold a control character") + + +def command_action(command: str) -> tuple[str, str]: + """The ``Exec`` action's command and arguments that run *command* in ``cmd.exe``.""" + command = command.strip() + _check_text("command", command) + return CMD, f'{_CMD_PREFIX}{command}"' + + +def own_command(execute: str | None, arguments: str | None) -> str | None: + """The command :func:`command_action` wrapped; None for any other action.""" + args = arguments or "" + if (execute or "").lower() != CMD.lower(): + return None + if not (args.startswith(_CMD_PREFIX) and args.endswith('"') and len(args) > len(_CMD_PREFIX)): + return None + return args[len(_CMD_PREFIX) : -1] + + +def description(spec: ScheduledJobSpecDict) -> str: + """The task's description: the job's name and description, then its cron expression.""" + first = f"{JOB_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip() + return f"{first}\n{SCHEDULE_LINE}{spec['schedule'].strip()}" + + +# -- the schedule -------------------------------------------------------------------------------- + + +def _evenly_spaced(values: list[int]) -> int | None: + """The step between *values*, two or more; None when they are not evenly spaced.""" + if len(values) < 2: + return None + step = values[1] - values[0] + return step if all(b - a == step for a, b in pairwise(values)) else None + + +def _clocks(s: CronSchedule) -> list[_Clock]: + times = sorted(h * 60 + m for h in s.hours for m in s.minutes) + step = _evenly_spaced(times) + if step is not None and len(times) > 2: + return [(times[0], step, times[-1] - times[0] + 1)] + if len(times) <= MAX_TRIGGERS: + return [(t, None, None) for t in times] + minutes = sorted(s.minutes) + step = _evenly_spaced(minutes) + if step is not None and len(s.hours) <= MAX_TRIGGERS: + span = minutes[-1] - minutes[0] + 1 + return [(h * 60 + minutes[0], step, span) for h in sorted(s.hours)] + raise ScheduledJobRefused( + f"these times of day need more than {MAX_TRIGGERS} triggers, Task Scheduler's limit" + ) + + +def _names(names: tuple[str, ...], values: frozenset[int], first: int) -> str: + return "".join(f"<{names[v - first]} />" for v in sorted(values)) + + +def _day_schedule(s: CronSchedule) -> str: + if s.either_day: + raise ScheduledJobRefused( + "Task Scheduler cannot fire on either a day of the month or a weekday, " + "as cron does when both are set" + ) + every_date = s.days == _ALL_DAYS and s.months == _ALL_MONTHS + if s.weekdays == _ALL_WEEKDAYS and every_date: + return "1" + if every_date: + days = _names(_WEEKDAYS, s.weekdays, 0) + return ( + f"{days}" + "1" + ) + if s.weekdays == _ALL_WEEKDAYS: + days = "".join(f"{d}" for d in sorted(s.days)) + months = _names(_MONTHS, s.months, 1) + return ( + f"{days}" + f"{months}" + ) + raise ScheduledJobRefused( + "Task Scheduler cannot combine a weekday with days of the month or with months" + ) + + +def _duration(minutes: int) -> str: + hours, rest = divmod(minutes, 60) + return "PT" + (f"{hours}H" if hours else "") + (f"{rest}M" if rest or not hours else "") + + +def _calendar_trigger(clock: _Clock, day_schedule: str) -> str: + start, interval, duration = clock + repetition = "" + if interval is not None and duration is not None: + repetition = ( + f"{_duration(interval)}" + f"{_duration(duration)}" + "false" + ) + hour, minute = divmod(start, 60) + return ( + f"{repetition}" + f"{_START_DATE}T{hour:02d}:{minute:02d}:00" + f"true{day_schedule}" + ) + + +def triggers(schedule: str) -> list[str]: + """The triggers that fire exactly when the cron expression *schedule* does. + + :raises ScheduledJobRefused: for a shape Task Scheduler cannot express, or an + expression cron would not take. + """ + if is_reboot(schedule): + return ["true"] + try: + s = parse_cron(schedule) + except ValueError as exc: + raise ScheduledJobRefused(str(exc)) from exc + day_schedule = _day_schedule(s) + return [_calendar_trigger(clock, day_schedule) for clock in _clocks(s)] + + +# -- the task ------------------------------------------------------------------------------------ + + +def _principal(run_as: str) -> str: + if run_as.upper() == "SYSTEM": + return f"{_SYSTEM_SID}HighestAvailable" + return ( + f"{_escape(run_as)}S4U" + "LeastPrivilege" + ) + + +def task_xml(spec: ScheduledJobSpecDict) -> str: + """The whole task for *spec*, as ``Register-ScheduledTask -Xml`` takes it. + + :raises ScheduledJobRefused: for a schedule, command or description a task + cannot hold. + """ + execute, arguments = command_action(spec["command"]) + _check_text("description", spec.get("description") or "") + trigger_xml = "".join(triggers(spec["schedule"])) + enabled = "true" if spec["enabled"] else "false" + return ( + f'' + f"{_escape(description(spec))}" + "" + f"{trigger_xml}" + f'{_principal(spec["run_as"])}' + "IgnoreNew" + "false" + "false" + "false" + "true" + f"{enabled}" + f'{_escape(execute)}' + f"{_escape(arguments)}" + "" + ) diff --git a/napalm_windows/time_zones.py b/napalm_windows/time_zones.py new file mode 100644 index 0000000..4834279 --- /dev/null +++ b/napalm_windows/time_zones.py @@ -0,0 +1,115 @@ +"""Windows time zone ids as IANA names, for the scheduled-jobs reading (#8). + +Windows names its zones by their standard-time name (``W. Europe Standard Time``); +the contract wants an IANA name. The table holds the common zones, each mapped to +the zone CLDR names for its territory ``001`` (``windowsZones.xml``); a zone not in +it is ``None`` -- the reading says it does not know rather than guess. +""" + +from __future__ import annotations + +WINDOWS_TO_IANA: dict[str, str] = { + # UTC and fixed offsets + "UTC": "Etc/UTC", + "Dateline Standard Time": "Etc/GMT+12", + "UTC-11": "Etc/GMT+11", + "UTC-09": "Etc/GMT+9", + "UTC-08": "Etc/GMT+8", + "UTC-02": "Etc/GMT+2", + "UTC+12": "Etc/GMT-12", + "UTC+13": "Etc/GMT-13", + # Europe + "GMT Standard Time": "Europe/London", + "Greenwich Standard Time": "Atlantic/Reykjavik", + "W. Europe Standard Time": "Europe/Berlin", + "Central Europe Standard Time": "Europe/Budapest", + "Romance Standard Time": "Europe/Paris", + "Central European Standard Time": "Europe/Warsaw", + "GTB Standard Time": "Europe/Bucharest", + "E. Europe Standard Time": "Europe/Chisinau", + "FLE Standard Time": "Europe/Kyiv", + "Turkey Standard Time": "Europe/Istanbul", + "Kaliningrad Standard Time": "Europe/Kaliningrad", + "Russian Standard Time": "Europe/Moscow", + "Belarus Standard Time": "Europe/Minsk", + "Azores Standard Time": "Atlantic/Azores", + "Cape Verde Standard Time": "Atlantic/Cape_Verde", + # Africa and the Middle East + "Morocco Standard Time": "Africa/Casablanca", + "W. Central Africa Standard Time": "Africa/Lagos", + "Egypt Standard Time": "Africa/Cairo", + "South Africa Standard Time": "Africa/Johannesburg", + "E. Africa Standard Time": "Africa/Nairobi", + "Namibia Standard Time": "Africa/Windhoek", + "Israel Standard Time": "Asia/Jerusalem", + "Jordan Standard Time": "Asia/Amman", + "Middle East Standard Time": "Asia/Beirut", + "Arabic Standard Time": "Asia/Baghdad", + "Arab Standard Time": "Asia/Riyadh", + "Iran Standard Time": "Asia/Tehran", + "Arabian Standard Time": "Asia/Dubai", + # Asia and the Pacific + "Georgian Standard Time": "Asia/Tbilisi", + "Azerbaijan Standard Time": "Asia/Baku", + "Caucasus Standard Time": "Asia/Yerevan", + "Afghanistan Standard Time": "Asia/Kabul", + "Pakistan Standard Time": "Asia/Karachi", + "West Asia Standard Time": "Asia/Tashkent", + "Ekaterinburg Standard Time": "Asia/Yekaterinburg", + "India Standard Time": "Asia/Kolkata", + "Sri Lanka Standard Time": "Asia/Colombo", + "Nepal Standard Time": "Asia/Kathmandu", + "Bangladesh Standard Time": "Asia/Dhaka", + "Myanmar Standard Time": "Asia/Yangon", + "SE Asia Standard Time": "Asia/Bangkok", + "N. Central Asia Standard Time": "Asia/Novosibirsk", + "North Asia Standard Time": "Asia/Krasnoyarsk", + "China Standard Time": "Asia/Shanghai", + "Singapore Standard Time": "Asia/Singapore", + "Taipei Standard Time": "Asia/Taipei", + "W. Australia Standard Time": "Australia/Perth", + "Tokyo Standard Time": "Asia/Tokyo", + "Korea Standard Time": "Asia/Seoul", + "Cen. Australia Standard Time": "Australia/Adelaide", + "AUS Central Standard Time": "Australia/Darwin", + "E. Australia Standard Time": "Australia/Brisbane", + "AUS Eastern Standard Time": "Australia/Sydney", + "Tasmania Standard Time": "Australia/Hobart", + "Vladivostok Standard Time": "Asia/Vladivostok", + "New Zealand Standard Time": "Pacific/Auckland", + "Fiji Standard Time": "Pacific/Fiji", + "Tonga Standard Time": "Pacific/Tongatapu", + "Samoa Standard Time": "Pacific/Apia", + # The Americas + "Hawaiian Standard Time": "Pacific/Honolulu", + "Aleutian Standard Time": "America/Adak", + "Alaskan Standard Time": "America/Anchorage", + "Pacific Standard Time": "America/Los_Angeles", + "Pacific Standard Time (Mexico)": "America/Tijuana", + "US Mountain Standard Time": "America/Phoenix", + "Mountain Standard Time": "America/Denver", + "Central America Standard Time": "America/Guatemala", + "Central Standard Time": "America/Chicago", + "Central Standard Time (Mexico)": "America/Mexico_City", + "Canada Central Standard Time": "America/Regina", + "SA Pacific Standard Time": "America/Bogota", + "Eastern Standard Time": "America/New_York", + "US Eastern Standard Time": "America/Indiana/Indianapolis", + "Cuba Standard Time": "America/Havana", + "Venezuela Standard Time": "America/Caracas", + "Atlantic Standard Time": "America/Halifax", + "SA Western Standard Time": "America/La_Paz", + "Pacific SA Standard Time": "America/Santiago", + "Paraguay Standard Time": "America/Asuncion", + "Newfoundland Standard Time": "America/St_Johns", + "E. South America Standard Time": "America/Sao_Paulo", + "Argentina Standard Time": "America/Argentina/Buenos_Aires", + "SA Eastern Standard Time": "America/Cayenne", + "Montevideo Standard Time": "America/Montevideo", + "Greenland Standard Time": "America/Nuuk", +} + + +def iana_time_zone(windows_id: str | None) -> str | None: + """The IANA name of the Windows zone *windows_id*; None for one the table lacks.""" + return WINDOWS_TO_IANA.get(windows_id or "") diff --git a/napalm_windows/windows.py b/napalm_windows/windows.py index eefae4f..6e09783 100644 --- a/napalm_windows/windows.py +++ b/napalm_windows/windows.py @@ -26,6 +26,8 @@ from napalm.base.exceptions import ConnectionClosedException 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.scheduled_tasks import WindowsScheduledJobsMixin from napalm_windows.transport import PowerShellError, PsrpTransport logger = logging.getLogger(__name__) @@ -182,9 +184,6 @@ _SERVICE_COMMANDS = { # real services use (MSSQL$SQLEXPRESS, CDPUserSvc_4a5b6, {GUID}-style names). _SERVICE_NAME_RE = re.compile(r"^[\w.$@{}\-]+$", re.ASCII) -# PowerShell accepts these as single-quote delimiters alongside the ASCII one. -_PS_SINGLE_QUOTES = ("'", "‘", "’", "‚", "‛") - _ROUTE_PROTOCOLS = { "local": "connected", "routeradvertisement": "connected", @@ -204,22 +203,6 @@ _DEAD_NEIGHBOUR_STATES = {"unreachable", "incomplete"} # --------------------------------------------------------------------------- -def _as_list(value: Any) -> list[Any]: - """Undo ConvertTo-Json unwrapping a one-element array into a bare value.""" - if value is None: - return [] - if isinstance(value, list): - return value - return [value] - - -def _ps_quote(value: str) -> str: - """Quote ``value`` as a PowerShell single-quoted (verbatim) string.""" - for q in _PS_SINGLE_QUOTES: - value = value.replace(q, q + q) - return f"'{value}'" - - def _mac(value: str | None) -> str: """``00-15-5d-01-02-03`` → ``00:15:5D:01:02:03``.""" if not value: @@ -271,7 +254,7 @@ def _is_noise_route(destination: str) -> bool: # --------------------------------------------------------------------------- -class WindowsDriver(OSDriver): +class WindowsDriver(WindowsScheduledJobsMixin, OSDriver): """NAPALM driver for Windows Server 2016+ and Windows 10/11. ``optional_args``: diff --git a/pyproject.toml b/pyproject.toml index b387fb1..8acbea1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.21.1", + "napalm-device-types>=4.26.0", # ScheduledJobsMixin "pypsrp>=0.8", ] diff --git a/tests/fixtures/synthetic/scheduled_tasks.json b/tests/fixtures/synthetic/scheduled_tasks.json new file mode 100644 index 0000000..ea04caa --- /dev/null +++ b/tests/fixtures/synthetic/scheduled_tasks.json @@ -0,0 +1,100 @@ +{ + "time_zone": "W. Europe Standard Time", + "count": 5, + "tasks": [ + { + "path": "\\Microsoft\\Windows\\Defrag\\", + "name": "ScheduledDefrag", + "state": "Ready", + "user": "SYSTEM", + "group": null, + "on_demand": true, + "description": "This task optimizes local storage drives.", + "actions": [ + {"class": "MSFT_TaskExecAction", "execute": "%windir%\\system32\\defrag.exe", "arguments": "-c -h -o -$", "class_id": null} + ], + "triggers": [ + {"class": "MSFT_TaskWeeklyTrigger", "enabled": true, "start": "2026-01-01T01:00:00", "days_interval": null, "weeks_interval": 1, "days_of_week": 1, "interval": "", "duration": "", "delay": ""} + ], + "last_run": "2026-11-01T00:00:12.0000000Z", + "last_result": 0, + "next_run": "2026-11-08T00:00:00.0000000Z" + }, + { + "path": "\\Microsoft\\Windows\\UpdateOrchestrator\\", + "name": "Reboot", + "state": "Disabled", + "user": "SYSTEM", + "group": null, + "on_demand": true, + "description": null, + "actions": [ + {"class": "MSFT_TaskExecAction", "execute": "%systemroot%\\system32\\MusNotification.exe", "arguments": "RebootDialog", "class_id": null} + ], + "triggers": [ + {"class": "MSFT_TaskTimeTrigger", "enabled": true, "start": "2026-11-04T03:00:00+01:00", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""} + ], + "last_run": "1999-11-29T23:00:00.0000000Z", + "last_result": 267011, + "next_run": null + }, + { + "path": "\\", + "name": "Admin's backup", + "state": "Ready", + "user": "Administrator", + "group": null, + "on_demand": true, + "description": "Copies D:\\data to the NAS", + "actions": [ + {"class": "MSFT_TaskExecAction", "execute": "robocopy.exe", "arguments": "D:\\data \\\\nas\\backup /MIR", "class_id": null}, + {"class": "MSFT_TaskExecAction", "execute": "C:\\scripts\\notify.cmd", "arguments": null, "class_id": null} + ], + "triggers": [ + {"class": "MSFT_TaskDailyTrigger", "enabled": true, "start": "2026-01-01T00:00:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "PT1H", "duration": "P1D", "delay": ""}, + {"class": "MSFT_TaskDailyTrigger", "enabled": false, "start": "2026-01-01T12:30:00", "days_interval": 2, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""} + ], + "last_run": "/Date(1793854800000)/", + "last_result": 2147942402, + "next_run": "/Date(1793858400000)/" + }, + { + "path": "\\", + "name": "nightly-dump", + "state": "Ready", + "user": "backup", + "group": null, + "on_demand": true, + "description": "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *", + "actions": [ + {"class": "MSFT_TaskExecAction", "execute": "%SystemRoot%\\System32\\cmd.exe", "arguments": "/d /s /c \"pg_dump -f D:\\dump.sql app\"", "class_id": null} + ], + "triggers": [ + {"class": "MSFT_TaskTrigger", "enabled": true, "start": "2020-01-01T02:30:00", "days_interval": 1, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""} + ], + "last_run": "2026-11-03T01:30:04.1234567Z", + "last_result": 1, + "next_run": "2026-11-04T01:30:00Z" + }, + { + "path": "\\Vendor\\", + "name": "Updater", + "state": "Running", + "user": null, + "group": "Users", + "on_demand": false, + "description": "", + "actions": [ + {"class": "MSFT_TaskComHandlerAction", "execute": null, "arguments": null, "class_id": "{A6BA00FE-40E8-477C-B713-C64A14F18ADB}"} + ], + "triggers": [ + {"class": "MSFT_TaskLogonTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": "PT15M"}, + {"class": "MSFT_TaskBootTrigger", "enabled": null, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""}, + {"class": "MSFT_TaskSessionStateChangeTrigger", "enabled": true, "start": "", "days_interval": null, "weeks_interval": null, "days_of_week": null, "interval": "", "duration": "", "delay": ""} + ], + "last_run": "2026-11-03T06:00:00Z", + "last_result": 267009, + "next_run": null + } + ] +} diff --git a/tests/test_scheduled_jobs.py b/tests/test_scheduled_jobs.py new file mode 100644 index 0000000..eb564ac --- /dev/null +++ b/tests/test_scheduled_jobs.py @@ -0,0 +1,639 @@ +"""Scheduled jobs on Windows: the Task Scheduler over PowerShell Remoting (#8). + +The reading is one script whose JSON a fake transport answers from +tests/fixtures/synthetic/scheduled_tasks.json; every write is one script, read +here as text. What a real host does with those scripts the fixtures cannot +prove -- see the README there. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest +from napalm_device_types import ( + ScheduledJobChanged, + ScheduledJobRefused, + ScheduledJobsMixin, + job_digest, +) + +from napalm_windows import WindowsDriver, task_xml +from napalm_windows import scheduled_tasks as mod +from napalm_windows.time_zones import iana_time_zone +from napalm_windows.transport import PowerShellError + +FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "scheduled_tasks.json" + +DEFRAG = "task:\\Microsoft\\Windows\\Defrag\\ScheduledDefrag" +REBOOT = "task:\\Microsoft\\Windows\\UpdateOrchestrator\\Reboot" +BACKUP = "task:\\Admin's backup" +DUMP = "task:\\nightly-dump" +UPDATER = "task:\\Vendor\\Updater" + + +def _reading() -> dict[str, Any]: + return json.loads(FIXTURE.read_text()) + + +class FakeTransport: + """Answers the reading script with *reading*; records every other script.""" + + def __init__(self, reading: Any, fail: str | None = None): + self.reading = reading + self.fail = fail + self.sent: list[str] = [] + self.is_open = True + + def run(self, script: str) -> str: + self.sent.append(script) + if script == mod._PS_SCHEDULED_TASKS: + return self.reading if isinstance(self.reading, str) else json.dumps(self.reading) + if self.fail: + raise PowerShellError(self.fail) + return "" + + def close(self) -> None: + self.is_open = False + + @property + def writes(self) -> list[str]: + return [s for s in self.sent if s != mod._PS_SCHEDULED_TASKS] + + +def _driver(reading: Any = None, fail: str | None = None) -> WindowsDriver: + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(_reading() if reading is None else reading, fail) # type: ignore[assignment] + return d + + +def _jobs(reading: Any = None) -> dict[str, dict[str, Any]]: + return {j["key"]: dict(j) for j in _driver(reading).get_scheduled_jobs()["jobs"]} + + +def _digest(key: str, reading: Any = None) -> str: + return str(_jobs(reading)[key]["digest"]) + + +def _spec(**changes: Any) -> dict[str, Any]: + spec = { + "name": "nightly-dump", + "schedule": "30 2 * * *", + "run_as": "backup", + "command": "pg_dump -f D:\\dump.sql app", + "enabled": True, + "description": "Dump the database", + } + spec.update(changes) + return spec + + +def _without_dump() -> dict[str, Any]: + reading = _reading() + reading["tasks"] = [t for t in reading["tasks"] if t["name"] != "nightly-dump"] + reading["count"] = len(reading["tasks"]) + return reading + + +# --------------------------------------------------------------------------- +# The contract +# --------------------------------------------------------------------------- + + +def test_a_windows_host_offers_every_verb(): + assert issubclass(WindowsDriver, ScheduledJobsMixin) + for verb in ( + "get_scheduled_jobs", + "manage_scheduled_job", + "put_scheduled_job", + "delete_scheduled_job", + ): + assert callable(getattr(WindowsDriver, verb)) + + +# --------------------------------------------------------------------------- +# Reading +# --------------------------------------------------------------------------- + + +class TestReading: + def test_every_task_in_one_round_trip(self): + d = _driver() + + reading = d.get_scheduled_jobs() + + assert len(reading["jobs"]) == 5 + assert d._transport.sent == [mod._PS_SCHEDULED_TASKS] + + def test_the_script_joins_the_task_and_its_run_info_and_changes_nothing(self): + script = mod._PS_SCHEDULED_TASKS + assert "Get-ScheduledTask" in script + assert "Get-ScheduledTaskInfo" in script + assert "ConvertTo-Json" in script + for verb in ("Set-", "Register-", "Unregister-", "Enable-", "Disable-", "Start-"): + assert verb not in script + + def test_a_platform_task(self): + job = _jobs()[DEFRAG] + + assert {k: job[k] for k in job if k != "digest"} == { + "key": DEFRAG, + "kind": "task", + "source": "\\Microsoft\\Windows\\Defrag\\ScheduledDefrag", + "run_as": "SYSTEM", + "schedule": "weekly on Sun at 01:00", + "schedule_kind": "triggers", + "command": "%windir%\\system32\\defrag.exe -c -h -o -$", + "enabled": True, + "managed_by": "platform", + "actions": ["enable", "disable", "run"], + "description": "This task optimizes local storage drives.", + "last_run": "2026-11-01T00:00:12+00:00", + "last_result": "success", + "next_run": "2026-11-08T00:00:00+00:00", + } + + def test_the_digest_is_the_contracts(self): + job = _jobs()[DEFRAG] + + assert job["digest"] == job_digest(job) + + def test_a_disabled_task_is_not_enabled_and_cannot_be_run(self): + job = _jobs()[REBOOT] + + assert job["enabled"] is False + assert job["actions"] == ["enable", "disable"] + + def test_a_task_that_never_ran_has_no_last_run_or_result(self): + """Task Scheduler says 30 November 1999 for never, and 0x41303 for its result.""" + job = _jobs()[REBOOT] + + assert (job["last_run"], job["last_result"], job["next_run"]) == (None, None, None) + + def test_a_task_without_a_description_has_none(self): + assert "description" not in _jobs()[REBOOT] + + def test_a_once_trigger_keeps_its_offset(self): + assert _jobs()[REBOOT]["schedule"] == "once at 2026-11-04 03:00+01:00" + + def test_an_admins_task_with_two_actions_and_two_triggers(self): + job = _jobs()[BACKUP] + + assert job["managed_by"] == "admin" + assert job["run_as"] == "Administrator" + assert ( + job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR\nC:\\scripts\\notify.cmd" + ) + assert job["schedule"] == ( + "daily at 00:00, every 1 hour for 1 day; every 2 days at 12:30 (disabled)" + ) + assert job["actions"] == ["enable", "disable", "run"] + + def test_json_dates_are_iso_utc(self): + job = _jobs()[BACKUP] + + assert job["last_run"] == "2026-11-05T05:00:00+00:00" + assert job["next_run"] == "2026-11-05T06:00:00+00:00" + + def test_a_failure_code_is_hex(self): + assert _jobs()[BACKUP]["last_result"] == "0x80070002" + + def test_an_applications_task(self): + job = _jobs()[DUMP] + + assert job["managed_by"] == "application" + assert job["name"] == "nightly-dump" + assert job["description"] == "Dump the database" + assert (job["schedule"], job["schedule_kind"]) == ("30 2 * * *", "cron") + assert job["command"] == "pg_dump -f D:\\dump.sql app" + assert job["run_as"] == "backup" + assert job["actions"] == ["enable", "disable", "run", "edit", "delete"] + assert job["last_result"] == "0x1" + assert job["last_run"] == "2026-11-03T01:30:04.123456+00:00" + + def test_an_applications_digest_covers_its_triggers(self): + """Triggers changed by hand change the digest, although the cron line stays.""" + changed = _reading() + changed["tasks"][3]["triggers"][0]["start"] = "2020-01-01T03:30:00" + + assert _digest(DUMP, changed) != _digest(DUMP) + assert _jobs(changed)[DUMP]["schedule"] == "30 2 * * *" + + def test_an_application_task_without_its_schedule_line_shows_its_triggers(self): + reading = _reading() + reading["tasks"][3]["description"] = "napalm-scheduled-job: nightly-dump" + job = _jobs(reading)[DUMP] + + assert (job["managed_by"], job["name"]) == ("application", "nightly-dump") + assert "description" not in job + assert (job["schedule"], job["schedule_kind"]) == ("trigger at 02:30", "triggers") + + def test_an_application_task_whose_action_was_changed_shows_it(self): + reading = _reading() + reading["tasks"][3]["actions"][0]["arguments"] = "/c whoami" + + assert _jobs(reading)[DUMP]["command"] == "%SystemRoot%\\System32\\cmd.exe /c whoami" + + @pytest.mark.parametrize( + ("path", "name"), + [("\\Vendor\\", "nightly-dump"), ("\\", "other-name"), ("\\", "Nightly Dump")], + ) + def test_the_marker_counts_only_on_the_root_task_of_that_name(self, path, name): + reading = _reading() + reading["tasks"][3].update(path=path, name=name) + + job = _jobs(reading)[f"task:{path}{name}"] + + assert job["managed_by"] == "admin" + assert "edit" not in job["actions"] + assert "name" not in job + + def test_a_group_principal_a_com_handler_and_event_triggers(self): + job = _jobs()[UPDATER] + + assert job["run_as"] == "Users" + assert job["command"] == "COM handler {A6BA00FE-40E8-477C-B713-C64A14F18ADB}" + assert job["schedule"] == "at logon after 15 minutes; at startup; session state change" + assert job["enabled"] is True + assert job["last_result"] == "running" + + def test_a_task_that_cannot_be_started_on_demand_does_not_offer_run(self): + assert _jobs()[UPDATER]["actions"] == ["enable", "disable"] + + def test_the_time_zone_is_iana(self): + assert _driver().get_scheduled_jobs()["time_zone"] == "Europe/Berlin" + + def test_an_unknown_time_zone_is_none(self): + reading = _reading() + reading["time_zone"] = "Mars Standard Time" + + assert _driver(reading).get_scheduled_jobs()["time_zone"] is None + + def test_one_task_arrives_as_a_bare_object(self): + """ConvertTo-Json unwraps a one-element array, nested ones too.""" + task = _reading()["tasks"][2] + task["actions"] = task["actions"][0] + task["triggers"] = task["triggers"][0] + reading = {"time_zone": "UTC", "count": 1, "tasks": task} + + (job,) = _driver(reading).get_scheduled_jobs()["jobs"] + + assert job["key"] == BACKUP + assert job["command"] == "robocopy.exe D:\\data \\\\nas\\backup /MIR" + assert job["schedule"] == "daily at 00:00, every 1 hour for 1 day" + + def test_a_host_without_tasks(self): + reading = {"time_zone": None, "count": 0, "tasks": None} + + assert _driver(reading).get_scheduled_jobs() == {"jobs": [], "time_zone": None} + + def test_a_reading_cut_short_raises(self): + with pytest.raises(ValueError): + _driver(json.dumps(_reading())[:-40]).get_scheduled_jobs() + + def test_a_reading_with_fewer_tasks_than_counted_raises(self): + reading = _reading() + reading["count"] = 6 + + with pytest.raises(ValueError, match="6"): + _driver(reading).get_scheduled_jobs() + + def test_an_empty_answer_raises(self): + with pytest.raises(ValueError): + _driver("").get_scheduled_jobs() + + def test_a_failed_reading_raises(self): + d = WindowsDriver("win01", "admin", "secret") + d._transport = FakeTransport(_reading()) # type: ignore[assignment] + d._transport.reading = None + d._transport.run = lambda script: (_ for _ in ()).throw(PowerShellError("Access denied")) # type: ignore[method-assign] + + with pytest.raises(PowerShellError): + d.get_scheduled_jobs() + + +class TestOddTasks: + def _job(self, **changes: Any) -> dict[str, Any]: + task = _reading()["tasks"][0] + task.update(changes) + return _jobs({"time_zone": None, "count": 1, "tasks": [task]})[DEFRAG] + + def test_an_action_without_a_command_or_handler_names_its_class(self): + job = self._job(actions=[{"class": "MSFT_TaskSendEmailAction"}]) + + assert job["command"] == "MSFT_TaskSendEmailAction" + + def test_a_start_and_delay_it_cannot_read_are_kept_as_they_are(self): + trigger = {"class": "MSFT_TaskDailyTrigger", "start": "soon", "delay": "a while"} + + assert self._job(triggers=[trigger])["schedule"] == "daily at soon after a while" + + def test_a_task_that_never_ran_since_it_was_read_has_no_result(self): + job = self._job(last_result=267011) + + assert job["last_run"] is not None + assert job["last_result"] is None + + def test_a_negative_result_is_the_same_code(self): + assert self._job(last_result=-2147024894)["last_result"] == "0x80070002" + + def test_a_reading_that_is_not_an_object_raises(self): + with pytest.raises(ValueError, match="reading"): + _driver("[]").get_scheduled_jobs() + + +class TestTimestamps: + @pytest.mark.parametrize( + ("value", "iso"), + [ + (None, None), + ("", None), + ("2026-11-03T01:30:00Z", "2026-11-03T01:30:00+00:00"), + ("2026-11-03T02:30:00+01:00", "2026-11-03T01:30:00+00:00"), + ("2026-11-03T01:30:00", "2026-11-03T01:30:00+00:00"), + ("/Date(1793854800000)/", "2026-11-05T05:00:00+00:00"), + ("/Date(1793854800000+0100)/", "2026-11-05T05:00:00+00:00"), + (1793854800, "2026-11-05T05:00:00+00:00"), + ("1999-11-30T00:00:00", None), + ("/Date(943916400000)/", None), + ("not a date", None), + ], + ) + def test_to_iso_utc(self, value, iso): + assert mod._timestamp(value) == iso + + +class TestTimeZones: + @pytest.mark.parametrize( + ("windows", "iana"), + [ + ("W. Europe Standard Time", "Europe/Berlin"), + ("GMT Standard Time", "Europe/London"), + ("Eastern Standard Time", "America/New_York"), + ("UTC", "Etc/UTC"), + ("Tokyo Standard Time", "Asia/Tokyo"), + ("Mars Standard Time", None), + (None, None), + ], + ) + def test_a_windows_zone_id_as_iana(self, windows, iana): + assert iana_time_zone(windows) == iana + + def test_every_name_in_the_table_is_a_real_zone(self): + from zoneinfo import ZoneInfo + + from napalm_windows.time_zones import WINDOWS_TO_IANA + + for name in WINDOWS_TO_IANA.values(): + ZoneInfo(name) + + +# --------------------------------------------------------------------------- +# Enable, disable, run +# --------------------------------------------------------------------------- + + +class TestManage: + @pytest.mark.parametrize( + ("action", "cmdlet"), + [("enable", "Enable-ScheduledTask"), ("disable", "Disable-ScheduledTask")], + ) + def test_switches_the_tasks_own_flag(self, action, cmdlet): + d = _driver() + + result = d.manage_scheduled_job(DEFRAG, action, digest=_digest(DEFRAG)) + + (script,) = d._transport.writes + assert cmdlet in script + assert "'\\Microsoft\\Windows\\Defrag\\'" in script + assert "'ScheduledDefrag'" in script + assert result == {"success": True, "output": f"{DEFRAG} {action}d"} + + def test_run_says_the_task_was_started_not_that_it_finished(self): + d = _driver() + + result = d.manage_scheduled_job(DEFRAG, "run", digest=_digest(DEFRAG)) + + (script,) = d._transport.writes + assert "Start-ScheduledTask" in script + assert result["success"] is True + assert "started" in result["output"] + assert "next reading" in result["output"] + + def test_reads_again_before_it_writes(self): + d = _driver() + + d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG)) + + assert d._transport.sent[0] == mod._PS_SCHEDULED_TASKS + + def test_the_task_is_found_by_exact_path_and_name(self): + """Not by -TaskName, which takes wildcards.""" + d = _driver() + + d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG)) + + script = d._transport.writes[0] + assert "-eq '\\Microsoft\\Windows\\Defrag\\'" in script + assert "-eq 'ScheduledDefrag'" in script + assert "-TaskName" not in script + + def test_a_quote_in_a_task_name_is_doubled(self): + d = _driver() + + d.manage_scheduled_job(BACKUP, "disable", digest=_digest(BACKUP)) + + assert "'Admin''s backup'" in d._transport.writes[0] + + def test_a_changed_task_is_not_switched(self): + d = _driver() + + with pytest.raises(ScheduledJobChanged): + d.manage_scheduled_job(DEFRAG, "disable", digest="0" * 16) + assert d._transport.writes == [] + + def test_an_unknown_task_raises_lookup_error(self): + with pytest.raises(LookupError): + _driver().manage_scheduled_job("task:\\nope", "run", digest="0" * 16) + + def test_an_unknown_action_is_refused_before_anything_is_sent(self): + d = _driver() + + with pytest.raises(ScheduledJobRefused, match="action"): + d.manage_scheduled_job(DEFRAG, "delete", digest=_digest(DEFRAG)) + assert d._transport.writes == [] + + def test_a_disabled_task_is_not_run(self): + d = _driver() + + with pytest.raises(ScheduledJobRefused, match="run"): + d.manage_scheduled_job(REBOOT, "run", digest=_digest(REBOOT)) + assert d._transport.writes == [] + + def test_what_powershell_says_is_the_result(self): + d = _driver(fail="Access is denied.") + + result = d.manage_scheduled_job(DEFRAG, "disable", digest=_digest(DEFRAG)) + + assert result == {"success": False, "output": "Access is denied."} + + +# --------------------------------------------------------------------------- +# An application's own task +# --------------------------------------------------------------------------- + + +class TestPut: + def test_creates_the_task_in_the_root_folder_from_xml(self): + d = _driver(_without_dump()) + + result = d.put_scheduled_job(_spec()) # type: ignore[arg-type] + + (script,) = d._transport.writes + assert "Register-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Xml '" in script + assert "-Force" in script + assert result == {"success": True, "output": f"{DUMP} created"} + + def test_the_xml_carries_the_definition(self): + d = _driver(_without_dump()) + + d.put_scheduled_job(_spec()) # type: ignore[arg-type] + + script = d._transport.writes[0] + assert task_xml.task_xml(_spec()).replace("'", "''") in script # type: ignore[arg-type] + + def test_a_task_of_that_name_there_already(self): + d = _driver() + + with pytest.raises(ScheduledJobChanged, match="already"): + d.put_scheduled_job(_spec()) # type: ignore[arg-type] + assert d._transport.writes == [] + + def test_an_admins_root_task_of_that_name_is_not_overwritten(self): + reading = _reading() + reading["tasks"][3]["description"] = "mine" + + d = _driver(reading) + with pytest.raises(ScheduledJobChanged, match="already"): + d.put_scheduled_job(_spec()) # type: ignore[arg-type] + with pytest.raises(ScheduledJobRefused, match="application"): + d.put_scheduled_job(_spec(), digest=_digest(DUMP, reading)) # type: ignore[arg-type] + assert d._transport.writes == [] + + def test_changes_its_own_task_with_the_digest_it_saw(self): + d = _driver() + + result = d.put_scheduled_job(_spec(schedule="*/5 * * * *"), digest=_digest(DUMP)) # type: ignore[arg-type] + + assert "Register-ScheduledTask" in d._transport.writes[0] + assert "PT5M" in d._transport.writes[0] + assert result == {"success": True, "output": f"{DUMP} changed"} + + def test_a_changed_task_is_not_overwritten(self): + d = _driver() + + with pytest.raises(ScheduledJobChanged): + d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type] + assert d._transport.writes == [] + + def test_a_task_that_went_away_is_not_changed(self): + d = _driver(_without_dump()) + + with pytest.raises(LookupError): + d.put_scheduled_job(_spec(), digest="0" * 16) # type: ignore[arg-type] + + def test_a_spec_the_contract_refuses_is_refused_before_anything_is_sent(self): + d = _driver() + + with pytest.raises(ScheduledJobRefused, match="name"): + d.put_scheduled_job(_spec(name="Nightly Dump")) # type: ignore[arg-type] + assert d._transport.sent == [] + + def test_a_schedule_task_scheduler_cannot_take_is_refused_before_anything_is_sent(self): + d = _driver(_without_dump()) + + with pytest.raises(ScheduledJobRefused, match="weekday"): + d.put_scheduled_job(_spec(schedule="0 0 1 * 1")) # type: ignore[arg-type] + assert d._transport.sent == [] + + def test_quotes_in_the_command_are_doubled_for_powershell(self): + d = _driver(_without_dump()) + + d.put_scheduled_job(_spec(command="echo it's done’")) # type: ignore[arg-type] + + script = d._transport.writes[0] + assert "echo it''s done’’" in script + body = script.split("-Xml '", 1)[1].rsplit("' -Force", 1)[0] + for quote in ("'", "‘", "’", "‚", "‛"): + assert quote not in body.replace(quote * 2, "") + + def test_what_powershell_says_is_the_result(self): + d = _driver(_without_dump(), fail="The user name or password is incorrect.") + + result = d.put_scheduled_job(_spec()) # type: ignore[arg-type] + + assert result == {"success": False, "output": "The user name or password is incorrect."} + + +class TestDelete: + def test_unregisters_its_own_task(self): + d = _driver() + + result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP)) + + (script,) = d._transport.writes + assert ( + "Unregister-ScheduledTask -TaskPath '\\' -TaskName 'nightly-dump' -Confirm:$false" + in script + ) + assert result == {"success": True, "output": f"{DUMP} deleted"} + + @pytest.mark.parametrize("key", [DEFRAG, BACKUP]) + def test_a_task_an_application_did_not_write_is_refused(self, key): + d = _driver() + + with pytest.raises(ScheduledJobRefused, match="application"): + d.delete_scheduled_job(key, digest=_digest(key)) + assert d._transport.writes == [] + + def test_a_changed_task_is_not_deleted(self): + d = _driver() + + with pytest.raises(ScheduledJobChanged): + d.delete_scheduled_job(DUMP, digest="0" * 16) + assert d._transport.writes == [] + + def test_an_unknown_task_raises_lookup_error(self): + with pytest.raises(LookupError): + _driver().delete_scheduled_job("task:\\nope", digest="0" * 16) + + def test_what_powershell_says_is_the_result(self): + d = _driver(fail="Access is denied.") + + result = d.delete_scheduled_job(DUMP, digest=_digest(DUMP)) + + assert result == {"success": False, "output": "Access is denied."} + + +def test_a_written_task_reads_back_as_the_spec(): + """What put writes, the reading parses back to the same cron line and command.""" + spec = _spec(command='"C:\\Program Files\\app\\run.exe" --quiet & echo done') + xml = task_xml.task_xml(spec) # type: ignore[arg-type] + execute, arguments = task_xml.command_action(spec["command"]) + reading = _reading() + task = copy.deepcopy(reading["tasks"][3]) + task["actions"] = [{"class": "MSFT_TaskExecAction", "execute": execute, "arguments": arguments}] + task["description"] = task_xml.description(spec) # type: ignore[arg-type] + reading["tasks"][3] = task + + job = _jobs(reading)[DUMP] + + assert (job["command"], job["schedule"], job["description"]) == ( + spec["command"], + spec["schedule"], + spec["description"], + ) + assert f"{execute}" in xml diff --git a/tests/test_task_xml.py b/tests/test_task_xml.py new file mode 100644 index 0000000..555549f --- /dev/null +++ b/tests/test_task_xml.py @@ -0,0 +1,260 @@ +"""An application's task as Task Scheduler XML, and a cron expression as its triggers (#8). + +A cron shape Task Scheduler can express exactly becomes triggers; every other +shape is refused, naming why. +""" + +from __future__ import annotations + +import xml.etree.ElementTree as ET # noqa: S405 - parses only what the tests built +from typing import Any + +import pytest +from napalm_device_types import ScheduledJobRefused + +from napalm_windows import task_xml + +NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"} + + +def _spec(**changes: Any) -> Any: + spec = { + "name": "nightly-dump", + "schedule": "30 2 * * *", + "run_as": "backup", + "command": "pg_dump -f D:\\dump.sql app", + "enabled": True, + "description": "Dump the database", + } + spec.update(changes) + return spec + + +def _task(**changes: Any) -> ET.Element: + return ET.fromstring(task_xml.task_xml(_spec(**changes))) # noqa: S314 + + +def _text(task: ET.Element, path: str) -> str | None: + found = task.find(path, NS) + return None if found is None else found.text + + +def _triggers(schedule: str) -> list[dict[str, Any]]: + """Each trigger as start, repetition and day schedule, for comparing.""" + triggers = [] + found = _task(schedule=schedule).find("t:Triggers", NS) + assert found is not None + for trigger in found: + tag = trigger.tag.split("}")[1] + entry: dict[str, Any] = {"type": tag} + if tag == "CalendarTrigger": + entry["start"] = _text(trigger, "t:StartBoundary") + entry["repeat"] = ( + _text(trigger, "t:Repetition/t:Interval"), + _text(trigger, "t:Repetition/t:Duration"), + ) + schedule_by = next(c for c in trigger if c.tag.split("}")[1].startswith("Schedule")) + entry["by"] = schedule_by.tag.split("}")[1] + entry["days"] = [d.text for d in schedule_by.iter(f"{{{NS['t']}}}Day")] + entry["names"] = [ + c.tag.split("}")[1] + for part in ("DaysOfWeek", "Months") + for parent in schedule_by.iter(f"{{{NS['t']}}}{part}") + for c in parent + ] + triggers.append(entry) + return triggers + + +class TestTriggers: + def test_daily_at_one_time(self): + assert _triggers("30 2 * * *") == [ + { + "type": "CalendarTrigger", + "start": "2020-01-01T02:30:00", + "repeat": (None, None), + "by": "ScheduleByDay", + "days": [], + "names": [], + } + ] + + def test_the_daily_alias(self): + assert [t["start"] for t in _triggers("@daily")] == ["2020-01-01T00:00:00"] + + def test_weekdays_at_two_times_are_two_weekly_triggers(self): + triggers = _triggers("0 8,17 * * 1-5") + + assert [t["start"] for t in triggers] == ["2020-01-01T08:00:00", "2020-01-01T17:00:00"] + assert {t["by"] for t in triggers} == {"ScheduleByWeek"} + assert triggers[0]["names"] == ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] + + def test_sunday_is_0_and_7(self): + assert _triggers("0 0 * * 0")[0]["names"] == _triggers("0 0 * * 7")[0]["names"] + assert _triggers("0 0 * * 7")[0]["names"] == ["Sunday"] + + def test_every_five_minutes_is_one_repetition(self): + assert _triggers("*/5 * * * *") == [ + { + "type": "CalendarTrigger", + "start": "2020-01-01T00:00:00", + "repeat": ("PT5M", "PT23H56M"), + "by": "ScheduleByDay", + "days": [], + "names": [], + } + ] + + def test_every_quarter_hour_in_working_hours(self): + (trigger,) = _triggers("*/15 8-17 * * 1-5") + + assert (trigger["start"], trigger["repeat"]) == ( + "2020-01-01T08:00:00", + ("PT15M", "PT9H46M"), + ) + assert trigger["by"] == "ScheduleByWeek" + + def test_every_six_hours(self): + (trigger,) = _triggers("0 */6 * * *") + + assert trigger["repeat"] == ("PT6H", "PT18H1M") + + def test_every_minute(self): + (trigger,) = _triggers("* * * * *") + + assert (trigger["start"], trigger["repeat"]) == ("2020-01-01T00:00:00", ("PT1M", "PT24H")) + + def test_a_step_that_does_not_divide_the_hour_repeats_within_each_hour(self): + """*/7 fires at :56 and then at :00 -- four minutes, not seven: one repetition per hour.""" + triggers = _triggers("*/7 * * * *") + + assert len(triggers) == 24 + assert triggers[1]["start"] == "2020-01-01T01:00:00" + assert {t["repeat"] for t in triggers} == {("PT7M", "PT57M")} + + def test_two_hours_of_every_other_minute(self): + triggers = _triggers("*/2 8,17 * * *") + + assert [(t["start"], t["repeat"]) for t in triggers] == [ + ("2020-01-01T08:00:00", ("PT2M", "PT59M")), + ("2020-01-01T17:00:00", ("PT2M", "PT59M")), + ] + + def test_days_of_the_month(self): + (trigger,) = _triggers("0 3 1,15 * *") + + assert (trigger["by"], trigger["days"]) == ("ScheduleByMonth", ["1", "15"]) + assert len(trigger["names"]) == 12 + + def test_some_months_only(self): + (trigger,) = _triggers("0 0 * 1,jul *") + + assert trigger["by"] == "ScheduleByMonth" + assert trigger["days"] == [str(d) for d in range(1, 32)] + assert trigger["names"] == ["January", "July"] + + def test_reboot_is_a_boot_trigger(self): + assert _triggers("@reboot") == [{"type": "BootTrigger"}] + + @pytest.mark.parametrize( + ("schedule", "why"), + [ + ("0 0 1 * 1", "either"), + ("0 0 */2 * 1", "weekday"), + ("0 0 * 1 1", "weekday"), + ("0,1,5 * * * *", "48"), + ], + ) + def test_a_shape_task_scheduler_cannot_take_is_refused(self, schedule, why): + with pytest.raises(ScheduledJobRefused, match=why): + task_xml.task_xml(_spec(schedule=schedule)) + + def test_an_expression_cron_would_not_take_is_refused(self): + with pytest.raises(ScheduledJobRefused, match="range"): + task_xml.triggers("61 * * * *") + + def test_at_most_48_triggers(self): + assert len(_triggers("0,30 0-23 * * *")) == 1 # one repetition + assert len(_triggers("0,20 0-11,13-23 * * *")) == 46 + with pytest.raises(ScheduledJobRefused, match="48"): + task_xml.task_xml(_spec(schedule="0,20,30 0-11,13-23 * * *")) + + +class TestTask: + def test_the_description_names_the_job_and_keeps_its_cron_line(self): + assert _text(_task(), "t:RegistrationInfo/t:Description") == ( + "napalm-scheduled-job: nightly-dump Dump the database\nschedule: 30 2 * * *" + ) + + def test_a_job_without_a_description(self): + assert task_xml.description(_spec(description="")) == ( + "napalm-scheduled-job: nightly-dump\nschedule: 30 2 * * *" + ) + + def test_the_command_runs_in_cmd(self): + task = _task(command='"C:\\Program Files\\app.exe" -x & echo ') + + assert _text(task, "t:Actions/t:Exec/t:Command") == "%SystemRoot%\\System32\\cmd.exe" + assert _text(task, "t:Actions/t:Exec/t:Arguments") == ( + '/d /s /c ""C:\\Program Files\\app.exe" -x & echo "' + ) + + def test_the_xml_is_escaped(self): + raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z")) + + assert "a & b < c" in raw + assert "x > y & z" in raw + + def test_a_user_runs_without_a_stored_password(self): + task = _task(run_as="backup") + + assert _text(task, "t:Principals/t:Principal/t:UserId") == "backup" + assert _text(task, "t:Principals/t:Principal/t:LogonType") == "S4U" + assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "LeastPrivilege" + + @pytest.mark.parametrize("run_as", ["SYSTEM", "system"]) + def test_system_is_the_local_system_account(self, run_as): + task = _task(run_as=run_as) + + assert _text(task, "t:Principals/t:Principal/t:UserId") == "S-1-5-18" + assert _text(task, "t:Principals/t:Principal/t:LogonType") is None + assert _text(task, "t:Principals/t:Principal/t:RunLevel") == "HighestAvailable" + + @pytest.mark.parametrize("enabled", [True, False]) + def test_enabled_is_the_tasks_flag(self, enabled): + assert _text(_task(enabled=enabled), "t:Settings/t:Enabled") == str(enabled).lower() + + def test_runs_like_cron_on_battery_and_without_catching_up(self): + task = _task() + + assert _text(task, "t:Settings/t:DisallowStartIfOnBatteries") == "false" + assert _text(task, "t:Settings/t:StopIfGoingOnBatteries") == "false" + assert _text(task, "t:Settings/t:StartWhenAvailable") == "false" + assert _text(task, "t:Settings/t:MultipleInstancesPolicy") == "IgnoreNew" + + def test_a_command_is_one_line(self): + with pytest.raises(ScheduledJobRefused, match="one line"): + task_xml.task_xml(_spec(command="echo a\necho b")) + + def test_a_control_character_is_refused(self): + with pytest.raises(ScheduledJobRefused, match="control"): + task_xml.task_xml(_spec(command="echo \x07")) + + def test_trailing_whitespace_of_the_command_is_dropped(self): + assert task_xml.command_action("echo hi\n") == ( + "%SystemRoot%\\System32\\cmd.exe", + '/d /s /c "echo hi"', + ) + + @pytest.mark.parametrize( + ("execute", "arguments", "command"), + [ + ("%SystemRoot%\\System32\\cmd.exe", '/d /s /c "echo hi"', "echo hi"), + ("%systemroot%\\system32\\CMD.EXE", '/d /s /c "echo hi"', "echo hi"), + ("%SystemRoot%\\System32\\cmd.exe", "/c echo hi", None), + ("powershell.exe", '/d /s /c "echo hi"', None), + ("%SystemRoot%\\System32\\cmd.exe", None, None), + ], + ) + def test_the_command_back_from_the_action(self, execute, arguments, command): + assert task_xml.own_command(execute, arguments) == command diff --git a/tools/harvest.py b/tools/harvest.py index 582edd9..194c9d3 100644 --- a/tools/harvest.py +++ b/tools/harvest.py @@ -14,7 +14,7 @@ import argparse import getpass import pathlib -from napalm_windows import WindowsDriver +from napalm_windows import WindowsDriver, scheduled_tasks from napalm_windows import windows as mod SCRIPTS = { @@ -25,6 +25,7 @@ SCRIPTS = { "routes": mod._PS_ROUTES, "services": mod._PS_SERVICES, "listening": mod._PS_LISTENING, + "scheduled_tasks": scheduled_tasks._PS_SCHEDULED_TASKS, } OUT = pathlib.Path(__file__).parent / "harvest-out" -- 2.54.0 From 74a8c53c7c28322d3e6175f67f3e79827ee343e5 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Tue, 3 Nov 2026 08:36:00 +0100 Subject: [PATCH 2/2] chore(scheduled-jobs): require napalm-device-types 4.27.0 4.26.0 went out with the sshd drop-in change; the scheduled-jobs contract is in 4.27.0. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 8acbea1..7224cd3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.26.0", # ScheduledJobsMixin + "napalm-device-types>=4.27.0", # ScheduledJobsMixin "pypsrp>=0.8", ] -- 2.54.0