Revert "Use ASCII-only source for Telegram and logs; remove emoji (v1.2.0)"

This reverts commit b16ebb028b.
This commit is contained in:
PTah
2026-04-27 10:25:55 +10:00
parent b032de9d1c
commit 850781a38d
+102 -97
View File
@@ -1,12 +1,15 @@
<# <#
.SYNOPSIS .SYNOPSIS
Windows login / RDP / RD Gateway event monitor; Telegram notifications. Мониторинг логинов/попыток входа с уведомлениями в Telegram
.DESCRIPTION .DESCRIPTION
Watches Security 4624/4625, optional Microsoft-Windows-TerminalServices-Gateway/Operational Отслеживает события входа в систему (Security 4624/4625) и события RD Gateway (302/303),
302/303, log rotation, heartbeat file, and daily report. отправляет уведомления в Telegram, делает ротацию логов, heartbeat в файл и ежедневный отчет.
.NOTES .NOTES
PowerShell 5.0+; run elevated. String literals in this file are kept ASCII-only so the script Требуется: PowerShell 5.0+, запуск от администратора.
still parses if the .ps1 was re-encoded during download (e.g. broken UTF-8). Telegram messages are English. Важное:
- На некоторых серверах RDP-логин приходит как LogonType=3, поэтому интерактивные типы: 2/3/10.
- Добавлены исключения шума: DWM-*, UMFD-*, HealthMailbox*, Font Driver Host*, NtLmSsp и др.
- Heartbeat без дрейфа: используется nextHeartbeatTime (а не "прошло N секунд").
#> #>
[CmdletBinding()] [CmdletBinding()]
@@ -18,30 +21,31 @@ param(
Set-StrictMode -Version Latest Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
# RU auditpol labels as BMP code points (ASCII-only source) # Строка из BMP code point (0x....) — в исходнике остается только ASCII, скрипт не ломается
# при скачивании через IWR, если при переносе в строке испортится UTF-8.
function Uc { param([int[]]$C) -join ($C | ForEach-Object { [char]$_ }) } function Uc { param([int[]]$C) -join ($C | ForEach-Object { [char]$_ }) }
# ============================================ # ============================================
# CONFIG # КОНФИГУРАЦИЯ
# ============================================ # ============================================
# Version; logged to file and host on start # Версия (обновляйте при значимых изменениях; пишется в лог и в консоль при интерактивном запуске)
$ScriptVersion = "1.2.0" $ScriptVersion = "1.1.1"
# Logs # Логи
$LogFile = "D:\Soft\Logs\login_monitor.log" $LogFile = "D:\Soft\Logs\login_monitor.log"
$LogBackupFolder = "D:\Soft\Logs\Backup" $LogBackupFolder = "D:\Soft\Logs\Backup"
$MaxBackupDays = 30 $MaxBackupDays = 30
# Log rotation (daily at local time) # Ротация логов (ежедневно)
$LogRotationHour = 0 $LogRotationHour = 0
$LogRotationMinute = 0 $LogRotationMinute = 0
# Heartbeat file only (no Telegram) # Heartbeat (только файл)
$HeartbeatInterval = 3600 $HeartbeatInterval = 3600
$HeartbeatFile = "D:\Soft\Logs\last_heartbeat.txt" $HeartbeatFile = "D:\Soft\Logs\last_heartbeat.txt"
# Daily report (local time) # Ежедневный отчет
$DailyReportHour = 9 $DailyReportHour = 9
$DailyReportMinute = 0 $DailyReportMinute = 0
$LastReportFile = "D:\Soft\Logs\last_daily_report.txt" $LastReportFile = "D:\Soft\Logs\last_daily_report.txt"
@@ -89,22 +93,22 @@ $ExcludedComputerPatterns = @(
"Authz*" "Authz*"
) )
# Optional: ignore noisy network logon (type 3) from a specific source IP + logon process substring # Узкое исключение "шумовых" сетевых логонов (LogonType=3) от конкретных источников.
# (e.g. some LDAP / mail gateway sync tools) # Пример: Proxmox Mail Gateway / LDAP sync, которые периодически создают 4624 с LogonProcessName=Advapi.
$IgnoreAdvapiNetworkLogonSourceIps = @( $IgnoreAdvapiNetworkLogonSourceIps = @(
"192.168.160.57" "192.168.160.57"
) )
$IgnoreAdvapiNetworkLogonProcessContains = "Advapi" $IgnoreAdvapiNetworkLogonProcessContains = "Advapi"
# ============================================ # ============================================
# INIT # ИНИЦИАЛИЗАЦИЯ
# ============================================ # ============================================
$LogDir = Split-Path $LogFile -Parent $LogDir = Split-Path $LogFile -Parent
if (!(Test-Path $LogDir)) { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null } if (!(Test-Path $LogDir)) { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null }
if (!(Test-Path $LogBackupFolder)) { New-Item -ItemType Directory -Path $LogBackupFolder -Force | Out-Null } if (!(Test-Path $LogBackupFolder)) { New-Item -ItemType Directory -Path $LogBackupFolder -Force | Out-Null }
# UTF-8 with BOM for log files (safer in older viewers) # UTF-8 с BOM: иначе часть просмотрщиков (FAR и др.) открывает лог как ANSI/OEM и показывает "кракозябры".
$script:Utf8BomEncoding = New-Object System.Text.UTF8Encoding $true $script:Utf8BomEncoding = New-Object System.Text.UTF8Encoding $true
function Ensure-FileStartsWithUtf8Bom { function Ensure-FileStartsWithUtf8Bom {
@@ -148,13 +152,13 @@ function ConvertTo-TelegramHtml {
try { try {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol =
[System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12 [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
Write-Log "TLS 1.2 enabled" Write-Log "TLS 1.2 включен"
} catch { } catch {
try { try {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
Write-Log "TLS 1.2 set" Write-Log "TLS 1.2 установлен"
} catch { } catch {
Write-Log "WARNING: could not set TLS 1.2" Write-Log "ВНИМАНИЕ: Не удалось включить TLS 1.2"
} }
} }
@@ -162,7 +166,7 @@ function Send-TelegramMessage {
param([string]$Message) param([string]$Message)
if ([string]::IsNullOrWhiteSpace($TelegramBotToken) -or [string]::IsNullOrWhiteSpace($TelegramChatID)) { if ([string]::IsNullOrWhiteSpace($TelegramBotToken) -or [string]::IsNullOrWhiteSpace($TelegramChatID)) {
Write-Log "Telegram: missing token or chat_id" Write-Log "Telegram: не задан токен/chat_id"
return $false return $false
} }
@@ -178,23 +182,23 @@ function Send-TelegramMessage {
$null = Invoke-RestMethod -Uri $uri -Method Post -Body $body -ErrorAction Stop -TimeoutSec 30 $null = Invoke-RestMethod -Uri $uri -Method Post -Body $body -ErrorAction Stop -TimeoutSec 30
return $true return $true
} catch { } catch {
Write-Log "Telegram send error: $($_.Exception.Message)" Write-Log "Ошибка отправки в Telegram: $($_.Exception.Message)"
return $false return $false
} }
} }
function Test-TelegramConnection { function Test-TelegramConnection {
Write-Log "Testing Telegram API (getMe)..." Write-Log "Проверка подключения к Telegram API..."
try { try {
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
$testUrl = "https://api.telegram.org/bot$TelegramBotToken/getMe" $testUrl = "https://api.telegram.org/bot$TelegramBotToken/getMe"
$response = Invoke-RestMethod -Uri $testUrl -Method Get -TimeoutSec 10 -ErrorAction Stop $response = Invoke-RestMethod -Uri $testUrl -Method Get -TimeoutSec 10 -ErrorAction Stop
if ($response.ok) { if ($response.ok) {
Write-Log "Telegram OK, bot: @$($response.result.username)" Write-Log "Подключение к Telegram успешно. Бот: @$($response.result.username)"
return $true return $true
} }
} catch { } catch {
Write-Log "Telegram API error: $($_.Exception.Message)" Write-Log "Ошибка подключения к Telegram: $($_.Exception.Message)"
return $false return $false
} }
return $false return $false
@@ -207,10 +211,10 @@ function Test-Administrator {
} }
if (-not (Test-Administrator)) { if (-not (Test-Administrator)) {
Write-Log "ERROR: run elevated (Administrator). Version $ScriptVersion" Write-Log "ОШИБКА: Скрипт должен быть запущен от имени администратора! (версия $ScriptVersion)"
exit 1 exit 1
} }
Write-Log "Running as Administrator, version $ScriptVersion" Write-Log "Скрипт запущен с правами администратора, версия $ScriptVersion"
function Enable-SecurityAudit { function Enable-SecurityAudit {
Write-Log "Checking security audit (auditpol) settings..." Write-Log "Checking security audit (auditpol) settings..."
@@ -375,7 +379,8 @@ function Enable-SecurityAudit {
} }
function Test-RDSDeploymentPresent { function Test-RDSDeploymentPresent {
# Gateway-only nodes are not "full session host"; gateway traffic uses separate Telegram lines (302/303) # Узел только с RD Gateway (RDS-Gateway и т.п.) не считаем «полноценным RDS по сессиям» —
# для шлюза отдельное сообщение в Telegram (журнал Gateway, 302/303 к целевым ПК).
$gatewayOnlyFeatureNames = @('RDS-Gateway', 'RDS-WEB-ACCESS') $gatewayOnlyFeatureNames = @('RDS-Gateway', 'RDS-WEB-ACCESS')
try { try {
@@ -406,22 +411,22 @@ function Send-Heartbeat {
$hHost = (ConvertTo-TelegramHtml $env:COMPUTERNAME) $hHost = (ConvertTo-TelegramHtml $env:COMPUTERNAME)
if ($IsStartup) { if ($IsStartup) {
$message = "<b>Login monitor started</b>`r`n" $message = "<b>✅ Мониторинг логинов ЗАПУЩЕН</b>`r`n"
$message += "Host: $hHost`r`n" $message += "🖥️ Сервер: $hHost`r`n"
$message += "Time: $timestamp" $message += "🕐 Время запуска: $timestamp"
if (Test-RDSDeploymentPresent) { if (Test-RDSDeploymentPresent) {
$message += "`r`n<b>RDS (session host role):</b> this server has non-Gateway RDS components; 4624/4625 and configured logon types are monitored (see script settings)" $message += "`r`n🔐 <b>RDS (хост сессий):</b> обнаружены компоненты RDS помимо чистого шлюза — в мониторинг входят входы по RDP/RDS на этом узле (Security 4624/4625, типы входа по настройке скрипта)."
} }
if ($EnableRDGatewayMonitoring) { if ($EnableRDGatewayMonitoring) {
try { try {
$gwLog = Get-WinEvent -ListLog $RDGatewayLogName -ErrorAction SilentlyContinue $gwLog = Get-WinEvent -ListLog $RDGatewayLogName -ErrorAction SilentlyContinue
if ($gwLog) { if ($gwLog) {
$message += "`r`n<b>RD Gateway log:</b> also recording user connections to <b>internal target PCs</b> via the gateway (events 302/303)" $message += "`r`n🌐 <b>RD Gateway:</b> журнал шлюза доступен — дополнительно фиксируются подключения пользователей к <b>внутренним целевым компьютерам</b> через RD Gateway (события 302/303 в журнале шлюза)."
} }
} catch { } } catch { }
} }
Send-TelegramMessage -Message $message | Out-Null Send-TelegramMessage -Message $message | Out-Null
Write-Log "Startup notification sent to Telegram" Write-Log "Отправлено уведомление о запуске скрипта"
} else { } else {
Write-TextFileUtf8Bom -Path $HeartbeatFile -Text $timestamp Write-TextFileUtf8Bom -Path $HeartbeatFile -Text $timestamp
} }
@@ -433,13 +438,13 @@ function Send-StopNotification {
$timestamp = Get-Date -Format "dd.MM.yyyy HH:mm:ss" $timestamp = Get-Date -Format "dd.MM.yyyy HH:mm:ss"
$hHost = (ConvertTo-TelegramHtml $env:COMPUTERNAME) $hHost = (ConvertTo-TelegramHtml $env:COMPUTERNAME)
$hReason = (ConvertTo-TelegramHtml $Reason) $hReason = (ConvertTo-TelegramHtml $Reason)
$message = "<b>Login monitor stopped</b>`r`n" $message = "<b>⚠️ МОНИТОРИНГ ЛОГИНОВ ОСТАНОВЛЕН</b>`r`n"
$message += "Host: $hHost`r`n" $message += "🖥️ Сервер: $hHost`r`n"
$message += "Time: $timestamp`r`n" $message += "🕐 Время остановки: $timestamp`r`n"
$message += "Reason: $hReason" $message += "📋 Причина: $hReason"
Send-TelegramMessage -Message $message | Out-Null Send-TelegramMessage -Message $message | Out-Null
Write-Log "Stop notification sent: $Reason" Write-Log "Уведомление об остановке отправлено: $Reason"
} }
function Rotate-LogFile { function Rotate-LogFile {
@@ -451,21 +456,21 @@ function Rotate-LogFile {
Copy-Item -Path $LogFile -Destination $backupFilePath -Force Copy-Item -Path $LogFile -Destination $backupFilePath -Force
Clear-Content -Path $LogFile -Force Clear-Content -Path $LogFile -Force
# Re-add UTF-8 BOM after Clear-Content # После Clear-Content файл пустой без BOM — восстановим UTF-8 BOM для корректного просмотра в FAR/редакторах
Ensure-FileStartsWithUtf8Bom -Path $LogFile Ensure-FileStartsWithUtf8Bom -Path $LogFile
Write-Log "Log file copied to backup: $backupFilePath" Write-Log "Лог-файл скопирован в бэкап: $backupFilePath"
$oldBackups = Get-ChildItem -Path $LogBackupFolder -Filter "LoginLog_*.bak" | $oldBackups = Get-ChildItem -Path $LogBackupFolder -Filter "LoginLog_*.bak" |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$MaxBackupDays) } Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$MaxBackupDays) }
foreach ($oldBackup in $oldBackups) { foreach ($oldBackup in $oldBackups) {
Remove-Item -Path $oldBackup.FullName -Force Remove-Item -Path $oldBackup.FullName -Force
Write-Log "Deleted old backup: $($oldBackup.Name)" Write-Log "Удален старый бэкап: $($oldBackup.Name)"
} }
return $true return $true
} }
} catch { } catch {
Write-Log "Log rotation error: $($_.Exception.Message)" Write-Log "Ошибка при ротации лог-файла: $($_.Exception.Message)"
} }
return $false return $false
} }
@@ -518,11 +523,11 @@ function Cleanup-OldLogs {
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$MaxBackupDays) } Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$MaxBackupDays) }
foreach ($oldBackup in $oldBackups) { foreach ($oldBackup in $oldBackups) {
Remove-Item -Path $oldBackup.FullName -Force Remove-Item -Path $oldBackup.FullName -Force
Write-Log "Deleted old backup: $($oldBackup.Name)" Write-Log "Удален старый бэкап: $($oldBackup.Name)"
} }
} }
} catch { } catch {
Write-Log "Old log cleanup error: $($_.Exception.Message)" Write-Log "Ошибка при очистке старых логов: $($_.Exception.Message)"
} }
} }
@@ -561,15 +566,15 @@ function Convert-ToIntSafe {
function Get-LogonTypeName { function Get-LogonTypeName {
param([int]$LogonType) param([int]$LogonType)
switch ($LogonType) { switch ($LogonType) {
2 { return "Interactive (console) (2)" } 2 { return "Интерактивный (консоль)" }
3 { return "Network (3) / often RDP on some hosts" } 3 { return "Сеть/RDP (Network) (3)" }
10 { return "Remote interactive RDP (10)" } 10 { return "Удаленный интерактивный (RDP) (10)" }
4 { return "Batch (4)" } 4 { return "Пакетный (Batch)" }
5 { return "Service (5)" } 5 { return "Сервис (Service)" }
7 { return "Unlock (7)" } 7 { return "Разблокировка (Unlock)" }
8 { return "Network cleartext (8)" } 8 { return "Сетевой с явными данными" }
9 { return "New credentials (9)" } 9 { return "Новые учетные данные" }
default { return "Type $LogonType (other)" } default { return "Тип $LogonType (неизвестный)" }
} }
} }
@@ -591,12 +596,12 @@ function Should-IgnoreEvent {
if ($EventID -eq 4648) { return $true } if ($EventID -eq 4648) { return $true }
if ([string]::IsNullOrWhiteSpace($Username)) { return $true } if ([string]::IsNullOrWhiteSpace($Username)) { return $true }
# DWM/UMFD (e.g. DOMAIN\\DWM-8) # DWM/UMFD (иногда приходит как DOMAIN\DWM-8)
if ($Username -match '(?i)(\\)?DWM-\d+') { return $true } if ($Username -match '(?i)(\\)?DWM-\d+') { return $true }
if ($Username -match '(?i)(\\)?UMFD-\d+') { return $true } if ($Username -match '(?i)(\\)?UMFD-\d+') { return $true }
if ($Username -like "*$") { return $true } if ($Username -like "*$") { return $true }
# Network logon 3 + Advapi + allowlisted source IP # Узкий фильтр: сетевой логон (3) + Advapi + конкретный IP источника
if ($EventID -eq 4624 -and $LogonType -eq 3) { if ($EventID -eq 4624 -and $LogonType -eq 3) {
foreach ($ip in $IgnoreAdvapiNetworkLogonSourceIps) { foreach ($ip in $IgnoreAdvapiNetworkLogonSourceIps) {
if ([string]::IsNullOrWhiteSpace($ip)) { continue } if ([string]::IsNullOrWhiteSpace($ip)) { continue }
@@ -662,7 +667,7 @@ function Get-LoginEventInfo {
) )
} }
} catch { } catch {
Write-Log "Error parsing event data: $($_.Exception.Message)" Write-Log "Ошибка при извлечении данных события: $($_.Exception.Message)"
} }
if ([string]::IsNullOrWhiteSpace($eventData.Username)) { $eventData.Username = "-" } if ([string]::IsNullOrWhiteSpace($eventData.Username)) { $eventData.Username = "-" }
@@ -697,19 +702,19 @@ function Format-LoginEvent {
$hTime = (ConvertTo-TelegramHtml ($TimeCreated.ToString('dd.MM.yyyy HH:mm:ss'))) $hTime = (ConvertTo-TelegramHtml ($TimeCreated.ToString('dd.MM.yyyy HH:mm:ss')))
$message = "<b>" $message = "<b>"
if ($EventID -eq 4624) { $message += "LOGON OK" } if ($EventID -eq 4624) { $message += "✅ УСПЕШНЫЙ ВХОД" }
elseif ($EventID -eq 4625) { $message += "LOGON FAILED" } elseif ($EventID -eq 4625) { $message += "❌ НЕУДАЧНАЯ ПОПЫТКА" }
else { $message += "EVENT" } else { $message += "⚠️ СОБЫТИЕ" }
$message += "</b>`r`n" $message += "</b>`r`n"
$message += "User: $hUser`r`n" $message += "👤 Пользователь: $hUser`r`n"
$message += "Security log (machine): $hLog`r`n" $message += "🏢 Сервер (журнал Security): $hLog`r`n"
$message += "Workstation: $hWkst`r`n" $message += "🖥️ Рабочая станция (клиент из события): $hWkst`r`n"
$message += "IP: $hIp`r`n" $message += "🌐 IP адрес: $hIp`r`n"
$message += "Process/code: $hProc`r`n" $message += "⚙️ Процесс/Код: $hProc`r`n"
$message += "Logon type: $hLtName ($LogonType)`r`n" $message += "🔑 Тип входа: $hLtName ($LogonType)`r`n"
$message += "Time: $hTime`r`n" $message += "🕐 Время: $hTime`r`n"
$message += "Event ID: $EventID" $message += "🔢 Event ID: $EventID"
return $message return $message
} }
@@ -718,11 +723,11 @@ function Test-RDGatewayLog {
try { try {
$logExists = Get-WinEvent -ListLog $RDGatewayLogName -ErrorAction SilentlyContinue $logExists = Get-WinEvent -ListLog $RDGatewayLogName -ErrorAction SilentlyContinue
if ($logExists) { if ($logExists) {
Write-Log "RD Gateway log found: $RDGatewayLogName" Write-Log "Журнал RD Gateway доступен: $RDGatewayLogName"
return $true return $true
} }
} catch { } catch {
Write-Log "RD Gateway log check error: $($_.Exception.Message)" Write-Log "Ошибка при проверке журнала RD Gateway: $($_.Exception.Message)"
} }
return $false return $false
} }
@@ -755,7 +760,7 @@ function Get-RDGatewayEventInfo {
} }
} }
} catch { } catch {
Write-Log "RD Gateway event parse error: $($_.Exception.Message)" Write-Log "Ошибка при извлечении RD Gateway события: $($_.Exception.Message)"
} }
return $eventData return $eventData
} }
@@ -778,20 +783,20 @@ function Format-RDGatewayEvent {
$hTime = (ConvertTo-TelegramHtml ($TimeCreated.ToString('dd.MM.yyyy HH:mm:ss'))) $hTime = (ConvertTo-TelegramHtml ($TimeCreated.ToString('dd.MM.yyyy HH:mm:ss')))
$message = "<b>" $message = "<b>"
if ($EventID -eq 302) { $message += "RD Gateway connection OK" } if ($EventID -eq 302) { $message += "🖥️ УСПЕШНОЕ ПОДКЛЮЧЕНИЕ ЧЕРЕЗ RD GATEWAY" }
elseif ($EventID -eq 303) { $message += "RD Gateway connection FAILED" } elseif ($EventID -eq 303) { $message += "❌ НЕУДАЧНОЕ ПОДКЛЮЧЕНИЕ ЧЕРЕЗ RD GATEWAY" }
else { $message += "RD Gateway event" } else { $message += "⚠️ СОБЫТИЕ RD GATEWAY" }
$message += "</b>`r`n" $message += "</b>`r`n"
$message += "User: $hUser`r`n" $message += "👤 Пользователь: $hUser`r`n"
$message += "Client IP: $hExt`r`n" $message += "🌐 IP пользователя (внешний): $hExt`r`n"
$message += "Target IP: $hInt`r`n" $message += "🖥️ IP внутренний: $hInt`r`n"
$message += "Protocol: $hProto`r`n" $message += "🔌 Протокол: $hProto`r`n"
if ($EventID -eq 303 -and $ErrorCode -ne "0" -and $ErrorCode -ne "N/A") { if ($EventID -eq 303 -and $ErrorCode -ne "0" -and $ErrorCode -ne "N/A") {
$message += "Error: $(ConvertTo-TelegramHtml $ErrorCode)`r`n" $message += "⚠️ Код ошибки: $(ConvertTo-TelegramHtml $ErrorCode)`r`n"
} }
$message += "Time: $hTime`r`n" $message += "🕐 Время: $hTime`r`n"
$message += "Event ID: $EventID" $message += "🔢 Event ID: $EventID"
return $message return $message
} }
@@ -813,27 +818,27 @@ function Send-DailyReport {
} }
} }
$count = $usernames.Count $count = $usernames.Count
# PS 5.1: a single name can be a scalar (no .Count); empty list is $null # PS 5.1: без @() один логин даёт скаляр String (нет .Count); пустой список даёт $null.
$uniqueUsers = @($usernames | Sort-Object -Unique) $uniqueUsers = @($usernames | Sort-Object -Unique)
$message = "<b>Daily report (quser)</b>`r`n" $message = "<b>📊 ЕЖЕДНЕВНЫЙ ОТЧЕТ</b>`r`n"
$message += "Server: $(ConvertTo-TelegramHtml $env:COMPUTERNAME)`r`n" $message += "🖥️ Сервер: $(ConvertTo-TelegramHtml $env:COMPUTERNAME)`r`n"
$message += "Time: $(Get-Date -Format 'dd.MM.yyyy HH:mm:ss')`r`n" $message += "🕐 Время отчета: $(Get-Date -Format 'dd.MM.yyyy HH:mm:ss')`r`n"
$message += "Active sessions: $count`r`n" $message += "👥 Активных сессий (quser): $count`r`n"
if ($uniqueUsers.Count -gt 0) { if ($uniqueUsers.Count -gt 0) {
$message += "`r`n<b>Unique logon names ($($uniqueUsers.Count)):</b>`r`n" $message += "`r`n<b>Уникальные логины ($($uniqueUsers.Count)):</b>`r`n"
foreach ($name in $uniqueUsers) { foreach ($name in $uniqueUsers) {
$safe = [System.Net.WebUtility]::HtmlEncode($name) $safe = [System.Net.WebUtility]::HtmlEncode($name)
$message += " - $safe`r`n" $message += " $safe`r`n"
} }
} else { } else {
$message += "`r`n<i>User list not available (quser empty or insufficient rights).</i>" $message += "`r`n<i>Список пользователей недоступен (quser пуст или недостаточно прав).</i>"
} }
Send-TelegramMessage -Message $message | Out-Null Send-TelegramMessage -Message $message | Out-Null
Write-TextFileUtf8Bom -Path $LastReportFile -Text ((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) Write-TextFileUtf8Bom -Path $LastReportFile -Text ((Get-Date).ToString("yyyy-MM-dd HH:mm:ss"))
Write-Log "Daily report sent to Telegram" Write-Log "Ежедневный отчет отправлен"
return $true return $true
} catch { } catch {
Write-Log "Daily report error: $($_.Exception.Message)" Write-Log "Ошибка ежедневного отчета: $($_.Exception.Message)"
return $false return $false
} }
} }
@@ -869,8 +874,8 @@ function Start-LoginMonitor {
) )
Write-Log "========================================" Write-Log "========================================"
Write-Log "Starting login event monitor" Write-Log "Запуск мониторинга логинов"
Write-Log "Monitoring logon types: 2,3,10 (when not in monitor-all mode)" Write-Log "Интерактивные типы: 2,3,10"
Write-Log "========================================" Write-Log "========================================"
Cleanup-OldLogs Cleanup-OldLogs
@@ -981,7 +986,7 @@ function Start-LoginMonitor {
$nextReportCheck = Check-AndSendDailyReport $nextReportCheck = Check-AndSendDailyReport
} }
} catch { } catch {
Write-Log "Monitor loop error: $($_.Exception.Message)" Write-Log "Ошибка цикла мониторинга: $($_.Exception.Message)"
} }
Start-Sleep -Seconds $MonitorInterval Start-Sleep -Seconds $MonitorInterval
} }
@@ -992,13 +997,13 @@ try {
Test-TelegramConnection | Out-Null Test-TelegramConnection | Out-Null
Start-LoginMonitor -MonitorInterval 5 -MonitorInteractiveOnly Start-LoginMonitor -MonitorInterval 5 -MonitorInteractiveOnly
} catch { } catch {
Write-Log "Fatal error: $($_.Exception.Message)" Write-Log "Критическая ошибка: $($_.Exception.Message)"
Send-StopNotification -Reason "Fatal error: $($_.Exception.Message)" Send-StopNotification -Reason "Критическая ошибка: $($_.Exception.Message)"
$script:StopNotificationSent = $true $script:StopNotificationSent = $true
throw throw
} finally { } finally {
if (-not $script:StopNotificationSent) { if (-not $script:StopNotificationSent) {
Send-StopNotification -Reason "Script exited" Send-StopNotification -Reason "Скрипт завершил работу"
} }
} }