Add Install-ScheduledTasks.ps1 for Task Scheduler registration; document in README

This commit is contained in:
PTah
2026-04-13 11:29:21 +10:00
parent b164e51965
commit 4f0b6e219c
2 changed files with 100 additions and 3 deletions
+86
View File
@@ -0,0 +1,86 @@
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Регистрирует в Планировщике заданий основной монитор и watchdog (как в README).
.DESCRIPTION
Запускайте из повышенной PowerShell. Пути по умолчанию — D:\Soft\.
Watchdog использует Watchdog_RDP_Monitor.ps1 из репозитория (проверка процесса и heartbeat).
#>
[CmdletBinding()]
param(
[string]$InstallRoot = "D:\Soft",
[string]$MainTaskName = "RDP Login Monitor",
[string]$WatchdogTaskName = "RDP Login Monitor Watchdog",
[int]$WatchdogRepeatMinutes = 5,
[int]$MainStartupRandomDelayMinutes = 1,
[int]$WatchdogStartupRandomDelayMinutes = 2
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$LoginScriptPath = Join-Path $InstallRoot "Login_Monitor.ps1"
$WatchdogScriptPath = Join-Path $InstallRoot "Watchdog_RDP_Monitor.ps1"
$LogsDir = Join-Path $InstallRoot "Logs"
if (-not (Test-Path -LiteralPath $LoginScriptPath)) {
throw "Не найден основной скрипт: $LoginScriptPath"
}
if (-not (Test-Path -LiteralPath $WatchdogScriptPath)) {
throw "Не найден watchdog: $WatchdogScriptPath"
}
if (-not (Test-Path -LiteralPath $LogsDir)) {
New-Item -ItemType Directory -Path $LogsDir -Force | Out-Null
}
$principal = New-ScheduledTaskPrincipal `
-UserId "NT AUTHORITY\SYSTEM" `
-LogonType ServiceAccount `
-RunLevel Highest
# --- Задание 1: основной монитор ---
$mainArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$LoginScriptPath`""
$mainAction = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $mainArgs
$mainTrigger = New-ScheduledTaskTrigger -AtStartup -RandomDelay (New-TimeSpan -Minutes $MainStartupRandomDelayMinutes)
$mainSettings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $MainTaskName `
-Action $mainAction `
-Trigger $mainTrigger `
-Principal $principal `
-Settings $mainSettings `
-Force | Out-Null
Write-Host "Создано задание: $MainTaskName" -ForegroundColor Cyan
# --- Задание 2: watchdog (старт + периодический запуск, как в README) ---
$wdArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$WatchdogScriptPath`""
$wdAction = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $wdArgs
$wdTriggerStartup = New-ScheduledTaskTrigger -AtStartup -RandomDelay (New-TimeSpan -Minutes $WatchdogStartupRandomDelayMinutes)
$repeatDuration = New-TimeSpan -Days 3650
$anchor = (Get-Date).AddMinutes([Math]::Max(3, $WatchdogRepeatMinutes))
$wdTriggerRepeat = New-ScheduledTaskTrigger -Once -At $anchor `
-RepetitionInterval (New-TimeSpan -Minutes $WatchdogRepeatMinutes) `
-RepetitionDuration $repeatDuration
$wdSettings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $WatchdogTaskName `
-Action $wdAction `
-Trigger @($wdTriggerStartup, $wdTriggerRepeat) `
-Principal $principal `
-Settings $wdSettings `
-Force | Out-Null
Write-Host "Создано задание: $WatchdogTaskName (триггеры: при старте ОС и каждые $WatchdogRepeatMinutes мин.)" -ForegroundColor Cyan
Write-Host "Готово. При необходимости сразу запустите: Start-ScheduledTask -TaskName '$MainTaskName'" -ForegroundColor Green
+14 -3
View File
@@ -4,6 +4,7 @@ PowerShell-набор для мониторинга входов в Windows с
- `Login_Monitor.ps1` — основной монитор (Security `4624/4625`, RD Gateway `302/303`, ротация логов, heartbeat, ежедневный отчет).
- `Watchdog_RDP_Monitor.ps1` — watchdog: проверяет, жив ли основной скрипт, и перезапускает его при падении/зависании heartbeat.
- `Install-ScheduledTasks.ps1` — создание в Планировщике заданий с теми же именами и параметрами, что в разделе 3 (нужна повышенная PowerShell).
## Что изменилось (важное)
@@ -14,7 +15,7 @@ PowerShell-набор для мониторинга входов в Windows с
## 1) Подготовка
1. Скопируйте `Login_Monitor.ps1` в `D:\Soft\Login_Monitor.ps1` (или измените путь в watchdog).
1. Скопируйте в `D:\Soft\` как минимум `Login_Monitor.ps1` и `Watchdog_RDP_Monitor.ps1` (для установки из скрипта — ещё `Install-ScheduledTasks.ps1`), либо измените пути в параметрах установщика / в watchdog.
2. Откройте `Login_Monitor.ps1` и задайте:
- `$TelegramBotToken`
- `$TelegramChatID`
@@ -29,7 +30,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "D:\Soft\Login_Monitor.p
## 3) Запуск через Планировщик заданий (Task Scheduler)
### Задание №1: основной монитор
Задания можно завести **вручную в GUI** (ниже) или **одной командой из PowerShell** — см. `Install-ScheduledTasks.ps1` (в начале файла стоит `#Requires -RunAsAdministrator`). Скрипт регистрирует **`RDP Login Monitor`** (старт ОС, запуск `Login_Monitor.ps1`) и **`RDP Login Monitor Watchdog`** (старт ОС + повтор каждые 5 минут, запуск `Watchdog_RDP_Monitor.ps1` из того же каталога). Пути по умолчанию: `D:\Soft\`. Параметры: `-InstallRoot`, `-MainTaskName`, `-WatchdogTaskName`, `-WatchdogRepeatMinutes`, задержки случайного старта и т.д.
Пример после копирования файлов в `D:\Soft\`:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "D:\Soft\Install-ScheduledTasks.ps1"
```
Это не заменяет настройку токена Telegram в `Login_Monitor.ps1`, а только регистрирует задания.
### Задание №1: основной монитор (вручную)
Создайте задачу `RDP Login Monitor`:
@@ -48,7 +59,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "D:\Soft\Login_Monitor.p
- **Settings**
- `If the task is already running`: `Do not start a new instance`
### Задание №2: watchdog
### Задание №2: watchdog (вручную)
Создайте задачу `RDP Login Monitor Watchdog`: