Files
napalm-windows/tests/test_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

261 lines
9.8 KiB
Python

"""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 <done>')
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 <done>"'
)
def test_the_xml_is_escaped(self):
raw = task_xml.task_xml(_spec(command="a & b < c", description="x > y & z"))
assert "a &amp; b &lt; c" in raw
assert "x &gt; y &amp; 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