Files
napalm-windows/napalm_windows/task_xml.py
T
Christian Manivong a508b872b0
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 15s
driver / test (3.12) (pull_request) Failing after 14s
driver / types (pull_request) Failing after 23s
driver / test (3.13) (pull_request) Failing after 13s
driver / lowest (pull_request) Failing after 14s
driver / security (pull_request) Failing after 32s
driver / build (pull_request) Successful in 25s
CI / driver (pull_request) Failing after 1m21s
driver / publish (pull_request) Skipped
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:<path><name>, 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 \<name> 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
2026-11-03 05:49:12 +01:00

250 lines
9.8 KiB
Python

"""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 "<command>"`` -- ``/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: <name> <description>`` and a second
line ``schedule: <cron expression>``: 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 "<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>"
if every_date:
days = _names(_WEEKDAYS, s.weekdays, 0)
return (
f"<ScheduleByWeek><DaysOfWeek>{days}</DaysOfWeek>"
"<WeeksInterval>1</WeeksInterval></ScheduleByWeek>"
)
if s.weekdays == _ALL_WEEKDAYS:
days = "".join(f"<Day>{d}</Day>" for d in sorted(s.days))
months = _names(_MONTHS, s.months, 1)
return (
f"<ScheduleByMonth><DaysOfMonth>{days}</DaysOfMonth>"
f"<Months>{months}</Months></ScheduleByMonth>"
)
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"<Repetition><Interval>{_duration(interval)}</Interval>"
f"<Duration>{_duration(duration)}</Duration>"
"<StopAtDurationEnd>false</StopAtDurationEnd></Repetition>"
)
hour, minute = divmod(start, 60)
return (
f"<CalendarTrigger>{repetition}"
f"<StartBoundary>{_START_DATE}T{hour:02d}:{minute:02d}:00</StartBoundary>"
f"<Enabled>true</Enabled>{day_schedule}</CalendarTrigger>"
)
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 ["<BootTrigger><Enabled>true</Enabled></BootTrigger>"]
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"<UserId>{_SYSTEM_SID}</UserId><RunLevel>HighestAvailable</RunLevel>"
return (
f"<UserId>{_escape(run_as)}</UserId><LogonType>S4U</LogonType>"
"<RunLevel>LeastPrivilege</RunLevel>"
)
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'<Task version="1.2" xmlns="{_NAMESPACE}">'
f"<RegistrationInfo><Description>{_escape(description(spec))}</Description>"
"</RegistrationInfo>"
f"<Triggers>{trigger_xml}</Triggers>"
f'<Principals><Principal id="Author">{_principal(spec["run_as"])}</Principal></Principals>'
"<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>"
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"
"<StartWhenAvailable>false</StartWhenAvailable>"
"<AllowStartOnDemand>true</AllowStartOnDemand>"
f"<Enabled>{enabled}</Enabled></Settings>"
f'<Actions Context="Author"><Exec><Command>{_escape(execute)}</Command>'
f"<Arguments>{_escape(arguments)}</Arguments></Exec></Actions>"
"</Task>"
)