From 98031a20a1dd8d3c536c4efabf289134b64e659b Mon Sep 17 00:00:00 2001 From: PTah Date: Mon, 4 May 2026 09:38:02 +1000 Subject: [PATCH] fix: InstallTasks before DPAPI, deploy elevation and installtasks logs (1.4.1) --- Deploy-LoginMonitor.ps1 | 33 ++++++++++++++++++++++++++++++++- Login_Monitor.ps1 | 37 +++++++++++++++++++------------------ version.txt | 2 +- 3 files changed, 52 insertions(+), 20 deletions(-) diff --git a/Deploy-LoginMonitor.ps1 b/Deploy-LoginMonitor.ps1 index ae6b282..d9e75f5 100644 --- a/Deploy-LoginMonitor.ps1 +++ b/Deploy-LoginMonitor.ps1 @@ -33,6 +33,18 @@ param( Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" +function Test-DeployRunningElevated { + try { + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + # LocalSystem (GPO startup / задачи SYSTEM): не всегда даёт true на BuiltInRole::Administrator. + if ($null -ne $id.User -and $id.User.Value -eq 'S-1-5-18') { return $true } + $p = New-Object Security.Principal.WindowsPrincipal($id) + return $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + } catch { + return $false + } +} + $InstallRoot = [System.IO.Path]::GetFullPath("$env:ProgramData\RDP-login-monitor") $LocalScript = Join-Path $InstallRoot "Login_Monitor.ps1" $VersionStampPath = Join-Path $InstallRoot "deployed_version.txt" @@ -206,6 +218,11 @@ try { exit 0 } + if (-not (Test-DeployRunningElevated)) { + Write-DeployLog "ОШИБКА: запустите Deploy из повышенной консоли PowerShell («Запуск от имени администратора»). Без этого дочерний Login_Monitor.ps1 -InstallTasks завершится с кодом 1 (нет прав на регистрацию задач)." + exit 0 + } + Stop-RdpLoginMonitorMainProcesses Copy-Item -LiteralPath $sourceScript -Destination $LocalScript -Force @@ -214,9 +231,23 @@ try { $installArgs = @( '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $LocalScript, '-InstallTasks' ) - $p = Start-Process -FilePath $PsExe -ArgumentList $installArgs -Wait -PassThru -WindowStyle Hidden + $instOut = Join-Path $InstallRoot "Logs\deploy_installtasks_stdout.log" + $instErr = Join-Path $InstallRoot "Logs\deploy_installtasks_stderr.log" + $p = Start-Process -FilePath $PsExe -ArgumentList $installArgs -Wait -PassThru -WindowStyle Hidden ` + -RedirectStandardOutput $instOut -RedirectStandardError $instErr if ($p.ExitCode -ne 0) { Write-DeployLog "Предупреждение: InstallTasks завершился с кодом $($p.ExitCode)." + foreach ($pair in @(@($instOut, 'stdout'), @($instErr, 'stderr'))) { + $lp = $pair[0] + $lbl = $pair[1] + if (Test-Path -LiteralPath $lp) { + $tail = Get-Content -LiteralPath $lp -Tail 40 -ErrorAction SilentlyContinue + if ($tail) { + Write-DeployLog "InstallTasks $lbl (хвост): $($tail -join ' | ')" + } + } + } + Write-DeployLog "Подсказка: полный вывод в Logs\deploy_installtasks_*.log; также см. login_monitor.log за это время." } else { Write-DeployLog "InstallTasks выполнен (код 0)." } diff --git a/Login_Monitor.ps1 b/Login_Monitor.ps1 index 48588db..354202f 100644 --- a/Login_Monitor.ps1 +++ b/Login_Monitor.ps1 @@ -69,7 +69,7 @@ $script:MonitorSingletonLockStream = $null # строки ниже, если правки «мелкие» и вы не хотите менять отображаемую версию в логах). # Рекомендация: при значимых релизах меняйте и $ScriptVersion, и version.txt одинаково; при только # исправлениях на шаре — достаточно поднять patch в version.txt (например 1.3.0.1). -$ScriptVersion = "1.4.0" +$ScriptVersion = "1.4.1" # Логи (все под InstallRoot) $LogFile = Join-Path $script:InstallRoot "Logs\login_monitor.log" @@ -491,6 +491,24 @@ function Start-RdpMonitorWatchdogMain { exit 0 } +# Watchdog и InstallTasks — до DPAPI/Telegram: Deploy вызывает -InstallTasks без зависимости от секретов на машине. +if ($Watchdog) { + Start-RdpMonitorWatchdogMain + exit 0 +} + +if ($InstallTasks) { + $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($currentUser) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Log "InstallTasks: нужны права администратора." + exit 1 + } + Register-RdpMonitorScheduledTasksCore + Write-Log "InstallTasks: задачи планировщика обновлены." + exit 0 +} + # --- Учётные данные Telegram (открытый текст или DPAPI Base64) --- if (-not [string]::IsNullOrWhiteSpace($TelegramBotTokenProtectedB64)) { try { @@ -511,23 +529,6 @@ if (-not [string]::IsNullOrWhiteSpace($TelegramChatIDProtectedB64)) { if ($TelegramBotToken -eq '') { $TelegramBotToken = "" } if ($TelegramChatID -eq '') { $TelegramChatID = "" } -if ($Watchdog) { - Start-RdpMonitorWatchdogMain - exit 0 -} - -if ($InstallTasks) { - $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = New-Object Security.Principal.WindowsPrincipal($currentUser) - if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - Write-Log "InstallTasks: нужны права администратора." - exit 1 - } - Register-RdpMonitorScheduledTasksCore - Write-Log "InstallTasks: задачи планировщика обновлены." - exit 0 -} - function ConvertTo-TelegramHtml { param([string]$Text) if ($null -eq $Text) { return '' } diff --git a/version.txt b/version.txt index 88c5fb8..347f583 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.4.0 +1.4.1