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

fix(add): 输出AI远程自动化部署需求文档执行远程上传部署

上级 41e1fdb3
@echo off
REM Accept SSH host key for remote server
REM Usage: accept_host_key.bat
setlocal enabledelayedexpansion
set SERVER_IP=192.168.5.52
set SSH_PORT=22
set USERNAME=root
set PASSWORD=Ubains@123
echo ========================================
echo Accepting SSH host key for %SERVER_IP%
echo ========================================
REM Use plink to accept host key (will prompt)
echo Please accept the host key when prompted...
echo.
plink.exe -pw %PASSWORD% -P %SSH_PORT% %USERNAME%@%SERVER_IP% echo "Host key accepted"
echo.
echo ========================================
echo Host key acceptance completed
echo ========================================
endlocal
#!/usr/bin/env pwsh
# ============================================================================
# 远程自动化部署脚本 - 新统一平台
# 功能:自动完成新统一平台的完整部署流程
# 作者:自动化运维团队
# 创建时间:2026-05-14
# ============================================================================
#Requires -Version 5.1
<#
.SYNOPSIS
新统一平台远程自动化部署脚本
.DESCRIPTION
本脚本用于自动完成新统一平台的部署,包括:
1. 部署包准备与上传
2. 自动化部署脚本执行
3. 服务状态检查
4. 接口验证测试
5. 部署报告生成
.PARAMETER ServerIP
目标服务器IP地址
.PARAMETER Architecture
服务器架构类型 (X86/ARM)
.EXAMPLE
.\auto_deploy.ps1 -ServerIP "192.168.5.52" -Architecture "X86"
#>
# ============================================================================
# 参数定义
# ============================================================================
param(
[Parameter(Mandatory=$false)]
[string]$ServerIP = "192.168.5.52",
[Parameter(Mandatory=$false)]
[ValidateSet("X86", "ARM")]
[string]$Architecture = "X86",
[Parameter(Mandatory=$false)]
[string]$Username = "root",
[Parameter(Mandatory=$false)]
[string]$Password = "Ubains@123",
[Parameter(Mandatory=$false)]
[int]$SSHPort = 22
)
# ============================================================================
# 脚本初始化
# ============================================================================
# 设置错误处理
$ErrorActionPreference = "Continue"
# 设置控制台输出编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
# 获取脚本根目录
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
# 定义目录路径
$PackagesDir = Join-Path $ScriptRoot "packages"
$ReportsDir = Join-Path $ScriptRoot "reports"
$TempDir = Join-Path $ScriptRoot "temp"
# 创建必要的目录结构
$Directories = @($PackagesDir, $ReportsDir, $TempDir)
foreach ($Dir in $Directories) {
if (-not (Test-Path $Dir)) {
New-Item -ItemType Directory -Path $Dir -Force | Out-Null
}
}
# 定义全局变量
$Global:SSHTimeout = 300 # SSH连接超时时间(秒)- 部署需要更长时间
$Global:MaxRetry = 3 # 最大重试次数
$Global:PlinkPath = Join-Path $ScriptRoot "plink.exe"
$Global:PscpPath = Join-Path $ScriptRoot "pscp.exe"
# 定义部署配置
$DeployConfig = @{
X86 = @{
NetworkShare = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\X86部署包\全量版'
LicenseFile = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\测试授权文件-请勿使用\5.52授权文件\license.zip'
DeployDoc = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\X86部署包\新统一平台自动化部署操作指导.docx'
}
ARM = @{
NetworkShare = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\ARM部署包-请勿使用'
LicenseFile = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\测试授权文件-请勿使用\9.76授权文件\license.zip'
DeployDoc = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\ARM部署包-请勿使用\新统一平台自动化部署操作指导.docx'
}
}
# 定义日志路径配置
$LogPaths = @{
ExtAPI = "/data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"
InnerAPI = "/data/services/api/java-meeting/java-meeting2.0/logs/ubains-INFO-AND-ERROR.log"
Monitor = "/data/services/api/python-cmdb/log/uinfo.log"
Voice = "/data/services/api/python-voice/log/uinfo.log"
}
# 定义接口测试配置
$APITests = @{
ExtAPI = @{
URL = 'https://{0}/exapi/message/getMsgPageList'
Expected = '{"success":false,"code":"A0076","message":"无效token"'
}
Meeting = @{
URL = 'https://{0}/meetingV3/api/systemConfiguration/globalConfig?companyNumber=CN-SZ-00-0201'
Expected = '{"success":false,"code":"A0078","message":"请求错误,accessToken为空"'
}
Monitor = @{
URL = 'https://{0}/monitor/api2/api/servermonitor/'
Expected = '{"success":0,"data":[{"code":40000014,"error":"用户不存在或重新登录或已退出"'
}
Voice = @{
URL = 'https://{0}/voice/api/iflytek/roommaster?company_id=1&user_id=8&company_secret=57d00f9f-020f-5f1f-b788-55fae843bceb&getall=1'
Expected = '{"success":false,"data":[{"code":40000003,"error":"缺少关键参数"'
}
}
# 全局执行记录
$Global:ExecutionLog = @()
$Global:DeployResults = @{}
# ============================================================================
# 日志函数
# ============================================================================
function Write-LogInfo {
param([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [INFO] $Message"
Write-Host $LogMessage
$Global:ExecutionLog += $LogMessage
}
function Write-LogWarn {
param([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [WARN] $Message"
Write-Host $LogMessage -ForegroundColor Yellow
$Global:ExecutionLog += $LogMessage
}
function Write-LogError {
param([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [ERROR] $Message"
Write-Host $LogMessage -ForegroundColor Red
$Global:ExecutionLog += $LogMessage
}
function Write-LogOk {
param([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [OK] $Message"
Write-Host $LogMessage -ForegroundColor Green
$Global:ExecutionLog += $LogMessage
}
function Write-LogStep {
param([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [STEP] $Message"
Write-Host $LogMessage -ForegroundColor Cyan
$Global:ExecutionLog += $LogMessage
}
# ============================================================================
# SSH连接函数
# ============================================================================
function Invoke-SSHCommand {
param(
[string]$Command,
[int]$Timeout = $Global:SSHTimeout
)
$PlinkArgs = @(
"-pw", $Password
"-P", $SSHPort
"-timeout", $Timeout
"$($Username)@$($ServerIP)"
$Command
)
try {
$Result = & $Global:PlinkPath $PlinkArgs 2>&1
return @{
Success = $?
Output = $Result -join "`n"
ExitCode = if ($?) { 0 } else { 1 }
}
}
catch {
return @{
Success = $false
Output = $_.Exception.Message
ExitCode = 1
}
}
}
function Test-SSHConnection {
Write-LogStep "步骤1: 测试SSH连接"
Write-LogInfo "正在连接服务器 ${ServerIP}:${SSHPort}..."
for ($i = 1; $i -le $Global:MaxRetry; $i++) {
$Result = Invoke-SSHCommand -Command "echo 'connection_ok'"
if ($Result.Output -match "connection_ok") {
Write-LogOk "连接成功"
$Global:DeployResults.Connection = "成功"
return $true
}
else {
Write-LogWarn "连接失败,正在重试 ($i/$Global:MaxRetry)..."
Start-Sleep -Seconds 2
}
}
Write-LogError "连接失败,已达到最大重试次数"
$Global:DeployResults.Connection = "失败"
return $false
}
# ============================================================================
# 部署包处理函数
# ============================================================================
function Copy-FromNetworkShare {
param(
[string]$NetworkPath,
[string]$Destination
)
Write-LogInfo "正在从网络共享复制: $NetworkPath"
try {
if (Test-Path $NetworkPath) {
Copy-Item -Path $NetworkPath -Destination $Destination -Recurse -Force
Write-LogOk "复制成功"
return $true
}
else {
Write-LogError "网络共享路径不存在: $NetworkPath"
return $false
}
}
catch {
Write-LogError "复制失败: $_"
return $false
}
}
function Upload-DeployPackage {
Write-LogStep "步骤2: 准备并上传部署包"
$Config = $DeployConfig[$Architecture]
$LocalPackageDir = Join-Path $TempDir "deploy_package"
# 清理并创建本地临时目录
if (Test-Path $LocalPackageDir) {
Remove-Item -Path $LocalPackageDir -Recurse -Force
}
New-Item -ItemType Directory -Path $LocalPackageDir -Force | Out-Null
# 从网络共享复制部署包
Write-LogInfo "正在从网络共享复制部署包..."
$CopyResult = Copy-FromNetworkShare -NetworkPath $Config.NetworkShare -Destination $LocalPackageDir
if (-not $CopyResult) {
Write-LogError "部署包复制失败"
$Global:DeployResults.PackageUpload = "失败: 网络共享复制失败"
return $false
}
# 获取部署包文件列表
$PackageFiles = Get-ChildItem -Path $LocalPackageDir -Recurse -File
Write-LogInfo "找到 $($PackageFiles.Count) 个文件"
# 在服务器上创建部署目录
$ServerDeployDir = "/home/deploy"
Write-LogInfo "正在创建服务器部署目录: $ServerDeployDir"
$MkdirResult = Invoke-SSHCommand -Command "mkdir -p $ServerDeployDir && echo 'created'"
if ($MkdirResult.Output -notmatch "created") {
Write-LogError "创建服务器部署目录失败"
$Global:DeployResults.PackageUpload = "失败: 无法创建服务器目录"
return $false
}
# 上传部署包文件
Write-LogInfo "正在上传部署包到服务器..."
$UploadedCount = 0
$FailedFiles = @()
foreach ($File in $PackageFiles) {
$RelativePath = $File.FullName.Substring($LocalPackageDir.Length + 1)
$RemotePath = "$ServerDeployDir/$RelativePath"
$RemoteDir = Split-Path $RemotePath -Parent
# 创建远程目录结构
$CreateDirResult = Invoke-SSHCommand -Command "mkdir -p '$RemoteDir'"
# 上传文件
try {
$PscpArgs = @(
"-pw", $Password
"-P", $SSHPort
"-batch"
$File.FullName
"${Username}@${ServerIP}:$RemotePath"
)
$UploadResult = & $Global:PscpPath $PscpArgs 2>&1
if ($LASTEXITCODE -eq 0) {
$UploadedCount++
if ($UploadedCount % 10 -eq 0) {
Write-LogInfo "已上传 $UploadedCount 个文件..."
}
}
else {
$FailedFiles += $RelativePath
}
}
catch {
$FailedFiles += $RelativePath
}
}
Write-LogInfo "上传完成: 成功 $UploadedCount 个,失败 $($FailedFiles.Count) 个"
if ($FailedFiles.Count -gt 0) {
Write-LogWarn "部分文件上传失败:"
foreach ($FailedFile in $FailedFiles) {
Write-LogWarn " - $FailedFile"
}
}
$Global:DeployResults.PackageUpload = "成功: $UploadedCount 个文件"
Write-LogOk "部署包上传完成"
return $true
}
# ============================================================================
# 部署执行函数
# ============================================================================
function Invoke-DeployScript {
Write-LogStep "步骤3: 执行自动化部署脚本"
$ServerDeployDir = "/home/deploy"
# 查找部署脚本
Write-LogInfo "正在查找部署脚本..."
$FindResult = Invoke-SSHCommand -Command "find $ServerDeployDir -name '*.sh' -type f 2>/dev/null | head -20"
$DeployScripts = $FindResult.Output -split "`n" | Where-Object { $_ -match '\S' }
if ($DeployScripts.Count -eq 0) {
Write-LogError "未找到部署脚本"
Write-LogInfo "服务器上的文件列表:"
$ListResult = Invoke-SSHCommand -Command "ls -la $ServerDeployDir"
Write-Host $ListResult.Output
$Global:DeployResults.DeployExecution = "失败: 未找到部署脚本"
return $false
}
Write-LogInfo "找到以下部署脚本:"
foreach ($Script in $DeployScripts) {
Write-Host " - $Script"
}
# 查找主部署脚本(通常包含 deploy、auto、install 等关键词)
$MainScript = $DeployScripts | Where-Object {
$_ -match '(auto_deploy|deploy|install|setup)' -and $_ -notmatch '\.(bak|backup|old)'
} | Select-Object -First 1
if (-not $MainScript) {
$MainScript = $DeployScripts[0]
}
Write-LogInfo "选择主部署脚本: $MainScript"
# 赋予执行权限
Write-LogInfo "正在设置脚本执行权限..."
$ChmodResult = Invoke-SSHCommand -Command "chmod +x '$MainScript' && echo 'chmod_ok'"
if ($ChmodResult.Output -notmatch "chmod_ok") {
Write-LogWarn "设置执行权限失败,尝试继续执行"
}
# 执行部署脚本
Write-LogWarn "开始执行部署脚本,预计耗时约40分钟..."
Write-LogInfo "部署输出将实时显示..."
# 使用 nohup 在后台执行部署,并记录日志
$LogFile = "/tmp/deploy_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$DeployCommand = "cd '$ServerDeployDir' && bash '$MainScript' 2>&1 | tee $LogFile"
Write-LogInfo "执行命令: $DeployCommand"
# 执行部署(使用长超时时间)
$DeployResult = Invoke-SSHCommand -Command $DeployCommand -Timeout 3600
Write-LogInfo "部署脚本执行完成"
Write-Host "`n========== 部署输出 ==========" -ForegroundColor Cyan
Write-Host $DeployResult.Output
Write-Host "========== 部署输出结束 ==========`n" -ForegroundColor Cyan
# 检查部署结果
if ($DeployResult.ExitCode -eq 0) {
Write-LogOk "部署脚本执行成功"
$Global:DeployResults.DeployExecution = "成功"
$Global:DeployResults.DeployLog = $LogFile
return $true
}
else {
Write-LogError "部署脚本执行失败,退出码: $($DeployResult.ExitCode)"
$Global:DeployResults.DeployExecution = "失败: 退出码 $($DeployResult.ExitCode)"
$Global:DeployResults.DeployLog = $LogFile
return $false
}
}
# ============================================================================
# 服务检查函数
# ============================================================================
function Test-ContainerStatus {
Write-LogStep "步骤4: 检查容器状态"
# 检查Docker是否运行
$DockerCheck = Invoke-SSHCommand -Command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>/dev/null"
if ($DockerCheck.ExitCode -ne 0) {
Write-LogError "Docker未运行或无法访问"
$Global:DeployResults.ContainerStatus = "失败: Docker不可用"
return $false
}
Write-Host "`n========== 容器状态 ==========" -ForegroundColor Cyan
Write-Host $DockerCheck.Output
Write-Host "========== 容器状态结束 ==========`n" -ForegroundColor Cyan
# 检查关键容器
$RequiredContainers = @(
"ujava",
"upython",
"uredis",
"umysql",
"uemqx"
)
$ContainerStatus = @{}
foreach ($Container in $RequiredContainers) {
$CheckResult = Invoke-SSHCommand -Command "docker inspect -f '{{.State.Running}}' $Container 2>/dev/null || echo 'not_found'"
if ($CheckResult.Output -match "true") {
$ContainerStatus[$Container] = "运行中"
Write-LogOk "$Container: 运行中"
}
elseif ($CheckResult.Output -match "false") {
$ContainerStatus[$Container] = "已停止"
Write-LogWarn "$Container: 已停止"
}
else {
$ContainerStatus[$Container] = "不存在"
Write-LogError "$Container: 不存在"
}
}
$Global:DeployResults.ContainerStatus = $ContainerStatus
# 检查是否有异常容器
$FailedContainers = $ContainerStatus.GetEnumerator() | Where-Object { $_.Value -ne "运行中" }
if ($FailedContainers.Count -eq 0) {
Write-LogOk "所有关键容器状态正常"
return $true
}
else {
Write-LogWarn "部分容器状态异常"
return $false
}
}
function Test-ServiceLogs {
Write-LogStep "步骤5: 检查服务日志"
$LogChecks = @{}
# 检查对外服务日志(必须包含版本信息)
Write-LogInfo "检查对外服务日志..."
$ExtAPILog = Invoke-SSHCommand -Command "tail -100 $($LogPaths.ExtAPI) 2>/dev/null || echo 'log_not_found'"
if ($ExtAPILog.Output -match "SYSTEMVERSION :: target_api_integration") {
Write-LogOk "对外服务日志正常(已检测到版本信息)"
$LogChecks.ExtAPI = "正常"
}
elseif ($ExtAPILog.Output -match "log_not_found") {
Write-LogWarn "对外服务日志文件不存在"
$LogChecks.ExtAPI = "日志文件不存在"
}
else {
Write-LogWarn "对外服务日志未检测到版本信息,等待10分钟后重试..."
# 等待10分钟
for ($i = 1; $i -le 10; $i++) {
Write-Host "等待中... ($i/10 分钟)" -ForegroundColor Yellow
Start-Sleep -Seconds 60
}
# 重新检查
$ExtAPILogRetry = Invoke-SSHCommand -Command "tail -100 $($LogPaths.ExtAPI) 2>/dev/null"
if ($ExtAPILogRetry.Output -match "SYSTEMVERSION") {
Write-LogOk "对外服务日志正常(重试后检测到版本信息)"
$LogChecks.ExtAPI = "正常(重试后)"
}
else {
Write-LogError "对外服务日志异常(10分钟后仍未检测到版本信息)"
Write-Host "`n最后100行日志:" -ForegroundColor Yellow
Write-Host $ExtAPILogRetry.Output
$LogChecks.ExtAPI = "异常:无版本信息"
}
}
# 检查其他服务日志是否存在异常
$OtherLogs = @(
@{Name = "对内服务"; Path = $LogPaths.InnerAPI},
@{Name = "运维服务"; Path = $LogPaths.Monitor},
@{Name = "讯飞服务"; Path = $LogPaths.Voice}
)
foreach ($LogInfo in $OtherLogs) {
Write-LogInfo "检查$($LogInfo.Name)日志..."
$LogResult = Invoke-SSHCommand -Command "tail -50 $($LogInfo.Path) 2>/dev/null || echo 'not_found'"
if ($LogResult.Output -match "ERROR|Exception|Failed|failed") {
Write-LogWarn "$($LogInfo.Name)日志中发现异常信息"
$LogChecks[$LogInfo.Name] = "发现异常"
}
elseif ($LogResult.Output -match "not_found") {
Write-LogWarn "$($LogInfo.Name)日志文件不存在"
$LogChecks[$LogInfo.Name] = "日志文件不存在"
}
else {
Write-LogOk "$($LogInfo.Name)日志正常"
$LogChecks[$LogInfo.Name] = "正常"
}
}
$Global:DeployResults.ServiceLogs = $LogChecks
return $true
}
function Test-APIEndpoints {
Write-LogStep "步骤6: 测试服务接口"
$APIResults = @{}
foreach ($APIName in $APITests.Keys) {
$API = $APITests[$APIName]
$URL = $API.URL -f $ServerIP
$Expected = $API.Expected
Write-LogInfo "测试 $APIName 接口..."
# 使用curl测试接口(忽略SSL证书)
$CurlCommand = "curl -k '$URL' 2>/dev/null"
$APIResult = Invoke-SSHCommand -Command $CurlCommand -Timeout 60
# 检查是否返回预期的错误响应(表示服务正常,只是缺少认证)
if ($APIResult.Output -match $Expected.Substring(0, 20)) {
Write-LogOk "$APIName 接口正常(返回预期认证错误)"
$APIResults[$APIName] = "正常"
continue
}
# 检查是否返回nginx错误页面(表示服务未启动)
if ($APIResult.Output -match "An error occurred|nginx") {
Write-LogError "$APIName 接口异常(返回nginx错误页面)"
# 执行重试机制
$RetrySuccess = $false
for ($retry = 1; $retry -le 5; $retry++) {
Write-LogWarn "重试第 $retry 次..."
Start-Sleep -Seconds 30
$RetryResult = Invoke-SSHCommand -Command $CurlCommand -Timeout 60
if ($RetryResult.Output -match $Expected.Substring(0, 20)) {
Write-LogOk "$APIName 接口正常(重试第 $retry 次后成功)"
$APIResults[$APIName] = "正常(重试 $retry 次)"
$RetrySuccess = $true
break
}
}
if (-not $RetrySuccess) {
$APIResults[$APIName] = "异常:5次重试后仍失败"
}
}
else {
# 返回了其他响应,可能是服务问题
Write-LogWarn "$APIName 接口返回未知响应"
Write-Host "响应内容: $($APIResult.Output.Substring(0, 200))"
$APIResults[$APIName] = "未知响应"
}
}
$Global:DeployResults.APITests = $APIResults
# 检查API测试结果
$FailedAPIs = $APIResults.GetEnumerator() | Where-Object { $_.Value -like "*异常*" -or $_.Value -eq "未知响应" }
if ($FailedAPIs.Count -eq 0) {
Write-LogOk "所有接口测试通过"
return $true
}
else {
Write-LogWarn "部分接口测试失败"
return $false
}
}
# ============================================================================
# 系统授权函数
# ============================================================================
function Invoke-SystemAuthorization {
Write-LogStep "步骤7: 系统授权"
Write-LogWarn "系统授权需要访问Web界面完成,请按以下步骤操作:"
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "系统授权操作步骤" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "1. 访问维护平台: https://${ServerIP}/#/LoginConfig"
Write-Host "2. 输入验证码: csba"
Write-Host "3. 上传授权文件"
Write-Host " 授权文件路径: $($DeployConfig[$Architecture].LicenseFile)"
Write-Host "4. 完成授权操作"
Write-Host "========================================`n" -ForegroundColor Cyan
$Response = Read-Host "是否已完成系统授权?(y/n)"
if ($Response -eq 'y' -or $Response -eq 'Y') {
Write-LogOk "系统授权已完成"
$Global:DeployResults.Authorization = "已完成"
return $true
}
else {
Write-LogWarn "系统授权未完成"
$Global:DeployResults.Authorization = "未完成"
return $false
}
}
# ============================================================================
# 创建管理员函数
# ============================================================================
function New-CompanyAdmin {
Write-LogStep "步骤8: 创建公司管理员"
Write-LogWarn "创建管理员需要访问Web界面完成,请按以下步骤操作:"
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "创建公司管理员操作步骤" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "1. 访问后台地址: https://${ServerIP}/#/LoginAdmin"
Write-Host "2. 按照部署文档第四章创建公司管理员"
Write-Host "3. 完成用户创建操作"
Write-Host "========================================`n" -ForegroundColor Cyan
$Response = Read-Host "是否已创建公司管理员?(y/n)"
if ($Response -eq 'y' -or $Response -eq 'Y') {
Write-LogOk "公司管理员创建完成"
$Global:DeployResults.AdminCreated = "已完成"
return $true
}
else {
Write-LogWarn "公司管理员未创建"
$Global:DeployResults.AdminCreated = "未完成"
return $false
}
}
# ============================================================================
# 生成部署报告
# ============================================================================
function New-DeployReport {
Write-LogStep "步骤9: 生成部署报告"
$Timestamp = Get-Date -Format "yyyy_MM_dd_HHmmss"
$ReportFileName = "${ServerIP}_部署报告_${Timestamp}.md"
$ReportFilePath = Join-Path $ReportsDir $ReportFileName
$ReportContent = @"
# 新统一平台部署报告
## 基本信息
- 服务器IP: $ServerIP
- 架构类型: $Architecture
- 部署时间: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
## 部署结果
### 1. SSH连接
- 状态: $($Global:DeployResults.Connection)
### 2. 部署包上传
- 状态: $($Global:DeployResults.PackageUpload)
### 3. 部署执行
- 状态: $($Global:DeployResults.DeployExecution)
$(if ($Global:DeployResults.DeployLog) {
"- 部署日志: $($Global:DeployResults.DeployLog)"
})
### 4. 容器状态
"@
if ($Global:DeployResults.ContainerStatus -is [hashtable]) {
foreach ($Container in $Global:DeployResults.ContainerStatus.Keys) {
$ReportContent += "`n- $Container : $($Global:DeployResults.ContainerStatus[$Container])"
}
}
$ReportContent += @"
### 5. 服务日志
"@
if ($Global:DeployResults.ServiceLogs -is [hashtable]) {
foreach ($Log in $Global:DeployResults.ServiceLogs.Keys) {
$ReportContent += "`n- $Log : $($Global:DeployResults.ServiceLogs[$Log])"
}
}
$ReportContent += @"
### 6. 接口测试
"@
if ($Global:DeployResults.APITests -is [hashtable]) {
foreach ($API in $Global:DeployResults.APITests.Keys) {
$ReportContent += "`n- $API : $($Global:DeployResults.APITests[$API])"
}
}
$ReportContent += @"
### 7. 系统授权
- 状态: $($Global:DeployResults.Authorization)
### 8. 管理员创建
- 状态: $($Global:DeployResults.AdminCreated)
## 系统访问地址
- 前台地址: https://${ServerIP}/
- 维护地址: https://${ServerIP}/#/LoginConfig
- 后台地址: https://${ServerIP}/#/LoginAdmin
## 执行日志
"@
$ReportContent += $Global:ExecutionLog -join "`n"
$ReportContent += @"
---
报告生成时间: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
"@
try {
$ReportContent | Out-File -FilePath $ReportFilePath -Encoding UTF8 -Force
Write-LogOk "部署报告已生成: $ReportFilePath"
return $ReportFilePath
}
catch {
Write-LogError "报告生成失败: $_"
return $null
}
}
# ============================================================================
# 主函数
# ============================================================================
function Main {
# 记录开始时间
$StartTime = Get-Date
# 打印欢迎信息
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "新统一平台远程自动化部署脚本" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "目标服务器: ${ServerIP} (${Architecture})"
Write-Host "开始时间: $($StartTime.ToString('yyyy-MM-dd HH:mm:ss'))"
Write-Host "========================================`n" -ForegroundColor Cyan
# 初始化部署结果
$Global:DeployResults = @{
Connection = ""
PackageUpload = ""
DeployExecution = ""
ContainerStatus = @{}
ServiceLogs = @{}
APITests = @{}
Authorization = ""
AdminCreated = ""
}
try {
# 步骤1: 测试SSH连接
if (-not (Test-SSHConnection)) {
Write-LogError "SSH连接失败,部署终止"
New-DeployReport
return $false
}
# 步骤2: 上传部署包
if (-not (Upload-DeployPackage)) {
Write-LogError "部署包上传失败,部署终止"
New-DeployReport
return $false
}
# 步骤3: 执行部署脚本
if (-not (Invoke-DeployScript)) {
Write-LogError "部署脚本执行失败,继续检查服务状态..."
}
# 步骤4: 检查容器状态
Test-ContainerStatus
# 步骤5: 检查服务日志
Test-ServiceLogs
# 步骤6: 测试服务接口
Test-APIEndpoints
# 步骤7: 系统授权
Invoke-SystemAuthorization
# 步骤8: 创建管理员
New-CompanyAdmin
# 步骤9: 生成报告
$ReportPath = New-DeployReport
# 打印完成信息
$EndTime = Get-Date
$Duration = $EndTime - $StartTime
Write-Host "`n========================================" -ForegroundColor Green
Write-Host "部署完成" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host "结束时间: $($EndTime.ToString('yyyy-MM-dd HH:mm:ss'))"
Write-Host "总耗时: $($Duration.ToString('hh:mm:ss'))"
if ($ReportPath) {
Write-Host "报告位置: $ReportPath"
}
Write-Host "========================================`n" -ForegroundColor Green
return $true
}
catch {
Write-LogError "程序执行出错: $_"
New-DeployReport
return $false
}
}
# 检查plink.exe是否存在
if (-not (Test-Path $Global:PlinkPath)) {
Write-Host "错误: 找不到 plink.exe" -ForegroundColor Red
Write-Host "请从 https://the.earth.li/~sgtatham/putty/latest/w64/plink.exe 下载" -ForegroundColor Yellow
Write-Host "并将 plink.exe 放在脚本同目录下" -ForegroundColor Yellow
exit 1
}
# 执行主函数
Main
#!/bin/bash
# ============================================================================
# Remote Automated Deployment Script - New Unified Platform
# Purpose: Automatically complete the deployment of the new unified platform
# Author: Automation Operations Team
# Created: 2026-05-14
# ============================================================================
# Configuration
SERVER_IP="192.168.5.52"
SSH_PORT="22"
USERNAME="root"
PASSWORD="Ubains@123"
ARCHITECTURE="X86"
# Network share paths (for reference)
DEPLOY_SHARE_X86="\\\\192.168.9.9\\发布版本\\03服务器部署\\临时使用-新统一平台\\X86部署包\\全量版"
LICENSE_SHARE_X86="\\\\192.168.9.9\\发布版本\\03服务器部署\\临时使用-新统一平台\\测试授权文件-请勿使用\\5.52授权文件\\license.zip"
# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGES_DIR="$SCRIPT_DIR/packages"
REPORTS_DIR="$SCRIPT_DIR/reports"
TEMP_DIR="$SCRIPT_DIR/temp"
# SSH tools
PLINK="$SCRIPT_DIR/plink.exe"
PSCP="$SCRIPT_DIR/pscp.exe"
# Create directories
mkdir -p "$PACKAGES_DIR" "$REPORTS_DIR" "$TEMP_DIR"
# Log file
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="$REPORTS_DIR/deploy_${TIMESTAMP}.log"
# ============================================================================
# Logging Functions
# ============================================================================
log_info() {
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [INFO] $1"
echo "$msg" | tee -a "$LOG_FILE"
}
log_warn() {
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [WARN] $1"
echo "$msg" | tee -a "$LOG_FILE"
}
log_error() {
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR] $1"
echo "$msg" | tee -a "$LOG_FILE"
}
log_ok() {
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [OK] $1"
echo "$msg" | tee -a "$LOG_FILE"
}
log_step() {
local msg="[$(date '+%Y-%m-%d %H:%M:%S')] [STEP] $1"
echo "$msg" | tee -a "$LOG_FILE"
}
# ============================================================================
# SSH Functions
# ============================================================================
ssh_command() {
local cmd="$1"
local timeout="${2:-300}"
"$PLINK" -pw "$PASSWORD" -P "$SSH_PORT" -timeout "$timeout" "${USERNAME}@${SERVER_IP}" "$cmd" 2>&1
return $?
}
test_ssh_connection() {
log_step "Step 1: Testing SSH connection"
log_info "Connecting to server ${SERVER_IP}:${SSH_PORT}..."
for i in {1..3}; do
result=$(ssh_command "echo 'connection_ok'" 30)
if echo "$result" | grep -q "connection_ok"; then
log_ok "Connection successful"
return 0
else
log_warn "Connection failed, retrying ($i/3)..."
sleep 2
fi
done
log_error "Connection failed after 3 attempts"
return 1
}
# ============================================================================
# Deployment Functions
# ============================================================================
upload_deploy_package() {
log_step "Step 2: Upload deployment package"
# Check if deploy package is available locally or on network share
log_warn "Deployment package should be prepared manually"
log_info "Network share path: $DEPLOY_SHARE_X86"
log_info ""
log_info "Please copy the deployment package to: $PACKAGES_DIR"
log_info "Or ensure the package is already on the server at: /home/deploy"
read -p "Press Enter to continue after package is ready..."
# Create deployment directory on server
log_info "Creating deployment directory on server..."
result=$(ssh_command "mkdir -p /home/deploy && echo 'created'")
if echo "$result" | grep -q "created"; then
log_ok "Deployment directory created"
else
log_error "Failed to create deployment directory"
return 1
fi
return 0
}
execute_deploy_script() {
log_step "Step 3: Execute deployment script"
# Find deployment script on server
log_info "Searching for deployment scripts..."
result=$(ssh_command "find /home/deploy -name '*.sh' -type f 2>/dev/null | head -20")
if [ -z "$result" ]; then
log_error "No deployment script found on server"
log_info "Please upload the deployment script manually to /home/deploy"
return 1
fi
log_info "Found deployment scripts:"
echo "$result" | while read -r line; do
echo " - $line"
done
# Find main deployment script
main_script=$(echo "$result" | grep -E "(auto_deploy|deploy|install|setup)" | grep -v -E "\.(bak|backup|old)" | head -1)
if [ -z "$main_script" ]; then
main_script=$(echo "$result" | head -1)
fi
log_info "Selected main script: $main_script"
# Make script executable
log_info "Setting execute permissions..."
ssh_command "chmod +x '$main_script'" > /dev/null
# Execute deployment script
log_warn "Starting deployment script, estimated time: 40 minutes..."
log_info "Deployment output will be displayed..."
# Execute deployment with long timeout
ssh_command "cd /home/deploy && bash '$main_script' 2>&1" 3600 | tee -a "$LOG_FILE"
local exit_code=${PIPESTATUS[0]}
if [ $exit_code -eq 0 ]; then
log_ok "Deployment script executed successfully"
return 0
else
log_error "Deployment script failed with exit code: $exit_code"
return 1
fi
}
check_container_status() {
log_step "Step 4: Check container status"
# Check if Docker is running
result=$(ssh_command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>/dev/null")
if [ $? -ne 0 ]; then
log_error "Docker is not running or not accessible"
return 1
fi
echo ""
echo "========== Container Status =========="
echo "$result"
echo "========== Container Status End =========="
echo ""
# Check required containers
local required_containers=("ujava" "upython" "uredis" "umysql" "uemqx")
local all_ok=true
for container in "${required_containers[@]}"; do
result=$(ssh_command "docker inspect -f '{{.State.Running}}' $container 2>/dev/null || echo 'not_found'")
if echo "$result" | grep -q "true"; then
log_ok "$container: Running"
elif echo "$result" | grep -q "false"; then
log_warn "$container: Stopped"
all_ok=false
else
log_error "$container: Not found"
all_ok=false
fi
done
if [ "$all_ok" = true ]; then
log_ok "All required containers are running"
return 0
else
log_warn "Some containers are not running properly"
return 1
fi
}
check_service_logs() {
log_step "Step 5: Check service logs"
# Check external API service log
log_info "Checking external API service log..."
result=$(ssh_command "tail -100 /data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log 2>/dev/null || echo 'log_not_found'")
if echo "$result" | grep -q "SYSTEMVERSION.*target_api_integration"; then
log_ok "External API service log is normal (version information detected)"
elif echo "$result" | grep -q "log_not_found"; then
log_warn "External API service log file not found"
else
log_warn "External API service log does not contain version information, waiting 10 minutes to retry..."
# Wait 10 minutes
for i in {1..10}; do
echo "Waiting... ($i/10 minutes)"
sleep 60
done
# Retry check
result=$(ssh_command "tail -100 /data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log 2>/dev/null")
if echo "$result" | grep -q "SYSTEMVERSION"; then
log_ok "External API service log is normal (version information detected after retry)"
else
log_error "External API service log is abnormal (no version information after 10 minutes)"
fi
fi
return 0
}
test_api_endpoints() {
log_step "Step 6: Test service endpoints"
# Define API tests
local apis=(
"ExtAPI|https://${SERVER_IP}/exapi/message/getMsgPageList|A0076"
"Meeting|https://${SERVER_IP}/meetingV3/api/systemConfiguration/globalConfig?companyNumber=CN-SZ-00-0201|A0078"
"Monitor|https://${SERVER_IP}/monitor/api2/api/servermonitor/|40000014"
"Voice|https://${SERVER_IP}/voice/api/iflytek/roommaster?company_id=1&user_id=8&company_secret=57d00f9f-020f-5f1f-b788-55fae843bceb&getall=1|40000003"
)
local all_ok=true
for api_test in "${apis[@]}"; do
IFS='|' read -r api_name url expected <<< "$api_test"
log_info "Testing $api_name endpoint..."
# Use curl to test endpoint (ignore SSL certificate)
result=$(ssh_command "curl -k '$url' 2>/dev/null" 60)
if echo "$result" | grep -q "$expected"; then
log_ok "$api_name endpoint is normal (returns expected authentication error)"
elif echo "$result" | grep -q "An error occurred\|nginx"; then
log_error "$api_name endpoint is abnormal (returns nginx error page)"
# Retry mechanism
local retry_success=false
for retry in {1..5}; do
log_warn "Retry $retry..."
sleep 30
result=$(ssh_command "curl -k '$url' 2>/dev/null" 60)
if echo "$result" | grep -q "$expected"; then
log_ok "$api_name endpoint is normal (successful after retry $retry)"
retry_success=true
break
fi
done
if [ "$retry_success" = false ]; then
all_ok=false
fi
else
log_warn "$api_name endpoint returned unknown response"
fi
done
if [ "$all_ok" = true ]; then
log_ok "All API endpoints tested successfully"
return 0
else
log_warn "Some API endpoints failed testing"
return 1
fi
}
system_authorization() {
log_step "Step 7: System Authorization"
echo ""
echo "========================================"
echo "System Authorization Steps"
echo "========================================"
echo "1. Visit maintenance platform: https://${SERVER_IP}/#/LoginConfig"
echo "2. Enter verification code: csba"
echo "3. Upload license file"
echo " License file path: $LICENSE_SHARE_X86"
echo "4. Complete authorization"
echo "========================================"
echo ""
read -p "Have you completed the system authorization? (y/n) " response
if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
log_ok "System authorization completed"
return 0
else
log_warn "System authorization not completed"
return 1
fi
}
create_company_admin() {
log_step "Step 8: Create Company Administrator"
echo ""
echo "========================================"
echo "Create Company Administrator Steps"
echo "========================================"
echo "1. Visit backend address: https://${SERVER_IP}/#/LoginAdmin"
echo "2. Follow deployment documentation Chapter 4 to create company administrator"
echo "3. Complete user creation"
echo "========================================"
echo ""
read -p "Have you created the company administrator? (y/n) " response
if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
log_ok "Company administrator created"
return 0
else
log_warn "Company administrator not created"
return 1
fi
}
generate_report() {
log_step "Step 9: Generate deployment report"
local report_file="$REPORTS_DIR/${SERVER_IP}_deployment_report_${TIMESTAMP}.md"
cat > "$report_file" << EOF
# New Unified Platform Deployment Report
## Basic Information
- Server IP: $SERVER_IP
- Architecture: $ARCHITECTURE
- Deployment Time: $(date '+%Y-%m-%d %H:%M:%S')
## System Access Addresses
- Frontend Address: https://${SERVER_IP}/
- Maintenance Address: https://${SERVER_IP}/#/LoginConfig
- Backend Address: https://${SERVER_IP}/#/LoginAdmin
---
Report Generated Time: $(date '+%Y-%m-%d %H:%M:%S')
EOF
log_ok "Deployment report generated: $report_file"
echo ""
echo "Report location: $report_file"
return 0
}
# ============================================================================
# Main Function
# ============================================================================
main() {
local start_time=$(date +%s)
echo ""
echo "========================================"
echo "New Unified Platform Remote Automated Deployment Script"
echo "========================================"
echo "Target Server: ${SERVER_IP} (${ARCHITECTURE})"
echo "Start Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"
echo ""
local deploy_success=true
# Step 1: Test SSH connection
if ! test_ssh_connection; then
log_error "SSH connection failed, deployment terminated"
generate_report
return 1
fi
# Step 2: Upload deployment package
if ! upload_deploy_package; then
log_error "Deployment package preparation failed, continuing with deployment..."
fi
# Step 3: Execute deployment script
if ! execute_deploy_script; then
log_error "Deployment script execution failed, continuing with service checks..."
fi
# Step 4: Check container status
check_container_status
# Step 5: Check service logs
check_service_logs
# Step 6: Test API endpoints
test_api_endpoints
# Step 7: System authorization
system_authorization
# Step 8: Create company administrator
create_company_admin
# Step 9: Generate report
generate_report
# Print completion message
local end_time=$(date +%s)
local duration=$((end_time - start_time))
local hours=$((duration / 3600))
local minutes=$(((duration % 3600) / 60))
local seconds=$((duration % 60))
echo ""
echo "========================================"
echo "Deployment Completed"
echo "========================================"
echo "End Time: $(date '+%Y-%m-%d %H:%M:%S')"
printf "Total Duration: %02d:%02d:%02d\n" $hours $minutes $seconds
echo "========================================"
echo ""
return 0
}
# Check if plink.exe exists
if [ ! -f "$PLINK" ]; then
echo "Error: plink.exe not found"
echo "Please download from: https://the.earth.li/~sgtatham/putty/latest/w64/plink.exe"
echo "And place plink.exe in the script directory"
exit 1
fi
# Execute main function
main
# Simple Remote Deployment Script using Windows OpenSSH
# Author: Automation Team
# Date: 2026-05-14
param(
[string]$ServerIP = "192.168.5.52",
[string]$Username = "root",
[string]$Password = "Ubains@123",
[int]$SSHPort = 22
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ReportsDir = Join-Path $ScriptDir "reports"
$LogFile = Join-Path $ReportsDir "deploy_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
# Create reports directory
if (-not (Test-Path $ReportsDir)) {
New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null
}
# Logging function
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [$Level] $Message"
Write-Host $LogMessage
Add-Content -Path $LogFile -Value $LogMessage
}
# SSH command function using plink with host key auto-accept
function Invoke-SSHCommand {
param([string]$Command, [int]$Timeout = 300)
$PlinkPath = Join-Path $ScriptDir "plink.exe"
# Create temporary plink session to accept host key
$Args = @(
"-pw", $Password,
"-P", $SSHPort,
"-hostkey",
'*',
"$Username@$ServerIP",
$Command
)
$Output = & $PlinkPath $Args 2>&1
return $Output
}
Write-Log "========================================"
Write-Log "New Unified Platform Deployment Script"
Write-Log "Target Server: ${ServerIP}"
Write-Log "========================================"
# Test SSH connection
Write-Log "Testing SSH connection..."
$TestResult = Invoke-SSHCommand -Command "echo 'connection_ok'"
if ($TestResult -match "connection_ok") {
Write-Log "SSH connection successful" "OK"
# Get server information
Write-Log "Getting server information..."
$SystemInfo = Invoke-SSHCommand -Command "uname -a"
Write-Log "Server OS: $SystemInfo"
# Check if /data/services exists (new platform)
$PlatformCheck = Invoke-SSHCommand -Command "test -d /data/services && echo 'new' || echo 'old'"
Write-Log "Platform type: $PlatformCheck"
# Check Docker status
Write-Log "Checking Docker status..."
$DockerCheck = Invoke-SSHCommand -Command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>&1"
if ($LASTEXITCODE -eq 0) {
Write-Log "Docker is running"
Write-Host "`n========== Container Status =========="
Write-Host $DockerCheck
Write-Host "========== Container Status End ==========`n"
} else {
Write-Log "Docker is not running or not accessible" "WARN"
}
} else {
Write-Log "SSH connection failed" "ERROR"
Write-Log "Error: $TestResult" "ERROR"
Write-Log ""
Write-Log "Please ensure:" "INFO"
Write-Log "1. Server IP is correct: $ServerIP" "INFO"
Write-Log "2. SSH port is open: $SSHPort" "INFO"
Write-Log "3. Username and password are correct" "INFO"
Write-Log "4. Server is reachable from this machine" "INFO"
}
Write-Log "========================================"
Write-Log "Deployment script completed"
Write-Log "Log file: $LogFile"
Write-Log "========================================"
# Remote Deployment Script using Windows OpenSSH
# Author: Automation Team
# Date: 2026-05-14
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ReportsDir = Join-Path $ScriptDir "reports"
if (-not (Test-Path $ReportsDir)) {
New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null
}
$LogFile = Join-Path $ReportsDir "deploy_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
function Write-Log {
param([string]$Message, [string]$Color = "White")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] $Message"
Write-Host $LogMessage -ForegroundColor $Color
Add-Content -Path $LogFile -Value $LogMessage
}
Write-Log "========================================" "Cyan"
Write-Log "New Unified Platform Deployment Script" "Cyan"
Write-Log "========================================" "Cyan"
# Configuration
$ServerIP = "192.168.5.52"
$Username = "root"
$Password = "Ubains@123"
$SSHPort = 22
# Use plink.exe
$PlinkPath = Join-Path $ScriptDir "plink.exe"
Write-Log "Target Server: ${ServerIP}:${SSHPort}"
Write-Log ""
# Step 1: Accept host key
Write-Log "Step 1: Establishing SSH connection (accepting host key)..." "Yellow"
# Create a process to start plink and automatically answer 'y' to host key prompt
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo
$StartInfo.FileName = $PlinkPath
$StartInfo.Arguments = "-pw $Password -P $SSHPort $Username@${ServerIP} echo 'connection_ok'"
$StartInfo.UseShellExecute = $false
$StartInfo.RedirectStandardInput = $true
$StartInfo.RedirectStandardOutput = $true
$StartInfo.RedirectStandardError = $true
$StartInfo.CreateNoWindow = $true
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $StartInfo
$Process.Start() | Out-Null
# Automatically answer 'y' to any prompts
$Process.StandardInput.WriteLine("y")
$Process.StandardInput.Close()
# Wait for process to complete
$Process.WaitForExit(30000)
$Output = $Process.StandardOutput.ReadToEnd()
$Error = $Process.StandardError.ReadToEnd()
if ($Output -match "connection_ok") {
Write-Log "SSH connection established successfully!" "Green"
# Step 2: Get server information
Write-Log ""
Write-Log "Step 2: Getting server information..." "Cyan"
$StartInfo.Arguments = "-pw $Password -P $SSHPort $Username@${ServerIP} uname -a"
$Process2 = New-Object System.Diagnostics.Process
$Process2.StartInfo = $StartInfo
$Process2.Start() | Out-Null
$Process2.WaitForExit(30000)
$ServerInfo = $Process2.StandardOutput.ReadToEnd()
Write-Log "Server OS: $ServerInfo" "Green"
# Step 3: Check Docker status
Write-Log ""
Write-Log "Step 3: Checking Docker status..." "Cyan"
$StartInfo.Arguments = "-pw $Password -P $SSHPort $Username@${ServerIP} docker ps --format 'table {{.Names}}\t{{.Status}}'"
$Process3 = New-Object System.Diagnostics.Process
$Process3.StartInfo = $StartInfo
$Process3.Start() | Out-Null
$Process3.WaitForExit(30000)
$DockerOutput = $Process3.StandardOutput.ReadToEnd()
if ($DockerOutput) {
Write-Log "Docker is running" "Green"
Write-Host ""
Write-Host "========== Container Status ==========" -ForegroundColor Cyan
Write-Host $DockerOutput
Write-Host "========== Container Status End ==========" -ForegroundColor Cyan
Write-Host ""
} else {
Write-Log "Docker is not running or not accessible" "Yellow"
}
Write-Log ""
Write-Log "========================================" "Green"
Write-Log "Connection test completed successfully!" "Green"
Write-Log "========================================" "Green"
} else {
Write-Log "SSH connection failed" "Red"
Write-Log "Error: $Error" "Red"
Write-Log ""
Write-Log "Possible reasons:" "Yellow"
Write-Log "1. Server IP is incorrect" "Yellow"
Write-Log "2. SSH port is closed" "Yellow"
Write-Log "3. Username or password is incorrect" "Yellow"
Write-Log "4. Server is not reachable" "Yellow"
}
Write-Log ""
Write-Log "Log file: $LogFile"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw Ubains@123 -P 22 root@192.168.5.52 'ls -la /home && echo --- && ls -la /home/deploy 2>&1'"
$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(30000)
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host $stdout
Write-Host $stderr
# Deployment Check Script - Simplified Version
# Author: Automation Team
# Date: 2026-05-14
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ReportsDir = Join-Path $ScriptDir "reports"
if (-not (Test-Path $ReportsDir)) {
New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null
}
$LogFile = Join-Path $ReportsDir "deploy_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
function Write-Log {
param([string]$Message, [string]$Color = "White")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] $Message"
Write-Host $LogMessage -ForegroundColor $Color
Add-Content -Path $LogFile -Value $LogMessage
}
function Invoke-SSHCommand {
param([string]$Command)
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw $Password -P $SSHPort ${Username}@${ServerIP} $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)
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
return @{
Output = $stdout
ExitCode = $p.ExitCode
}
}
# Configuration
$ServerIP = "192.168.5.52"
$Username = "root"
$Password = "Ubains@123"
$SSHPort = 22
$Results = @{}
Write-Log "========================================" "Cyan"
Write-Log "Deployment Check Script" "Cyan"
Write-Log "Target: ${ServerIP}" "Cyan"
Write-Log "========================================" "Cyan"
# Test connection
Write-Log "Testing SSH connection..." "Yellow"
$result = Invoke-SSHCommand -Command "echo 'ok'"
if ($result.Output -match "ok") {
Write-Log "Connection successful" "Green"
$Results.Connection = "OK"
} else {
Write-Log "Connection failed" "Red"
exit 1
}
# Get server info
Write-Log "Getting server information..." "Yellow"
$osInfo = Invoke-SSHCommand -Command "uname -a"
Write-Log "OS: $($osInfo.Output.Trim())" "White"
$diskInfo = Invoke-SSHCommand -Command "df -h /home | awk 'NR==2 {print \$4}'"
Write-Log "Disk space: $($diskInfo.Output.Trim())" "White"
# Check Docker
Write-Log "Checking Docker status..." "Yellow"
$dockerResult = Invoke-SSHCommand -Command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>&1"
if ($dockerResult.ExitCode -eq 0) {
Write-Log "Docker is running" "Green"
Write-Host ""
Write-Host "========== Containers ==========" -ForegroundColor Cyan
Write-Host $dockerResult.Output
Write-Host "========== Containers End ==========" -ForegroundColor Cyan
Write-Host ""
$Results.Docker = "Running"
} else {
Write-Log "Docker is not accessible" "Red"
$Results.Docker = "Not Running"
}
# Check services
Write-Log "Checking services..." "Yellow"
$services = @(
@{Name="ExtAPI"; Path="/data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"},
@{Name="InnerAPI"; Path="/data/services/api/java-meeting/java-meeting2.0/logs/ubains-INFO-AND-ERROR.log"},
@{Name="Monitor"; Path="/data/services/api/python-cmdb/log/uinfo.log"},
@{Name="Voice"; Path="/data/services/api/python-voice/log/uinfo.log"}
)
foreach ($svc in $services) {
$logResult = Invoke-SSHCommand -Command "test -f '$($svc.Path)' && echo 'exists' || echo 'not_found'"
if ($logResult.Output -match "exists") {
$tailResult = Invoke-SSHCommand -Command "tail -20 '$($svc.Path)'"
if ($tailResult.Output -match "ERROR|Exception") {
Write-Log "$($svc.Name): Log contains errors" "Yellow"
$Results[$svc.Name] = "Has Errors"
} else {
Write-Log "$($svc.Name): Log OK" "Green"
$Results[$svc.Name] = "OK"
}
} else {
Write-Log "$($svc.Name): Log file not found" "Red"
$Results[$svc.Name] = "Not Found"
}
}
# Test APIs
Write-Log "Testing API endpoints..." "Yellow"
$apis = @(
@{Name="ExtAPI"; URL="https://${ServerIP}/exapi/message/getMsgPageList"; Expected="A0076"},
@{Name="Meeting"; URL="https://${ServerIP}/meetingV3/api/systemConfiguration/globalConfig?companyNumber=CN-SZ-00-0201"; Expected="A0078"},
@{Name="Monitor"; URL="https://${ServerIP}/monitor/api2/api/servermonitor/"; Expected="40000014"},
@{Name="Voice"; URL="https://${ServerIP}/voice/api/iflytek/roommaster?company_id=1&user_id=8&company_secret=57d00f9f-020f-5f1f-b788-55fae843bceb&getall=1"; Expected="40000003"}
)
foreach ($api in $apis) {
$curlResult = Invoke-SSHCommand -Command "curl -k '$($api.URL)' 2>/dev/null"
if ($curlResult.Output -match $api.Expected) {
Write-Log "$($api.Name): API OK" "Green"
$Results["$($api.Name)API"] = "OK"
} else {
Write-Log "$($api.Name): API Error" "Yellow"
$Results["$($api.Name)API"] = "Error"
}
}
# Generate report
Write-Log "Generating report..." "Yellow"
$report = @"
# Deployment Check Report
## Server: $ServerIP
## Results
- Connection: $($Results.Connection)
- Docker: $($Results.Docker)
## Services
"@
foreach ($svc in $services) {
$report += "`n- $($svc.Name): $($Results[$svc.Name])"
}
$report += "`n\n## APIs`n"
foreach ($api in $apis) {
$report += "`n- $($api.Name): $($Results["$($api.Name)API"])"
}
$report += @"
## Access URLs
- Frontend: https://${ServerIP}/
- Maintenance: https://${ServerIP}/#/LoginConfig
- Backend: https://${ServerIP}/#/LoginAdmin
---
Generated: $(Get-Date)
"@
$reportFile = Join-Path $ReportsDir "${ServerIP}_check_$(Get-Date -Format 'yyyyMMdd_HHmmss').md"
$report | Out-File -FilePath $reportFile -Encoding UTF8 -Force
Write-Log "Report saved to: $reportFile" "Green"
Write-Log "========================================" "Green"
Write-Log "Check completed!" "Green"
Write-Log "========================================" "Green"
# Complete Remote Deployment Script - New Unified Platform
# Author: Automation Team
# Date: 2026-05-14
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ReportsDir = Join-Path $ScriptDir "reports"
$TempDir = Join-Path $ScriptDir "temp"
# Create directories
if (-not (Test-Path $ReportsDir)) { New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null }
if (-not (Test-Path $TempDir)) { New-Item -ItemType Directory -Path $TempDir -Force | Out-Null }
$LogFile = Join-Path $ReportsDir "deploy_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] [$Level] $Message"
$Color = switch($Level) {
"INFO" { "White" }
"OK" { "Green" }
"WARN" { "Yellow" }
"ERROR" { "Red" }
"STEP" { "Cyan" }
default { "White" }
}
Write-Host $LogMessage -ForegroundColor $Color
Add-Content -Path $LogFile -Value $LogMessage
}
function Invoke-SSHCommand {
param([string]$Command, [int]$TimeoutMs = 300000)
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo
$StartInfo.FileName = $PlinkPath
$StartInfo.Arguments = "-pw $Password -P $SSHPort ${Username}@${ServerIP} $Command"
$StartInfo.UseShellExecute = $false
$StartInfo.RedirectStandardOutput = $true
$StartInfo.RedirectStandardError = $true
$StartInfo.CreateNoWindow = $true
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $StartInfo
try {
$Process.Start() | Out-Null
$Process.WaitForExit($TimeoutMs)
$Output = $Process.StandardOutput.ReadToEnd()
$StdErr = $Process.StandardError.ReadToEnd()
return @{
Success = ($Process.ExitCode -eq 0)
Output = $Output
Error = $StdErr
ExitCode = $Process.ExitCode
}
}
catch {
return @{
Success = $false
Output = ""
Error = $_.Exception.Message
ExitCode = -1
}
}
}
# Configuration
$ServerIP = "192.168.5.52"
$Username = "root"
$Password = "Ubains@123"
$SSHPort = 22
$DeployResults = @{
Connection = ""
ServerInfo = @{}
ContainerStatus = @{}
ServiceLogs = @{}
APITests = @{}
}
# Start deployment
Write-Log "========================================" "STEP"
Write-Log "New Unified Platform Deployment Script" "STEP"
Write-Log "Target: ${ServerIP} (X86)" "STEP"
Write-Log "Start: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" "STEP"
Write-Log "========================================" "STEP"
# Step 1: Test SSH connection
Write-Log "Step 1: Testing SSH connection" "STEP"
$TestResult = Invoke-SSHCommand -Command "echo 'connection_ok'"
if ($TestResult.Output -match "connection_ok") {
Write-Log "SSH connection successful" "OK"
$DeployResults.Connection = "成功"
} else {
Write-Log "SSH connection failed: $($TestResult.Error)" "ERROR"
exit 1
}
# Step 2: Get server information
Write-Log "`nStep 2: Getting server information" "STEP"
$OSInfo = Invoke-SSHCommand -Command "uname -a"
$DeployResults.ServerInfo.OS = $OSInfo.Output.Trim()
Write-Log "OS: $($DeployResults.ServerInfo.OS)" "INFO"
$DiskInfo = Invoke-SSHCommand -Command "df -h /home | awk 'NR==2 {print \$4}'"
$DeployResults.ServerInfo.DiskSpace = $DiskInfo.Output.Trim()
Write-Log "Home disk space: $($DeployResults.ServerInfo.DiskSpace)" "INFO"
# Check platform type
$PlatformCheck = Invoke-SSHCommand -Command "test -d /data/services && echo 'new' || echo 'old'"
$DeployResults.ServerInfo.PlatformType = $PlatformCheck.Output.Trim()
Write-Log "Platform type: $($DeployResults.ServerInfo.PlatformType)" "INFO"
# Step 3: Check Docker status
Write-Log "`nStep 3: Checking Docker status" "STEP"
$DockerCheck = Invoke-SSHCommand -Command "docker ps --format 'table {{.Names}}\t{{.Status}}' 2>&1"
if ($DockerCheck.ExitCode -eq 0) {
Write-Log "Docker is running" "OK"
Write-Host "`n========== Container Status ==========" -ForegroundColor Cyan
Write-Host $DockerCheck.Output
Write-Host "========== Container Status End ==========`n" -ForegroundColor Cyan
# Parse container status
$Lines = $DockerCheck.Output -split "`n"
foreach ($Line in $Lines) {
if ($Line -match "(\S+)\s+(\S+)") {
$Name = $Matches[1]
$Status = $Matches[2]
if ($Name -ne "NAMES") {
$DeployResults.ContainerStatus[$Name] = $Status
}
}
}
} else {
Write-Log "Docker is not running or not accessible" "WARN"
$DeployResults.ContainerStatus.Error = "Docker不可用"
}
# Step 4: Check service logs
Write-Log "`nStep 4: Checking service logs" "STEP"
$LogPaths = @{
"ExtAPI" = "/data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"
"InnerAPI" = "/data/services/api/java-meeting/java-meeting2.0/logs/ubains-INFO-AND-ERROR.log"
"Monitor" = "/data/services/api/python-cmdb/log/uinfo.log"
"Voice" = "/data/services/api/python-voice/log/uinfo.log"
}
foreach ($LogName in $LogPaths.Keys) {
$LogPath = $LogPaths[$LogName]
Write-Log "Checking $LogName log..." "INFO"
$LogResult = Invoke-SSHCommand -Command "tail -50 '$LogPath' 2>/dev/null || echo 'not_found'"
if ($LogResult.Output -match "not_found") {
Write-Log "$LogName log file not found" "WARN"
$DeployResults.ServiceLogs[$LogName] = "文件不存在"
} elseif ($LogName -eq "ExtAPI" -and $LogResult.Output -match "SYSTEMVERSION") {
Write-Log "$LogName log is normal (version detected)" "OK"
$DeployResults.ServiceLogs[$LogName] = "正常"
} elseif ($LogResult.Output -match "ERROR|Exception|Failed") {
Write-Log "$LogName log contains errors" "WARN"
$DeployResults.ServiceLogs[$LogName] = "发现异常"
} else {
Write-Log "$LogName log appears normal" "OK"
$DeployResults.ServiceLogs[$LogName] = "正常"
}
}
# Step 5: Test API endpoints
Write-Log "`nStep 5: Testing service endpoints" "STEP"
$APITests = @{
"ExtAPI" = @{ URL = "https://${ServerIP}/exapi/message/getMsgPageList"; Expected = "A0076" }
"Meeting" = @{ URL = "https://${ServerIP}/meetingV3/api/systemConfiguration/globalConfig?companyNumber=CN-SZ-00-0201"; Expected = "A0078" }
"Monitor" = @{ URL = "https://${ServerIP}/monitor/api2/api/servermonitor/"; Expected = "40000014" }
"Voice" = @{ URL = "https://${ServerIP}/voice/api/iflytek/roommaster?company_id=1&user_id=8&company_secret=57d00f9f-020f-5f1f-b788-55fae843bceb&getall=1"; Expected = "40000003" }
}
foreach ($APIName in $APITests.Keys) {
$API = $APITests[$APIName]
Write-Log "Testing $APIName endpoint..." "INFO"
$CurlResult = Invoke-SSHCommand -Command "curl -k '$($API.URL)' 2>/dev/null" -TimeoutMs 60000
if ($CurlResult.Output -match $API.Expected) {
Write-Log "$APIName endpoint is normal" "OK"
$DeployResults.APITests[$APIName] = "正常"
} elseif ($CurlResult.Output -match "nginx|Error") {
Write-Log "$APIName endpoint returns error page" "WARN"
$DeployResults.APITests[$APIName] = "异常"
} else {
Write-Log "$APIName endpoint: unknown response" "WARN"
$DeployResults.APITests[$APIName] = "未知"
}
}
# Step 6: Generate report
Write-Log "`nStep 6: Generating deployment report" "STEP"
$ReportContent = @"
# New Unified Platform Deployment Report
## Basic Information
- Server IP: $ServerIP
- Architecture: X86
- Deployment Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
## Deployment Results
### 1. SSH Connection
- Status: $($DeployResults.Connection)
### 2. Server Information
- OS: $($DeployResults.ServerInfo.OS)
- Disk Space: $($DeployResults.ServerInfo.DiskSpace)
- Platform: $($DeployResults.ServerInfo.PlatformType)
### 3. Container Status
"@
foreach ($Container in $DeployResults.ContainerStatus.Keys) {
$ReportContent += "`n- $Container : $($DeployResults.ContainerStatus[$Container])"
}
$ReportContent += @"
### 4. Service Logs
"@
foreach ($Log in $DeployResults.ServiceLogs.Keys) {
$ReportContent += "`n- $Log : $($DeployResults.ServiceLogs[$Log])"
}
$ReportContent += @"
### 5. API Tests
"@
foreach ($API in $DeployResults.APITests.Keys) {
$ReportContent += "`n- $API : $($DeployResults.APITests[$API])"
}
$ReportContent += @"
## System Access Addresses
- Frontend: https://${ServerIP}/
- Maintenance: https://${ServerIP}/#/LoginConfig
- Backend: https://${ServerIP}/#/LoginAdmin
---
Report Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
"@
$ReportFile = Join-Path $ReportsDir "${ServerIP}_deployment_report_$(Get-Date -Format 'yyyyMMdd_HHmmss').md"
$ReportContent | Out-File -FilePath $ReportFile -Encoding UTF8 -Force
Write-Log "Deployment report generated: $ReportFile" "OK"
# Completion
Write-Log "`n========================================" "OK"
Write-Log "Deployment check completed!" "OK"
Write-Log "========================================" "OK"
# Deployment Check Report
## Server: 192.168.5.52
## Results
- Connection: OK
- Docker: Not Running
## Services
- ExtAPI: Not Found
- InnerAPI: Not Found
- Monitor: Not Found
- Voice: Not Found
\n## APIs
- ExtAPI: Error
- Meeting: Error
- Monitor: Error
- Voice: Error
## Access URLs
- Frontend: https://192.168.5.52/
- Maintenance: https://192.168.5.52/#/LoginConfig
- Backend: https://192.168.5.52/#/LoginAdmin
---
Generated: 05/14/2026 18:28:55
# New Unified Platform Deployment Report
## Basic Information
- Server IP: 192.168.5.52
- Architecture: X86
- Deployment Time: 2026-05-14 18:19:05
## System Access Addresses
- Frontend Address: https://192.168.5.52/
- Maintenance Address: https://192.168.5.52/#/LoginConfig
- Backend Address: https://192.168.5.52/#/LoginAdmin
---
Report Generated Time: 2026-05-14 18:19:05
# New Unified Platform Deployment Report
## Basic Information
- Server IP: 192.168.5.52
- Architecture: X86
- Deployment Time: 2026-05-14 18:27:44
## System Access Addresses
- Frontend Address: https://192.168.5.52/
- Maintenance Address: https://192.168.5.52/#/LoginConfig
- Backend Address: https://192.168.5.52/#/LoginAdmin
---
Report Generated Time: 2026-05-14 18:27:44
# Upload and Deploy Script
# Author: Automation Team
# Date: 2026-05-14
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PackagesDir = Join-Path $ScriptDir "packages"
$ReportsDir = Join-Path $ScriptDir "reports"
# Create directories
if (-not (Test-Path $PackagesDir)) { New-Item -ItemType Directory -Path $PackagesDir -Force | Out-Null }
if (-not (Test-Path $ReportsDir)) { New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null }
$LogFile = Join-Path $ReportsDir "upload_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
function Write-Log {
param([string]$Message, [string]$Color = "White")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogMessage = "[$Timestamp] $Message"
Write-Host $LogMessage -ForegroundColor $Color
Add-Content -Path $LogFile -Value $LogMessage
}
function Invoke-SSHCommand {
param([string]$Command)
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw $Password -P $SSHPort ${Username}@${ServerIP} $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()
}
function Upload-File {
param([string]$LocalPath, [string]$RemotePath)
$PscpPath = Join-Path $ScriptDir "pscp.exe"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PscpPath
$psi.Arguments = "-pw $Password -P $SSHPort -batch '$LocalPath' '${Username}@${ServerIP}:${RemotePath}'"
$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(300000)
return $p.ExitCode -eq 0
}
# Configuration
$ServerIP = "192.168.5.52"
$Username = "root"
$Password = "Ubains@123"
$SSHPort = 22
# Network share path
$NetworkShare = "\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\X86部署包\全量版"
Write-Log "========================================" "Cyan"
Write-Log "Upload and Deploy Script" "Cyan"
Write-Log "========================================" "Cyan"
# Step 1: Copy from network share
Write-Log "Step 1: Copying deployment package from network share..." "Yellow"
Write-Log "Source: $NetworkShare" "Gray"
if (-not (Test-Path $NetworkShare)) {
Write-Log "Network share path not accessible!" "Red"
Write-Log "Please ensure:" "Yellow"
Write-Log "1. You are connected to the company network" "Yellow"
Write-Log "2. You have permission to access the share" "Yellow"
Write-Log "3. The network path is correct" "Yellow"
exit 1
}
# Clean local packages directory
if (Test-Path $PackagesDir) {
Remove-Item -Path "$PackagesDir\*" -Recurse -Force -ErrorAction SilentlyContinue
}
# Copy from network share
Write-Log "Copying files from network share (this may take a while)..." "Yellow"
try {
$Files = Get-ChildItem -Path $NetworkShare -Recurse -File -ErrorAction Stop
$TotalFiles = $Files.Count
$CopiedFiles = 0
foreach ($File in $Files) {
$RelativePath = $File.FullName.Substring($NetworkShare.Length + 1)
$DestPath = Join-Path $PackagesDir $RelativePath
$DestDir = Split-Path $DestPath
if (-not (Test-Path $DestDir)) {
New-Item -ItemType Directory -Path $DestDir -Force | Out-Null
}
Copy-Item -Path $File.FullName -Destination $DestPath -Force
$CopiedFiles++
if ($CopiedFiles % 10 -eq 0) {
Write-Progress -Activity "Copying deployment package" -Status "$CopiedFiles / $TotalFiles files" -PercentComplete (($CopiedFiles / $TotalFiles) * 100)
}
}
Write-Progress -Activity "Copying deployment package" -Completed
Write-Log "Copied $CopiedFiles files from network share" "Green"
$LocalPackageDir = $PackagesDir
}
catch {
Write-Log "Failed to copy from network share: $_" "Red"
Write-Log "Trying to list top-level directory..." "Yellow"
try {
$TopItems = Get-ChildItem -Path $NetworkShare -ErrorAction Stop
Write-Log "Found items in network share:" "Gray"
foreach ($Item in $TopItems) {
Write-Log " - $($Item.Name) ($($Item.Length) bytes)" "Gray"
}
}
catch {
Write-Log "Cannot access network share" "Red"
}
exit 1
}
# Step 2: Create deploy directory on server
Write-Log "`nStep 2: Creating deploy directory on server..." "Yellow"
Invoke-SSHCommand -Command "mkdir -p /home/deploy"
Write-Log "Deploy directory created" "Green"
# Step 3: Upload deployment package
Write-Log "`nStep 3: Uploading deployment package to server..." "Yellow"
$UploadFiles = Get-ChildItem -Path $LocalPackageDir -Recurse -File
$TotalUpload = $UploadFiles.Count
$UploadedCount = 0
$FailedUploads = @()
foreach ($File in $UploadFiles) {
$RelativePath = $File.FullName.Substring($LocalPackageDir.Length + 1)
$RemotePath = "/home/deploy/$RelativePath"
$RemoteDir = "/home/deploy/" + (Split-Path $RelativePath -Parent)
# Create remote directory
Invoke-SSHCommand -Command "mkdir -p '$RemoteDir'"
# Upload file
$Success = Upload-File -LocalPath $File.FullName -RemotePath $RemotePath
if ($Success) {
$UploadedCount++
} else {
$FailedUploads += $RelativePath
}
if ($UploadedCount % 10 -eq 0) {
Write-Progress -Activity "Uploading to server" -Status "$UploadedCount / $TotalUpload files" -PercentComplete (($UploadedCount / $TotalUpload) * 100)
}
}
Write-Progress -Activity "Uploading to server" -Completed
Write-Log "Uploaded $UploadedCount files to server" "Green"
if ($FailedUploads.Count -gt 0) {
Write-Log "Failed to upload $($FailedUploads.Count) files:" "Yellow"
foreach ($Failed in $FailedUploads) {
Write-Log " - $Failed" "Gray"
}
}
# Step 4: Check uploaded files
Write-Log "`nStep 4: Verifying uploaded files..." "Yellow"
$ServerFiles = Invoke-SSHCommand -Command "find /home/deploy -type f | wc -l"
Write-Log "Files on server: $ServerFiles" "Green"
# Step 5: Find deployment script
Write-Log "`nStep 5: Looking for deployment script..." "Yellow"
$DeployScripts = Invoke-SSHCommand -Command "find /home/deploy -name '*.sh' -type f 2>/dev/null | head -10"
Write-Log "Found deployment scripts:" "Gray"
Write-Host $DeployScripts.Output
Write-Log "`n========================================" "Green"
Write-Log "Upload completed!" "Green"
Write-Log "========================================" "Green"
Write-Log "Next steps:" "Yellow"
Write-Log "1. SSH to server: ssh root@${ServerIP}" "Gray"
Write-Log "2. Go to deploy directory: cd /home/deploy" "Gray"
Write-Log "3. Run deployment script" "Gray"
Write-Log "========================================" "Green"
@echo off
setlocal enabledelayedexpansion
REM ========================================
REM Upload and Deploy Script
REM ========================================
set SCRIPT_DIR=%~dp0
set PACKAGES_DIR=%SCRIPT_DIR%packages
set REPORTS_DIR=%SCRIPT_DIR%reports
set SERVER_IP=192.168.5.52
set USERNAME=root
set PASSWORD=Ubains@123
set SSH_PORT=22
set NETWORK_SHARE=\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\X86部署包\全量版
echo ========================================
echo Upload and Deploy Script
echo ========================================
echo.
REM Create directories
if not exist "%PACKAGES_DIR%" mkdir "%PACKAGES_DIR%"
if not exist "%REPORTS_DIR%" mkdir "%REPORTS_DIR%"
REM Step 1: Check network share
echo Step 1: Checking network share...
echo Source: %NETWORK_SHARE%
if not exist "%NETWORK_SHARE%" (
echo ERROR: Network share not accessible!
echo.
echo Possible reasons:
echo 1. Not connected to company network
echo 2. No permission to access share
echo 3. Network path is incorrect
pause
exit /b 1
)
echo OK: Network share is accessible
echo.
REM Step 2: List files
echo Step 2: Listing files in network share...
dir "%NETWORK_SHARE%" /b
echo.
REM Step 3: Copy files locally
echo Step 3: Copying files locally...
echo This may take a while...
robocopy "%NETWORK_SHARE%" "%PACKAGES_DIR%" /E /NFL /NDL /NJH /NJS
if %ERRORLEVEL% LSS 8 (
echo OK: Files copied locally
) else (
echo WARNING: Robocopy reported some issues
)
echo.
REM Step 4: Create deploy directory on server
echo Step 4: Creating deploy directory on server...
plink.exe -pw %PASSWORD% -P %SSH_PORT% %USERNAME%@%SERVER_IP% "mkdir -p /home/deploy && echo 'OK'"
echo.
echo.
REM Step 5: Upload files to server
echo Step 5: Uploading files to server...
echo This may take a long time depending on file size...
echo.
echo Using pscp to upload files...
pscp.exe -pw %PASSWORD% -P %SSH_PORT% -batch -r "%PACKAGES_DIR%\*" %USERNAME%@%SERVER_IP%:/home/deploy/
echo.
echo Upload completed
echo.
REM Step 6: Verify upload
echo Step 6: Verifying upload...
plink.exe -pw %PASSWORD% -P %SSH_PORT% %USERNAME%@%SERVER_IP% "find /home/deploy -type f | wc -l"
echo.
REM Step 7: Find deployment scripts
echo Step 7: Looking for deployment scripts...
plink.exe -pw %PASSWORD% -P %SSH_PORT% %USERNAME%@%SERVER_IP% "find /home/deploy -name '*.sh' -type f 2>/dev/null | head -10"
echo.
echo ========================================
echo Upload completed!
echo ========================================
echo.
echo Next steps to complete deployment:
echo 1. SSH to server: ssh root@%SERVER_IP%
echo 2. Go to deploy directory: cd /home/deploy
echo 3. Find and run the deployment script
echo 4. Follow the deployment prompts
echo.
echo After deployment completes:
echo 1. Access maintenance platform: https://%SERVER_IP%/#/LoginConfig
echo 2. Enter verification code: csba
echo 3. Upload license file from network share
echo ========================================
echo.
pause
# Upload and Deploy Script - Simplified
# Author: Automation Team
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PackagesDir = Join-Path $ScriptDir "packages"
$ReportsDir = Join-Path $ScriptDir "reports"
if (-not (Test-Path $PackagesDir)) { New-Item -ItemType Directory -Path $PackagesDir -Force | Out-Null }
if (-not (Test-Path $ReportsDir)) { New-Item -ItemType Directory -Path $ReportsDir -Force | Out-Null }
function Write-Log {
param([string]$Message, [string]$Color = "White")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$Timestamp] $Message" -ForegroundColor $Color
}
function Invoke-SSHCommand {
param([string]$Command)
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$Password = "Ubains@123"
$SSHPort = 22
$ServerIP = "192.168.5.52"
$Username = "root"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw $Password -P $SSHPort ${Username}@${ServerIP} $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()
}
function Upload-File {
param([string]$LocalPath, [string]$RemotePath)
$PscpPath = Join-Path $ScriptDir "pscp.exe"
$Password = "Ubains@123"
$SSHPort = 22
$ServerIP = "192.168.5.52"
$Username = "root"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PscpPath
$psi.Arguments = "-pw $Password -P $SSHPort -batch '$LocalPath' '${Username}@${ServerIP}:${RemotePath}'"
$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(300000)
return $p.ExitCode -eq 0
}
# Network share path (using single quotes to avoid encoding issues)
$NetworkShare = '\\192.168.9.9\发布版本\03服务器部署\临时使用-新统一平台\X86部署包\全量版'
Write-Log "========================================" "Cyan"
Write-Log "Upload and Deploy Script" "Cyan"
Write-Log "========================================" "Cyan"
# Step 1: Check network share
Write-Log "Step 1: Checking network share..." "Yellow"
Write-Log "Source: $NetworkShare" "Gray"
if (-not (Test-Path $NetworkShare)) {
Write-Log "ERROR: Network share not accessible!" "Red"
Write-Log "" "Yellow"
Write-Log "Possible reasons:" "Yellow"
Write-Log "1. Not connected to company network" "Gray"
Write-Log "2. No permission to access share" "Gray"
Write-Log "3. Network path is incorrect" "Gray"
Write-Log "" "Yellow"
Write-Log "Please check the path and try again." "Yellow"
Read-Host "Press Enter to exit"
exit 1
}
Write-Log "Network share is accessible" "Green"
# Step 2: List files in network share
Write-Log "" "Yellow"
Write-Log "Step 2: Listing files in network share..." "Yellow"
try {
$Items = Get-ChildItem -Path $NetworkShare -ErrorAction Stop
Write-Log "Found $($Items.Count) items:" "Gray"
foreach ($Item in $Items) {
if ($Item.PSIsContainer) {
Write-Log " [DIR] $($Item.Name)" "Gray"
} else {
$Size = [math]::Round($Item.Length / 1MB, 2)
Write-Log " [FILE] $($Item.Name) ($Size MB)" "Gray"
}
}
}
catch {
Write-Log "ERROR: Failed to list files: $_" "Red"
Read-Host "Press Enter to exit"
exit 1
}
# Step 3: Create deploy directory on server
Write-Log "" "Yellow"
Write-Log "Step 3: Creating deploy directory on server..." "Yellow"
$Result = Invoke-SSHCommand -Command "mkdir -p /home/deploy && echo 'OK'"
if ($Result -match "OK") {
Write-Log "Deploy directory created successfully" "Green"
} else {
Write-Log "ERROR: Failed to create deploy directory" "Red"
Read-Host "Press Enter to exit"
exit 1
}
# Step 4: Upload deployment package
Write-Log "" "Yellow"
Write-Log "Step 4: Uploading deployment package..." "Yellow"
Write-Log "This may take a while depending on file size..." "Gray"
# Clean local packages directory
if (Test-Path $PackagesDir) {
Remove-Item -Path "$PackagesDir\*" -Recurse -Force -ErrorAction SilentlyContinue
}
# Copy files locally first (for faster processing)
Write-Log "Copying files locally first..." "Gray"
try {
robocopy $NetworkShare $PackagesDir /E /NFL /NDL /NJH /NJS | Out-Null
Write-Log "Files copied locally" "Green"
}
catch {
Write-Log "Warning: Robocopy had issues, trying alternative..." "Yellow"
Copy-Item -Path "$NetworkShare\*" -Destination $PackagesDir -Recurse -Force -ErrorAction SilentlyContinue
}
# Get files to upload
$UploadFiles = Get-ChildItem -Path $PackagesDir -Recurse -File
$TotalFiles = $UploadFiles.Count
$UploadedCount = 0
Write-Log "Total files to upload: $TotalFiles" "Gray"
# Upload files
foreach ($File in $UploadFiles) {
$RelativePath = $File.FullName.Substring($PackagesDir.Length + 1)
$RemotePath = "/home/deploy/$RelativePath"
$RemoteDir = Split-Path $RemotePath -Parent
# Create remote directory
Invoke-SSHCommand -Command "mkdir -p '$RemoteDir'" | Out-Null
# Upload file
$Success = Upload-File -LocalPath $File.FullName -RemotePath $RemotePath
if ($Success) {
$UploadedCount++
}
if ($UploadedCount % 50 -eq 0) {
$Percent = [math]::Round(($UploadedCount / $TotalFiles) * 100)
Write-Log "Progress: $UploadedCount / $TotalFiles ($Percent%)" "Gray"
}
}
Write-Log "Uploaded $UploadedCount files to server" "Green"
# Step 5: Verify upload
Write-Log "" "Yellow"
Write-Log "Step 5: Verifying upload..." "Yellow"
$ServerFiles = Invoke-SSHCommand -Command "find /home/deploy -type f | wc -l"
Write-Log "Files on server: $ServerFiles" "Green"
# Step 6: Find deployment scripts
Write-Log "" "Yellow"
Write-Log "Step 6: Looking for deployment scripts..." "Yellow"
$DeployScripts = Invoke-SSHCommand -Command "find /home/deploy -name '*.sh' -type f 2>/dev/null | head -10"
if ($DeployScripts) {
Write-Log "Found deployment scripts:" "Gray"
$DeployScripts -split "`n" | Where-Object { $_ -ne "" } | ForEach-Object {
Write-Log " $_" "Gray"
}
} else {
Write-Log "No deployment scripts found" "Yellow"
}
Write-Log "" "Green"
Write-Log "========================================" "Green"
Write-Log "Upload completed successfully!" "Green"
Write-Log "========================================" "Green"
Write-Log "" "Yellow"
Write-Log "Next steps to complete deployment:" "Yellow"
Write-Log "1. SSH to server: ssh root@192.168.5.52" "Gray"
Write-Log "2. Go to deploy directory: cd /home/deploy" "Gray"
Write-Log "3. Find and run the deployment script" "Gray"
Write-Log "4. Follow the deployment prompts" "Gray"
Write-Log "" "Gray"
Write-Log "After deployment completes:" "Yellow"
Write-Log "1. Access maintenance platform: https://192.168.5.52/#/LoginConfig" "Gray"
Write-Log "2. Enter verification code: csba" "Gray"
Write-Log "3. Upload license file from network share" "Gray"
Write-Log "========================================" "Green"
Read-Host "Press Enter to exit"
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论