Windows服务监控与自动重启脚本

代码脚本 · Windows

监控Windows服务运行状态,异常时自动重启并发送邮件告警

详细内容

# ========================================== # Windows服务监控与自动重启脚本 # 用途:监控指定Windows服务状态,停止时自动重启并告警 # 使用方法: # 1. 修改 $services 数组 # 2. 以管理员身份运行: .\service_monitor.ps1 # 3. 可加入任务计划程序定时执行 # ========================================== # ========== 配置 ========== $services = @( "MySQL", "Nginx", "Spooler" # 在此添加要监控的服务名 ) $restartAttempts = 3 # 重启尝试次数 $restartInterval = 30 # 每次重启间隔(秒) $logFile = "C:\logs\service_monitor.log" # 邮件告警配置 $emailAlert = $false $smtpServer = "smtp.example.com" $smtpPort = 587 $smtpUser = "alert@example.com" $smtpPass = "your_password" $emailTo = "admin@example.com" # ========================== # 创建日志目录 $logDir = Split-Path $logFile -Parent if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } function Write-Log { param([string]$Message, [string]$Level = "INFO") $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logEntry = "[$timestamp] [$Level] $Message" Add-Content -Path $logFile -Value $logEntry Write-Host $logEntry } function Send-AlertEmail { param([string]$Subject, [string]$Body) if (-not $emailAlert) { return } try { $securePass = ConvertTo-SecureString $smtpPass -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($smtpUser, $securePass) Send-MailMessage -SmtpServer $smtpServer -Port $smtpPort -UseSsl ` -Credential $credential -From $smtpUser -To $emailTo ` -Subject $Subject -Body $Body -Encoding UTF8 Write-Log "告警邮件已发送" } catch { Write-Log "发送邮件失败: $_" "ERROR" } } Write-Log "========== 服务监控开始 ==========" $allOk = $true foreach ($svcName in $services) { $service = Get-Service -Name $svcName -ErrorAction SilentlyContinue if (-not $service) { Write-Log "服务 '$svcName' 不存在" "WARN" continue } Write-Log "检查服务: $svcName (状态: $($service.Status))" if ($service.Status -eq 'Running') { Write-Log " ✓ 服务运行正常" continue } $allOk = $false Write-Log " ✗ 服务未运行,尝试重启..." "WARN" # 发送告警邮件 Send-AlertEmail -Subject "【服务告警】$svcName 已停止" ` -Body "服务 $svcName 在 $(Get-Date) 检测到未运行,正在尝试自动重启。" # 尝试重启 $restarted = $false for ($i = 1; $i -le $restartAttempts; $i++) { Write-Log " 第 $i 次尝试重启..." try { Start-Service -Name $svcName -ErrorAction Stop Start-Sleep -Seconds 5 $check = Get-Service -Name $svcName if ($check.Status -eq 'Running') { Write-Log " ✓ 服务重启成功" $restarted = $true break } } catch { Write-Log " 重启失败: $_" "ERROR" } Start-Sleep -Seconds $restartInterval } if (-not $restarted) { Write-Log " ✗ 服务重启失败,已尝试 $restartAttempts 次" "ERROR" Send-AlertEmail -Subject "【严重告警】$svcName 重启失败" ` -Body "服务 $svcName 在尝试 $restartAttempts 次重启后仍未恢复,请人工介入处理。" } } if ($allOk) { Write-Log "所有服务运行正常" } Write-Log "========== 服务监控结束 =========="

适配环境

适配系统:Windows 10+,Windows Server 2016+

依赖环境:Windows PowerShell 5.1+

参数说明

[{"name": "services", "label": "\u670d\u52a1\u540d\u79f0\u5217\u8868(\u6bcf\u884c\u4e00\u4e2a)", "type": "textarea", "default": "MySQL"}, {"name": "restartAttempts", "label": "\u91cd\u542f\u5c1d\u8bd5\u6b21\u6570", "default": "3"}]
Windows服务监控

更多Windows