提交 04eb0502 authored 作者: 陈泽健's avatar 陈泽健

fix(edit):补充钉钉对接通知发送,远程自动化部署实现,PRD文档增加约束描述。

上级 9f8a1cb0
# Complete Acceptance Test Script
$PlinkPath = "E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
function Invoke-SSH {
param([string]$Command)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw Ubains@123 -P 22 root@192.168.5.52 $Command"
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null
$p.WaitForExit(120000)
return $p.StandardOutput.ReadToEnd()
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Complete Acceptance Test" -ForegroundColor Cyan
Write-Host "Server: 192.168.5.52" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Test 1: Container Status
Write-Host "Test 1: Container Status Check" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
$containers = Invoke-SSH -Command "docker ps --format 'table {{.Names}}\t{{.Status}}'"
Write-Host $containers
Write-Host ""
# Test 2: External Service Log Check
Write-Host "Test 2: External Service Log (SYSTEMVERSION Check)" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
$extApiLog = Invoke-SSH -Command "tail -100 /data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"
if ($extApiLog -match "SYSTEMVERSION :: target_api_integration") {
Write-Host "✅ External service log: SYSTEMVERSION found - PASS" -ForegroundColor Green
} else {
Write-Host "⚠️ External service log: SYSTEMVERSION not found - checking again in 10 min..." -ForegroundColor Yellow
Start-Sleep -Seconds 600
$extApiLogRetry = Invoke-SSH -Command "tail -100 /data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"
if ($extApiLogRetry -match "SYSTEMVERSION") {
Write-Host "✅ External service log: SYSTEMVERSION found (after retry) - PASS" -ForegroundColor Green
} else {
Write-Host "❌ External service log: SYSTEMVERSION not found - FAIL" -ForegroundColor Red
Write-Host "Last log lines:" -ForegroundColor Gray
Write-Host $extApiLogRetry
}
}
Write-Host ""
# Test 3: API Endpoint Tests
Write-Host "Test 3: Service API Endpoint Tests" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
$apiTests = @{
"ExtAPI" = @{URL = "https://192.168.5.52/exapi/message/getMsgPageList"; Expected = "A0076"}
"Meeting" = @{URL = "https://192.168.5.52/meetingV3/api/systemConfiguration/globalConfig?companyNumber=CN-SZ-00-0201"; Expected = "A0078"}
"Monitor" = @{URL = "https://192.168.5.52/monitor/api2/api/servermonitor/"; Expected = "40000014"}
"Voice" = @{URL = "https://192.168.5.52/voice/api/iflytek/roommaster?company_id=1&user_id=8&company_secret=57d00f9f-020f-5f1f-b788-55fae843bceb&getall=1"; Expected = "40000003"}
}
foreach ($api in $apiTests.Keys) {
$test = $apiTests[$api]
Write-Host "Testing $api..." -ForegroundColor Cyan
$result = Invoke-SSH -Command "curl -k '$($test.URL)' 2>/dev/null"
if ($result -match $test.Expected) {
Write-Host "✅ $api: PASS" -ForegroundColor Green
} elseif ($result -match "nginx|Error") {
Write-Host "❌ $api: FAIL (nginx error page)" -ForegroundColor Red
} else {
Write-Host "⚠️ $api: UNKNOWN RESPONSE" -ForegroundColor Yellow
}
}
Write-Host ""
# Test 4: Service Status Summary
Write-Host "Test 4: Service Status Summary" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
$javaProcesses = Invoke-SSH -Command "ps aux | grep java | grep -v grep | wc -l"
$pythonProcesses = Invoke-SSH -Command "ps aux | grep 'python.*uwsgi\|python.*httpd' | grep -v grep | wc -l"
Write-Host "Java processes: $($javaProcesses.Trim())" -ForegroundColor Cyan
Write-Host "Python service processes: $($pythonProcesses.Trim())" -ForegroundColor Cyan
# Check specific services
$services = @(
@{Name = "ExtAPI"; Path = "/data/services/api/java-meeting/java-meeting-extapi"},
@{Name = "InnerAPI"; Path = "/data/services/api/java-meeting/java-meeting2.0"},
@{Name = "Monitor"; Path = "/data/services/api/python-cmdb"},
@{Name = "Voice"; Path = "/data/services/api/python-voice"}
)
foreach ($svc in $services) {
$exists = Invoke-SSH -Command "test -d '$($svc.Path)' && echo 'exists' || echo 'not_found'"
if ($exists -match "exists") {
Write-Host "✅ $($svc.Name): Directory exists" -ForegroundColor Green
} else {
Write-Host "❌ $($svc.Name): Directory not found" -ForegroundColor Red
}
}
Write-Host ""
# Final Summary
Write-Host "========================================" -ForegroundColor Green
Write-Host "Acceptance Test Summary" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Next Steps:" -ForegroundColor Yellow
Write-Host "1. System Authorization: https://192.168.5.52/#/LoginConfig" -ForegroundColor Gray
Write-Host " Verification code: csba" -ForegroundColor Gray
Write-Host " License file: E:\自动化部署\X86-5.52\license.zip" -ForegroundColor Gray
Write-Host ""
Write-Host "2. Create Company Admin: https://192.168.5.52/#/LoginAdmin" -ForegroundColor Gray
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
# Monitor All Systems Deployment
$PlinkPath = "E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Monitoring All Systems Deployment" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
function Invoke-SSH {
param([string]$Command)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw Ubains@123 -P 22 root@192.168.5.52 $Command"
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null
$p.WaitForExit(60000)
return $p.StandardOutput.ReadToEnd()
}
# Check if deployment script is still running
$running = Invoke-SSH -Command "ps aux | grep deploy_all_complete | grep -v grep | wc -l"
if ($running.Trim() -eq "1") {
Write-Host "Deployment Status: RUNNING" -ForegroundColor Green
Write-Host ""
# Show recent log lines
Write-Host "Recent deployment log:" -ForegroundColor Gray
Write-Host "========================================" -ForegroundColor Gray
$log = Invoke-SSH -Command "tail -30 /data/offline_auto_unifiedPlatform/new_auto_script.log 2>/dev/null || tail -30 /var/log/deploy/deploy.log 2>/dev/null || echo 'Log not available'"
Write-Host $log
} else {
Write-Host "Deployment Status: COMPLETED or NOT RUNNING" -ForegroundColor Yellow
Write-Host ""
# Show full log
Write-Host "Full deployment log:" -ForegroundColor Gray
Write-Host "========================================" -ForegroundColor Gray
$log = Invoke-SSH -Command "tail -100 /data/offline_auto_unifiedPlatform/new_auto_script.log 2>/dev/null || tail -100 /var/log/deploy/deploy.log 2>/dev/null"
Write-Host $log
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Gray
Write-Host "Services Status:" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
# Check Docker containers
$docker = Invoke-SSH -Command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>/dev/null || echo 'Docker not available'"
Write-Host $docker
Write-Host ""
Write-Host "========================================" -ForegroundColor Gray
Write-Host "Java Services:" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
# Check Java processes
$java = Invoke-SSH -Command "ps aux | grep java | grep -v grep | wc -l"
Write-Host "Total Java processes: $($java.Trim())" -ForegroundColor Cyan
Write-Host ""
Write-Host "========================================" -ForegroundColor Gray
Write-Host "Quick Commands:" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Gray
Write-Host "SSH to server: ssh root@192.168.5.52" -ForegroundColor White
Write-Host "Monitor deployment log: tail -f /data/offline_auto_unifiedPlatform/new_auto_script.log" -ForegroundColor White
Write-Host "Check services: docker ps" -ForegroundColor White
Write-Host "========================================" -ForegroundColor Gray
# Re-run Deployment Script with Full System Selection
$PlinkPath = "E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Re-running Deployment with System Selection" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "This will connect to the server and run the deployment script interactively." -ForegroundColor Yellow
Write-Host "When prompted to select systems, please choose '全部系统' (All Systems)" -ForegroundColor Yellow
Write-Host ""
Write-Host "Press Enter to continue..." -ForegroundColor Gray
Read-Host
Write-Host ""
Write-Host "Connecting to server 192.168.5.52..." -ForegroundColor Cyan
Write-Host "You will be prompted for deployment options in the SSH session." -ForegroundColor Yellow
Write-Host ""
# Start interactive SSH session
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw Ubains@123 -P 22 root@192.168.5.52"
$psi.UseShellExecute = $true
$psi.RedirectStandardOutput = $false
$psi.RedirectStandardError = $false
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null
$p.WaitForExit()
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "SSH session completed" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
# DingTalk Notification Module
# UTF-8 BOM encoding required
$ScriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }
function Get-DingTalkConfig {
param([string]$ConfigPath = (Join-Path $ScriptRoot "config.json"))
if (-not (Test-Path $ConfigPath)) {
Write-Host "ERROR: Config not found: $ConfigPath" -ForegroundColor Red
throw "Config not found"
}
$config = Get-Content $ConfigPath -Raw | ConvertFrom-Json
Write-Host "INFO: Config loaded" -ForegroundColor Green
return $config
}
function Start-ReportHttpServer {
param([string]$ReportDir, [int]$Port)
try {
if (-not (Test-Path $ReportDir)) {
New-Item -ItemType Directory -Path $ReportDir -Force | Out-Null
Write-Host "INFO: Created report dir: $ReportDir" -ForegroundColor Green
}
$existingProcess = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue | Where-Object State -eq "Listen"
if ($existingProcess) {
Write-Host "INFO: HTTP server already running on port $Port" -ForegroundColor Yellow
return $true
}
$process = Start-Process -FilePath "python3" -ArgumentList "-m http.server $Port --directory $ReportDir" -WindowStyle Hidden -PassThru
Start-Sleep -Seconds 2
if ($process.HasExited) {
Write-Host "ERROR: HTTP server failed to start" -ForegroundColor Red
return $false
}
Write-Host "INFO: HTTP server started: http://localhost:$Port" -ForegroundColor Green
return $true
}
catch {
Write-Host "ERROR: Start HTTP server failed: $_" -ForegroundColor Red
return $false
}
}
function Get-NgrokPublicUrl {
param([string]$NgrokPath, [int]$Port)
try {
$ngrokApiUrl = "http://localhost:4040/api/tunnels"
try {
$tunnels = Invoke-RestMethod -Uri $ngrokApiUrl -ErrorAction Stop
$existingTunnel = $tunnels.tunnels | Where-Object { $_.config.addr -eq "http://localhost:$Port" }
if ($existingTunnel) {
Write-Host "INFO: ngrok tunnel exists: $($existingTunnel.public_url)" -ForegroundColor Yellow
return $existingTunnel.public_url
}
}
catch {
Write-Host "INFO: ngrok not running, starting new tunnel" -ForegroundColor Yellow
}
if (-not (Test-Path $NgrokPath)) {
Write-Host "ERROR: ngrok not found: $NgrokPath" -ForegroundColor Red
return $null
}
Start-Process -FilePath $NgrokPath -ArgumentList "http $Port --log=stdout" -WindowStyle Hidden
Start-Sleep -Seconds 3
$tunnels = Invoke-RestMethod -Uri $ngrokApiUrl
$publicUrl = $tunnels.tunnels[0].public_url
Write-Host "INFO: ngrok tunnel created: $publicUrl" -ForegroundColor Green
return $publicUrl
}
catch {
Write-Host "ERROR: Get ngrok URL failed: $_" -ForegroundColor Red
return $null
}
}
function New-DingTalkSignature {
param([string]$Secret, [long]$Timestamp)
try {
# Step 1: timestamp + \n + secret
$stringToSign = "$Timestamp`n$Secret"
# Step 2: HMAC-SHA256
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.Key = [System.Text.Encoding]::UTF8.GetBytes($Secret)
$signatureBytes = $hmacsha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($stringToSign))
# Step 3: Base64 encode
$base64Signature = [Convert]::ToBase64String($signatureBytes)
# Step 4: URL encode
$urlEncodedSign = [System.Uri]::EscapeDataString($base64Signature)
Write-Host "DEBUG: timestamp=$Timestamp" -ForegroundColor DarkGray
Write-Host "DEBUG: stringToSign=$stringToSign" -ForegroundColor DarkGray
Write-Host "DEBUG: sign=$urlEncodedSign" -ForegroundColor DarkGray
return $urlEncodedSign
}
catch {
Write-Host "ERROR: Generate signature failed: $_" -ForegroundColor Red
return $null
}
}
function Send-DingTalkMessage {
param([string]$Webhook, [string]$Secret, [string]$Title, [string]$Content)
try {
$timestamp = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
$sign = New-DingTalkSignature -Secret $Secret -Timestamp $timestamp
$body = @{
msgtype = "markdown"
markdown = @{
title = $Title
text = $Content
}
} | ConvertTo-Json -Depth 10
$url = "$Webhook&timestamp=$timestamp&sign=$sign"
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType "application/json" -TimeoutSec 10
if ($response.errcode -eq 0) {
Write-Host "INFO: DingTalk message sent successfully" -ForegroundColor Green
return $true
}
else {
Write-Host "ERROR: DingTalk message failed: $($response.errmsg)" -ForegroundColor Red
return $false
}
}
catch {
Write-Host "ERROR: Send DingTalk message exception: $_" -ForegroundColor Red
return $false
}
}
function Clear-ExpiredReports {
param([string]$ReportDir, [int]$Days)
try {
if (-not (Test-Path $ReportDir)) {
return
}
$expiredDate = (Get-Date).AddDays(-$Days)
$expiredFiles = Get-ChildItem -Path $ReportDir -Filter "*.md" | Where-Object { $_.LastWriteTime -lt $expiredDate }
foreach ($file in $expiredFiles) {
Remove-Item $file.FullName -Force
Write-Host "INFO: Deleted expired report: $($file.Name)" -ForegroundColor Yellow
}
if ($expiredFiles.Count -gt 0) {
Write-Host "INFO: Deleted $($expiredFiles.Count) expired reports" -ForegroundColor Green
}
}
catch {
Write-Host "ERROR: Clear expired reports failed: $_" -ForegroundColor Red
}
}
function Send-DingTalkReport {
param(
[string]$Summary,
[string]$FullReportPath,
[string]$ServerName,
[string]$ConfigPath = (Join-Path $ScriptRoot "config.json")
)
try {
$config = Get-DingTalkConfig -ConfigPath $ConfigPath
$displayName = if ($ServerName) { $ServerName } else { $config.ServerName }
$finalContent = $Summary
if ($FullReportPath -and (Test-Path $FullReportPath)) {
$reportUrl = $null
if ($config.EnableHttpServer) {
Start-ReportHttpServer -ReportDir $config.ReportDir -Port $config.HttpPort | Out-Null
}
if ($config.EnableNgrok) {
$publicUrl = Get-NgrokPublicUrl -NgrokPath $config.NgrokPath -Port $config.HttpPort
if ($publicUrl) {
$reportName = Split-Path $FullReportPath -Leaf
$reportUrl = "$publicUrl/$reportName"
}
}
if (-not $reportUrl) {
$reportName = Split-Path $FullReportPath -Leaf
$reportUrl = "file://$FullReportPath"
}
$finalContent = "$Summary`n`n---`n`n#### Report: [$reportName]($reportUrl)"
}
$title = "Server Health Report - $displayName"
$result = Send-DingTalkMessage -Webhook $config.Webhook -Secret $config.Secret -Title $title -Content $finalContent
Clear-ExpiredReports -ReportDir $config.ReportDir -Days $config.ReportRetentionDays
return $result
}
catch {
Write-Host "ERROR: Send DingTalk report failed: $_" -ForegroundColor Red
return $false
}
}
Export-ModuleMember -Function @('Get-DingTalkConfig', 'Start-ReportHttpServer', 'Get-NgrokPublicUrl', 'Send-DingTalkMessage', 'Send-DingTalkReport', 'Clear-ExpiredReports')
# 钉钉通知通用模块
为服务器监测脚本提供统一的钉钉消息通知功能,支持摘要消息和完整报告链接。
## 功能特性
-**钉钉机器人集成**:支持加签验证的钉钉自定义机器人
-**Markdown格式**:支持发送Markdown格式的结构化消息
-**HTTP报告托管**:自动启动HTTP服务器托管报告文件
-**ngrok隧道**:自动建立公网访问隧道(可选)
-**自动清理**:自动清理过期报告文件
-**多项目支持**:支持通过不同配置文件管理多个项目
## 目录结构
```
钉钉通知/
├── config.json # 配置文件(钉钉webhook、密钥、端口等)
├── DingTalkHelper.psm1 # 核心模块(所有功能函数)
├── 使用示例.ps1 # 使用示例代码
└── README.md # 本文档
```
## 快速开始
### 1. 配置文件修改
编辑 `config.json`,修改相关配置:
```json
{
"Webhook": "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
"Secret": "SECYOUR_SECRET",
"HttpPort": 8080,
"NgrokPath": "/usr/local/bin/ngrok",
"ReportDir": "/root/reports",
"ReportRetentionDays": 30,
"ServerName": "服务器巡检",
"EnableHttpServer": true,
"EnableNgrok": true
}
```
### 2. 基础调用
```powershell
# 导入模块
Import-Module "Docs\PRD\AI服务器监测\通用模块\钉钉通知\DingTalkHelper.psm1"
# 准备摘要
$summary = @"
### 🖥️ 服务器巡检报告
**时间**: 2026-05-15 10:30:00
**状态**: 🟢 正常
#### 📊 核心指标
| 指标 | 当前 | 状态 |
|:---|:---|:---|
| CPU | 45% | 🟢 |
| 内存 | 62% | 🟢 |
"@
# 发送通知
Send-DingTalkReport -Summary $summary
```
### 3. 发送摘要+报告链接
```powershell
# 生成完整报告
$reportPath = "/root/reports/health_20260515.md"
$fullReport | Out-File -FilePath $reportPath -Encoding UTF8
# 发送通知(自动生成公网链接)
Send-DingTalkReport -Summary $summary -FullReportPath $reportPath
```
## 函数说明
### Send-DingTalkReport
主函数,发送钉钉通知。
**参数:**
- `Summary` (必填):摘要内容(Markdown格式)
- `FullReportPath` (可选):完整报告文件路径
- `ServerName` (可选):服务器名称,覆盖配置中的默认值
- `ConfigPath` (可选):配置文件路径
**示例:**
```powershell
Send-DingTalkReport -Summary $summary
Send-DingTalkReport -Summary $summary -FullReportPath "/root/reports/health.md"
Send-DingTalkReport -Summary $summary -FullReportPath "/root/reports/health.md" -ServerName "生产环境"
```
### 其他函数
- `Get-DingTalkConfig`:加载配置文件
- `Start-ReportHttpServer`:启动HTTP服务器
- `Get-NgrokPublicUrl`:获取ngrok公网URL
- `Send-DingTalkMessage`:发送原始钉钉消息
- `Clear-ExpiredReports`:清理过期报告
## 多项目配置
为不同项目创建独立的配置文件:
```
config.json # 默认配置
大亚湾中广核_config.json # 项目A配置
兰州中石化_config.json # 项目B配置
```
调用时指定配置路径:
```powershell
Send-DingTalkReport -Summary $summary -ConfigPath "大亚湾中广核_config.json"
```
## 钉钉消息格式示例
```
### 🖥️ 服务器巡检报告 - 大亚湾中广核
**时间**: 2026-05-15 10:30:00
**状态**: ⚠️ 警告 (3警告, 1严重)
#### 📊 核心指标
| 指标 | 当前 | 阈值 | 状态 |
|:---|:---|:---|:---|
| CPU使用率 | 82% | 85% | 🟡 |
| 内存使用率 | 91% | 85% | 🔴 |
| 磁盘使用率 | 78% | 90% | 🟢 |
#### 🚨 严重问题
- 内存使用率过高 91% (阈值85%)
- MySQL慢查询 12.5万 (阈值100)
#### 📋 AI分析建议
1. 建议排查内存占用高的进程
2. 优化MySQL慢查询语句
---
#### 📄 [点击查看完整报告](https://xxx.ngrok.io/health_20260515.md)
**报告文件**: `health_20260515.md`
**服务器**: `大亚湾中广核`
```
## 注意事项
1. **ngrok限制**:免费版URL每次重启会变化,建议付费版固定域名
2. **端口占用**:确保配置的HTTP端口未被占用
3. **报告目录**:确保报告目录有写入权限
4. **网络访问**:确保服务器能访问钉钉API和ngrok服务
5. **时间同步**:服务器时间不准确可能导致签名验证失败
## 依赖要求
- PowerShell 5.1 或更高版本
- Python 3(用于HTTP服务器)
- ngrok(可选,用于公网访问)
## 许可
本模块为内部工具,仅供公司内部使用。
{
"Webhook": "https://oapi.dingtalk.com/robot/send?access_token=27071a77f20da381e9a321653ec5f4dcf668bcf058c01162f28e3f1f8633386d",
"Secret": "SEC5d85d5735a1805ada1be84929d5b37f5b72a2a832a6bcd9a1ca5615e5799be38",
"HttpPort": 8080,
"NgrokPath": "/usr/local/bin/ngrok",
"ReportDir": "/root/reports",
"ReportRetentionDays": 30,
"ServerName": "服务器巡检",
"EnableHttpServer": true,
"EnableNgrok": true
}
# Test DingTalk Notification
Import-Module .\DingTalkHelper.psm1 -Force
$summary = @"
### 服务器巡检报告 - 兰州中石化
**时间**: 2026-05-15 06:23:04
**主机**: 139.159.163.86
**状态**: ⚠️ 警告 (0严重, 3警告)
#### 📊 核心指标
| 指标 | 当前值 | 阈值 | 状态 |
|:---|:---|:---|:---|
| CPU使用率 | 1.1% | 85% | ✅ |
| 内存使用率 | 78.7% | 85% | ✅ |
| Swap使用率 | 1.4% | - | ⚠️ |
| 磁盘使用率 | 66.0% | 90% | ✅ |
| 线程总数 | 1443 | 1000 | ⚠️ |
#### ⚠️ 警告项
- Swap已使用: 1.4%
- 总线程数: 1443 (阈值1000)
- Redis缓存命中率: 58.0%
#### 🤖 AI分析建议
1. 线程数偏高,建议排查是否有线程泄漏
2. Redis缓存命中率偏低,建议检查缓存策略
"@
$fullReportPath = "E:\GithubData\ubains-module-test\Docs\PRD\AI服务器监测\分析报告\预定项目\兰州中石化\巡检报告_20260515_062304.md"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "DingTalk Test Message" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Report: $fullReportPath" -ForegroundColor Yellow
Write-Host ""
Write-Host "Sending DingTalk message..." -ForegroundColor Cyan
$result = Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath -ServerName "Lanzhou"
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
if ($result) {
Write-Host "SUCCESS: Message sent to DingTalk!" -ForegroundColor Green
} else {
Write-Host "FAILED: Message not sent" -ForegroundColor Red
}
Write-Host "========================================" -ForegroundColor Cyan
# DingTalk Notification Test
$modulePath = "E:\GithubData\ubains-module-test\Docs\PRD\AI服务器监测\通用模块\钉钉通知\DingTalkHelper.psm1"
Import-Module $modulePath -Force
$fullReportPath = "E:\GithubData\ubains-module-test\Docs\PRD\AI服务器监测\分析报告\预定项目\兰州中石化\巡检报告_20260515_062304.md"
$summary = @"
### Server Health Report - Lanzhou
**Time**: 2026-05-15 06:23:04
**Host**: 139.159.163.86
**Status**: Warning (0 Critical, 3 Warnings)
#### Metrics
| Metric | Value | Threshold | Status |
|:---|:---|:---|:---|
| CPU | 1.1% | 85% | OK |
| Memory | 78.7% | 85% | OK |
| Swap | 1.4% | - | WARN |
| Disk | 66.0% | 90% | OK |
| Threads | 1443 | 1000 | WARN |
#### Warnings
- Swap in use: 1.4%
- Thread count: 1443 (limit 1000)
- Redis cache hit ratio: 58.0%
#### Database
- MySQL connections: 15/151 (9.9%)
- Slow queries: 0
- Database size: 1433.16 MB
"@
Write-Host "Sending DingTalk message..." -ForegroundColor Cyan
try {
$result = Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath -ServerName "Lanzhou"
if ($result) {
Write-Host "SUCCESS: Message sent!" -ForegroundColor Green
} else {
Write-Host "FAILED: Message not sent" -ForegroundColor Red
}
} catch {
Write-Host "ERROR: $_" -ForegroundColor Red
}
# Simple test without signature
$webhook = "https://oapi.dingtalk.com/robot/send?access_token=27071a77f20da381e9a321653ec5f4dcf668bcf058c01162f28e3f1f8633386d"
$body = @{
msgtype = "text"
text = @{
content = "Test message without signature"
}
} | ConvertTo-Json -Depth 10
Write-Host "Sending simple test message..." -ForegroundColor Cyan
Write-Host "Webhook: $webhook" -ForegroundColor Yellow
try {
$response = Invoke-RestMethod -Uri $webhook -Method Post -Body $body -ContentType "application/json" -TimeoutSec 10
Write-Host "Response: $($response | ConvertTo-Json)" -ForegroundColor Green
if ($response.errcode -eq 0) {
Write-Host "SUCCESS!" -ForegroundColor Green
} else {
Write-Host "FAILED: errcode=$($response.errcode), errmsg=$($response.errmsg)" -ForegroundColor Red
}
} catch {
Write-Host "ERROR: $_" -ForegroundColor Red
}
# 钉钉通知通用模块 - 使用示例
# 说明:此脚本展示如何在不同服务器监测场景中使用钉钉通知模块
# ===================================================================
# 方式一:基础调用 - 仅发送摘要消息
# ===================================================================
# 导入模块
$modulePath = "Docs\PRD\AI服务器监测\通用模块\钉钉通知\DingTalkHelper.psm1"
Import-Module $modulePath -Force
# 准备摘要内容
$summary = @"
### 🖥️ 服务器巡检报告 - 大亚湾中广核
**时间**: 2026-05-15 10:30:00
**状态**: ⚠️ 警告 (3警告, 1严重)
#### 📊 核心指标
| 指标 | 当前 | 阈值 | 状态 |
|:---|:---|:---|:---|
| CPU使用率 | 82% | 85% | 🟡 |
| 内存使用率 | 91% | 85% | 🔴 |
| 磁盘使用率 | 78% | 90% | 🟢 |
| 系统负载 | 6.5 | 8 | 🟢 |
#### 🚨 严重问题
- 内存使用率过高 91% (阈值85%)
- MySQL慢查询 12.5万 (阈值100)
#### 📋 AI分析建议
1. 建议排查内存占用高的进程
2. 优化MySQL慢查询语句
"@
# 发送通知(仅摘要)
Send-DingTalkReport -Summary $summary
# ===================================================================
# 方式二:发送摘要 + 完整报告链接
# ===================================================================
# 假设已生成完整报告文件
$fullReportPath = "/root/reports/health_20260515_103000.md"
# 发送通知(摘要+链接)
Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath
# ===================================================================
# 方式三:自定义服务器名称
# ===================================================================
Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath -ServerName "生产环境-MySQL主库"
# ===================================================================
# 方式四:自定义配置文件路径
# ===================================================================
# 为不同项目使用不同配置
$configPath = "Docs\PRD\AI服务器监测\预定项目\大亚湾中广核项目\dingtalk_config.json"
Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath -ConfigPath $configPath
# ===================================================================
# 完整示例:服务器巡检脚本集成
# ===================================================================
function Invoke-ServerHealthCheck {
param(
[string]$ServerName = "未命名服务器",
[string]$ConfigPath = "Docs\PRD\AI服务器监测\通用模块\钉钉通知\config.json"
)
Write-Host "开始服务器巡检: $ServerName" -ForegroundColor Cyan
# 1. 执行巡检逻辑(这里用模拟数据)
$healthData = @{
CPUPercent = 82
MemoryPercent = 91
DiskPercent = 78
LoadAverage = 6.5
SlowQueries = 125000
}
# 2. 判断状态
$criticalIssues = @()
$warnings = @()
if ($healthData.MemoryPercent -gt 85) {
$criticalIssues += "内存使用率过高 $($healthData.MemoryPercent)%"
}
if ($healthData.SlowQueries -gt 100) {
$criticalIssues += "MySQL慢查询 $($healthData.SlowQueries)"
}
$status = switch ($criticalIssues.Count) {
{ $_ -eq 0 } { "🟢 正常" }
{ $_ -le 2 } { "🟡 警告" }
default { "🔴 严重" }
}
# 3. 生成摘要
$summary = @"
### 🖥️ 服务器巡检报告 - $ServerName
**时间**: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
**状态**: $status
#### 📊 核心指标
| 指标 | 当前 | 阈值 | 状态 |
|:---|:---|:---|:---|
| CPU使用率 | $($healthData.CPUPercent)% | 85% | $(if($healthData.CPUPercent -gt 85){'🔴'}elseif($healthData.CPUPercent -gt 70){'🟡'}else{'🟢'}) |
| 内存使用率 | $($healthData.MemoryPercent)% | 85% | $(if($healthData.MemoryPercent -gt 85){'🔴'}elseif($healthData.MemoryPercent -gt 70){'🟡'}else{'🟢'}) |
| 磁盘使用率 | $($healthData.DiskPercent)% | 90% | $(if($healthData.DiskPercent -gt 90){'🔴'}elseif($healthData.DiskPercent -gt 80){'🟡'}else{'🟢'}) |
| 系统负载 | $($healthData.LoadAverage) | 8 | $(if($healthData.LoadAverage -gt 16){'🔴'}elseif($healthData.LoadAverage -gt 8){'🟡'}else{'🟢'}) |
$(if($criticalIssues){@"
#### 🚨 严重问题
$($criticalIssues | ForEach-Object { "- $_" } | Out-String)
"@})
$(if($warnings){@"
#### ⚠️ 警告
$($warnings | ForEach-Object { "- $_" } | Out-String)
"@})
#### 📋 AI分析建议
1. $(if($healthData.MemoryPercent -gt 85){"建议排查内存占用高的进程,考虑优化或增加内存"}else{"内存使用正常"})
2. $(if($healthData.SlowQueries -gt 100){"优化MySQL慢查询语句,检查索引是否合理"}else{"数据库性能正常"})
"@
# 4. 生成完整报告(模拟)
$reportDir = "/root/reports"
$reportFileName = "health_$(Get-Date -Format 'yyyyMMdd_HHmmss').md"
$reportPath = Join-Path $reportDir $reportFileName
# 确保目录存在
if (-not (Test-Path $reportDir)) {
New-Item -ItemType Directory -Path $reportDir -Force | Out-Null
}
# 保存完整报告(这里用摘要代替,实际应包含完整数据)
$fullReport = @"
# 服务器全深入巡检报告
$summary
## 详细数据
- [此处为完整巡检数据]
- [包含所有120+检测点的详细信息]
"@
$fullReport | Out-File -FilePath $reportPath -Encoding UTF8
Write-Host "完整报告已保存: $reportPath" -ForegroundColor Green
# 5. 发送钉钉通知
Write-Host "发送钉钉通知..." -ForegroundColor Cyan
$result = Send-DingTalkReport -Summary $summary -FullReportPath $reportPath -ServerName $ServerName
if ($result) {
Write-Host "钉钉通知发送成功!" -ForegroundColor Green
}
else {
Write-Host "钉钉通知发送失败!" -ForegroundColor Red
}
return $result
}
# 执行巡检
Invoke-ServerHealthCheck -ServerName "大亚湾中广核"
# ===================================================================
# 批量巡检多个服务器
# ===================================================================
$servers = @(
@{ Name = "大亚湾中广核"; IP = "192.168.5.61" },
@{ Name = "兰州中石化"; IP = "192.168.1.100" },
@{ Name = "PXX项目"; IP = "192.168.2.50" }
)
foreach ($server in $servers) {
Write-Host "`n========== 巡检 $($server.Name) ==========" -ForegroundColor Magenta
Invoke-ServerHealthCheck -ServerName $server.Name
}
# 钉钉通知测试 - 使用真实报告
# 导入模块
$modulePath = "E:\GithubData\ubains-module-test\Docs\PRD\AI服务器监测\通用模块\钉钉通知\DingTalkHelper.psm1"
Import-Module $modulePath -Force
# 报告文件路径(Windows路径)
$fullReportPath = "E:\GithubData\ubains-module-test\Docs\PRD\AI服务器监测\分析报告\预定项目\兰州中石化\巡检报告_20260515_062304.md"
# 准备摘要内容(从报告中提取关键信息)
$summary = @"
### 🖥️ 服务器巡检报告 - 兰州中石化
**时间**: 2026-05-15 06:23:04
**主机**: 139.159.163.86 (kunpeng)
**状态**: ⚠️ 警告 (0严重, 3警告)
#### 📊 核心指标
| 指标 | 当前值 | 阈值 | 状态 |
|:---|:---|:---|:---|
| CPU使用率 | 1.1% | 85% | ✅ |
| 内存使用率 | 78.7% | 85% | ✅ |
| Swap使用率 | 1.4% | - | ⚠️ |
| 磁盘使用率 | 66.0% | 90% | ✅ |
| 线程总数 | 1443 | 1000 | ⚠️ |
| 系统负载 | 0.0 | 8 | ✅ |
#### ⚠️ 警告项
- Swap已使用: 1.4%
- 总线程数: 1443 (阈值1000)
- Redis缓存命中率: 58.0%
#### 📋 数据库状态
- MySQL连接: 15/151 (9.9%)
- 慢查询数: 0
- 数据库大小: 1433.16 MB (ubains库)
#### 🤖 AI分析建议
1. 线程数偏高,建议排查是否有线程泄漏
2. Redis缓存命中率偏低,建议检查缓存策略
3. 内存使用率78.7%,接近阈值,需关注
"@
# 发送钉钉通知
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "钉钉通知测试" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "报告文件: $fullReportPath" -ForegroundColor Yellow
Write-Host "服务器名称: 兰州中石化" -ForegroundColor Yellow
Write-Host ""
# 检查报告文件是否存在
if (Test-Path $fullReportPath) {
Write-Host "✅ 报告文件存在" -ForegroundColor Green
}
else {
Write-Host "❌ 报告文件不存在,仅发送摘要" -ForegroundColor Red
}
Write-Host ""
Write-Host "正在发送钉钉消息..." -ForegroundColor Cyan
try {
$result = Send-DingTalkReport -Summary $summary -FullReportPath $fullReportPath -ServerName "兰州中石化"
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
if ($result) {
Write-Host "✅ 钉钉消息发送成功!" -ForegroundColor Green
}
else {
Write-Host "❌ 钉钉消息发送失败!" -ForegroundColor Red
}
Write-Host "========================================" -ForegroundColor Cyan
}
catch {
Write-Host ""
Write-Host "❌ 发生异常: $_" -ForegroundColor Red
Write-Host "异常位置: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
}
# 角色 # 角色
你是一名资深的Linux系统运维专家,专注于会议预定系统的稳定性保障,擅长通过Shell/Python脚本进行服务器深度巡检和故障诊断。 你是一名资深的Linux系统运维专家,专注于会议预定系统的稳定性保障,擅长通过Shell/Python脚本进行服务器深度巡检和故障诊断。
# 钉钉通知对接
- 将分析报告以md形式调用钉钉机器人接口发送报告,并保存至服务器。
- 钉钉机器人:https://oapi.dingtalk.com/robot/send?access_token=27071a77f20da381e9a321653ec5f4dcf668bcf058c01162f28e3f1f8633386
- 钉钉机器人加签:SEC5d85d5735a1805ada1be84929d5b37f5b72a2a832a6bcd9a1ca5615e5799be38
- 接口文档参考:https://open.dingtalk.com/document/orgapp/custom-robots-send-group-messages#title-7fs-kgs-36x
# 目标服务器配置 # 目标服务器配置
- **主机地址**: 192.168.5.61 - **主机地址**: 192.168.5.61
- **SSH端口**: 22 - **SSH端口**: 22
......
...@@ -48,8 +48,13 @@ ...@@ -48,8 +48,13 @@
- 登录目标服务器,并切换到root用户。 - 登录目标服务器,并切换到root用户。
3. 部署执行 3. 部署执行
- 严格根据部署文档执行部署操作!!! - 严格根据部署文档执行部署操作!!!
- 如遇选择部署的系统,则选择全部系统,并执行部署操作。 - 如遇选择部署的系统,则选择全部系统,并执行部署操作。直接在交互式SSH会话中运行脚本,手动选择"全部系统"。
- 不要自己乱操作,严格按照文档操作执行即可。 - 不要自己乱操作,严格按照文档操作执行即可。
- 文档中明确标明超管账号密码为:superadmin Ubains@1357
- 授权文件上传操作,直接根据部署文档使用web界面的上传功能。
- 创建用户使用:
- 根据文档指引到指定页面创建管理员,公司选择名称为:“自动化”的公司,创建admin用户。
- 按照部署文档该等待的就等待,等待服务正常启动完成,再往下根据部署文档操作。不允许私自操作。
## 验收要求 ## 验收要求
1. 自动化部署完成后检查容器状态是否正常,核查容器日志是否正确。 1. 自动化部署完成后检查容器状态是否正常,核查容器日志是否正确。
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论