"""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")