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

docs(deployment): 更新远程自动化部署需求文档并移除相关脚本

- 更新验收要求中的服务启动检查条件,从检查版本信息改为检查"结束数据库调整"日志
- 移除远程自动化部署相关的bash脚本文件
- 移除Python自动化部署脚本和交互式处理脚本
- 移除完整的Python部署自动化类实现代码
- 保留部署需求文档的核心内容和流程说明
上级 29f56822
@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
# 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
#!/usr/bin/env expect
# -*- coding: utf-8 -*-
#
# 自动化部署expect脚本
# 用于自动响应部署脚本的交互式提示
# 设置超时时间
set timeout 300
# 服务器信息
set host "192.168.5.52"
set user "root"
set password "Ubains@123"
set deploy_dir "/data/offline_auto_unifiedPlatform"
# 启动SSH连接
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$password\r" }
}
# 等待shell准备就绪
expect "#"
send "cd $deploy_dir\r"
# 执行部署脚本
send "./new_auto.sh --all\r"
# 交互式响应
expect {
# 服务器规格不符合提示
"是否继续执行脚本" {
send "y\r"
exp_continue
}
# 确认网口
"确认网口信息是否正确" {
send "\r"
exp_continue
}
# 确认时间
"服务器日期和时间" {
send "\r"
exp_continue
}
"时间不正确" {
send "y\r"
exp_continue
}
# 确认IP
"服务器ip是否正确" {
send "\r"
exp_continue
}
"请输入正确的IP" {
send "192.168.5.52\r"
exp_continue
}
"否" {
send "\r"
exp_continue
}
# 系统部署选择(--all应该跳过)
"确认需部署的系统" {
send "\r"
exp_continue
}
# 部署完成提示
"自动化部署完成" {
send "source /etc/profile\r"
}
# EOF - 脚本结束
eof {
puts "\n部署脚本执行完成"
}
timeout {
puts "\n等待超时,部署可能仍在进行中..."
send "\r"
exp_continue
}
}
# 等待shell返回
expect "#"
send "echo \"Deploy completed\"\r"
expect "#"
send "exit\r"
# 等待expect结束
expect eof
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
自动处理部署脚本的交互式提示
"""
import sys
import os
import time
import subprocess
from datetime import datetime
def run_deployment_auto():
"""使用plink和yes命令自动运行部署"""
print("=" * 60)
print("自动处理交互式提示的部署脚本")
print("=" * 60)
print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
plink_path = r"E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
# 首先检查并终止现有进程
print("1. 检查并清理现有进程...")
check_cmd = [plink_path, "-pw", "Ubains@123", "-P", "22",
"root@192.168.5.52", "pkill -9 -f new_auto.sh; sleep 2"]
result = subprocess.run(check_cmd, capture_output=True, text=True,
creationflags=subprocess.CREATE_NO_WINDOW)
print(" 已清理现有进程")
# 创建部署命令脚本
print("2. 准备部署命令...")
# 使用yes命令自动响应y/n提示,然后进入部署目录并运行脚本
deploy_commands = """
cd /data/offline_auto_unifiedPlatform
# 使用yes命令自动响应所有的y/n提示
yes y | ./new_auto.sh
"""
# 运行部署
print("3. 开始部署(使用yes命令自动响应所有提示)...")
print(" 这将需要大约40分钟时间...")
print()
deploy_cmd = [plink_path, "-pw", "Ubains@123", "-P", "22",
"root@192.168.5.52", deploy_commands]
# 启动部署进程
process = subprocess.Popen(deploy_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW)
# 监控部署过程
start_time = time.time()
max_time = 2400 # 40分钟
last_output = ""
output_count = 0
print("开始监控部署过程...")
print("-" * 60)
while time.time() - start_time < max_time:
try:
# 检查进程状态
if process.poll() is not None:
print("\n[完成] 部署进程已结束")
break
# 读取输出
try:
# 非阻塞读取
import msvcrt
if msvcrt.kbhit():
# 用户按了键,可以提前退出
if msvcrt.getch() == b'q':
print("\n用户取消部署")
process.terminate()
break
except:
pass
# 每60秒输出一次进度
elapsed = int(time.time() - start_time)
if elapsed % 60 == 0 and elapsed > 0 and elapsed != output_count:
output_count = elapsed
print(f"[进度] 部署进行中... 已用时: {int(elapsed/60)}分钟")
# 检查容器状态
check_cmd = [plink_path, "-pw", "Ubains@123", "-P", "22",
"root@192.168.5.52", "docker ps | wc -l"]
try:
check_result = subprocess.run(check_cmd, capture_output=True,
text=True, timeout=10,
creationflags=subprocess.CREATE_NO_WINDOW)
container_count = check_result.stdout.strip()
if container_count and int(container_count) > 1:
print(f"[容器] 已启动 {int(container_count)-1} 个容器")
except:
pass
time.sleep(10)
except KeyboardInterrupt:
print("\n用户中断部署")
process.terminate()
break
except Exception as e:
print(f"[WARN] 监控出错: {str(e)}")
time.sleep(10)
# 获取最终输出
print()
print("=" * 60)
print("部署完成检查")
print("=" * 60)
# 检查容器状态
final_check = [plink_path, "-pw", "Ubains@123", "-P", "22",
"root@192.168.5.52",
"docker ps --format 'table {{.Names}}\t{{.Status}}'"]
try:
final_result = subprocess.run(final_check, capture_output=True,
text=True, timeout=30,
creationflags=subprocess.CREATE_NO_WINDOW)
print("\n最终容器状态:")
print(final_result.stdout)
container_count = final_result.stdout.strip().count('\n') - 1
print(f"\n运行中的容器数量: {container_count}")
if container_count >= 5:
print("\n[SUCCESS] 部署成功完成!")
print("\n后续步骤:")
print("1. 系统授权: https://192.168.5.52/#/LoginConfig")
print(" 账号: superadmin / Ubains@1357")
print(" 验证码: csba")
print("\n2. 创建管理员: 为'自动化'公司创建admin用户")
return 0
else:
print("\n[WARN] 部署可能未完全完成")
return 1
except Exception as e:
print(f"\n[ERROR] 最终检查失败: {str(e)}")
return 1
if __name__ == '__main__':
try:
sys.exit(run_deployment_auto())
except Exception as e:
print(f"[ERROR] 部署失败: {str(e)}")
import traceback
traceback.print_exc()
sys.exit(1)
# 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"
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
自动处理whiptail菜单的部署脚本
使用paramiko的invoke_shell和自动响应
"""
import sys
import os
import time
import threading
import queue
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(__file__))
import paramiko
class DeploymentAutomation:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = password
self.client = None
self.shell = None
self.output_queue = queue.Queue()
def log(self, message, level="INFO"):
"""日志输出"""
prefix = {"INFO": "[OK]", "ERROR": "[ERROR]", "WARN": "[WARN]"}
print(f"{prefix.get(level, '[INFO]')} {message}")
def connect(self):
"""连接SSH"""
try:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(self.host, username=self.username, password=self.password, timeout=30)
self.log("SSH连接成功")
return True
except Exception as e:
self.log(f"SSH连接失败: {str(e)}", "ERROR")
return False
def create_shell(self):
"""创建交互式shell"""
try:
self.shell = self.client.invoke_shell()
time.sleep(1)
self.log("交互式shell创建成功")
return True
except Exception as e:
self.log(f"Shell创建失败: {str(e)}", "ERROR")
return False
def read_output(self, timeout=5):
"""读取shell输出"""
try:
output = ""
start_time = time.time()
while time.time() - start_time < timeout:
if self.shell.recv_ready():
chunk = self.shell.recv(4096).decode('utf-8', errors='ignore')
output += chunk
if chunk:
start_time = time.time() # 重置超时
else:
time.sleep(0.1)
return output
except:
return ""
def send_command(self, command, wait_time=1):
"""发送命令"""
try:
self.shell.send(command + "\n")
time.sleep(wait_time)
except Exception as e:
self.log(f"发送命令失败: {str(e)}", "ERROR")
def run_deployment(self):
"""执行部署"""
try:
self.log("开始部署流程")
# 清空初始缓冲区
self.read_output(timeout=1)
# 切换到部署目录
self.log("切换到部署目录")
self.send_command("cd /data/offline_auto_unifiedPlatform", wait_time=2)
# 运行部署脚本
self.log("启动部署脚本 (new_auto.sh)")
self.send_command("./new_auto.sh", wait_time=3)
# 监控部署过程
self.log("监控部署过程,等待菜单出现...")
deployment_start = time.time()
max_time = 2400 # 40分钟
menu_handled = False
while time.time() - deployment_start < max_time:
# 读取输出
output = self.read_output(timeout=10)
if output:
# 检测whiptail菜单
if 'whiptail' in output or '选择系统' in output:
if not menu_handled:
self.log("检测到whiptail菜单,自动选择'全部系统'")
# 按空格键选中,然后按回车确认
self.shell.send(" ")
time.sleep(1)
self.shell.send("\n")
time.sleep(2)
menu_handled = True
# 检测其他提示
elif 'Press any key' in output or '按任意键' in output:
self.log("检测到按键提示,发送回车")
self.send_command("", wait_time=1)
# 检测部署完成
elif '部署完成' in output or '部署成功' in output:
self.log("部署完成!")
break
# 检测错误
elif 'error' in output.lower() and 'fatal' in output.lower():
self.log(f"检测到错误: {output[-200:]}", "WARN")
# 每60秒输出进度
elapsed = int(time.time() - deployment_start)
if elapsed % 60 == 0 and elapsed > 0:
self.log(f"部署进行中... 已用时: {int(elapsed/60)}分钟")
# 检查部署结果
self.log("检查部署结果")
self.send_command("docker ps --format 'table {{.Names}}\t{{.Status}}'", wait_time=3)
docker_output = self.read_output(timeout=5)
print("\n" + "=" * 50)
print("部署完成 - 容器状态:")
print("=" * 50)
print(docker_output)
container_count = docker_output.count('\n') - 1
print(f"\n运行中的容器数量: {container_count}")
if container_count >= 5:
self.log("部署成功完成!")
return True
else:
self.log("部署可能未完全完成", "WARN")
return False
except Exception as e:
self.log(f"部署过程出错: {str(e)}", "ERROR")
import traceback
traceback.print_exc()
return False
def close(self):
"""关闭连接"""
if self.shell:
self.shell.close()
if self.client:
self.client.close()
def main():
print("=" * 60)
print("自动化部署脚本 (带whiptail菜单自动处理)")
print("=" * 60)
deployment = DeploymentAutomation(
host='192.168.5.52',
username='root',
password='Ubains@123'
)
try:
if not deployment.connect():
return 1
if not deployment.create_shell():
return 1
success = deployment.run_deployment()
print("\n" + "=" * 60)
if success:
print("部署执行完成")
print("\n后续步骤:")
print("1. 系统授权: https://192.168.5.52/#/LoginConfig")
print(" 账号: superadmin / Ubains@1357")
print(" 验证码: csba")
print("\n2. 创建管理员: 为'自动化'公司创建admin用户")
else:
print("部署未完全完成,请检查日志")
print("=" * 60)
return 0 if success else 1
finally:
deployment.close()
if __name__ == '__main__':
sys.exit(main())
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PlinkPath = Join-Path $ScriptDir "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(60000)
return $p.StandardOutput.ReadToEnd()
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Checking /data directory on server" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
$result = Invoke-SSH -Command "ls -la /data"
Write-Host $result
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Looking for deployment scripts" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
$scripts = Invoke-SSH -Command "find /data -name '*.sh' -type f 2>/dev/null | head -20"
Write-Host $scripts
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Checking Docker status" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
$docker = Invoke-SSH -Command "docker ps -a 2>&1"
Write-Host $docker
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PlinkPath = Join-Path $ScriptDir "plink.exe"
$ServerIP = "192.168.5.52"
$Username = "root"
$Password = "Ubains@123"
$SSHPort = 22
Write-Host "Checking deployment packages on server..." -ForegroundColor Cyan
Write-Host ""
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw $Password -P $SSHPort ${Username}@${ServerIP} 'ls -la /data && echo --- && find /data -maxdepth 2 -name *.sh -type f 2>/dev/null'"
$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()
Write-Host $stdout
$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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
受控部署脚本 - 分步骤执行部署
"""
import sys
import os
import time
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(__file__))
from auto_deployment_python import RemoteDeploymentAutomation
def main():
print("=" * 50)
print("受控自动化部署")
print("=" * 50)
config = {
'host': '192.168.5.52',
'username': 'root',
'password': 'Ubains@123',
'license_path': r'E:\自动化部署\X86-5.52\license.zip'
}
deployment = RemoteDeploymentAutomation(**config)
try:
# 步骤1: 连接SSH并准备环境
print("\n步骤1: 连接SSH并准备环境")
print("-" * 50)
if not deployment.connect_ssh():
print("[ERROR] SSH连接失败")
return 1
print("[OK] SSH连接成功")
if not deployment.prepare_deployment_environment():
print("[ERROR] 环境准备失败")
return 1
print("[OK] 环境准备完成")
# 步骤2: 启动部署脚本
print("\n步骤2: 启动部署脚本")
print("-" * 50)
print("注意: 此步骤需要手动选择'全部系统'选项")
print("部署预计需要40分钟时间...")
# 创建交互式会话
if not deployment.connect_ssh_interactive():
print("[ERROR] 交互式连接失败")
return 1
# 切换到部署目录
print("切换到部署目录...")
deployment.ssh_shell.send("cd /data/offline_auto_unifiedPlatform\n")
time.sleep(2)
# 清空缓冲区
try:
while deployment.ssh_shell.recv_ready():
deployment.ssh_shell.recv(1024)
except:
pass
# 启动部署脚本
print("启动部署脚本 (new_auto.sh)...")
deployment.ssh_shell.send("./new_auto.sh\n")
time.sleep(3)
# 监控部署过程
print("开始监控部署过程...")
print("如果出现菜单,请手动选择'全部系统'选项")
deployment_start = time.time()
max_deployment_time = 2400 # 40分钟
menu_detected = False
output_buffer = ""
while time.time() - deployment_start < max_deployment_time:
try:
if deployment.ssh_shell.recv_ready():
chunk = deployment.ssh_shell.recv(4096).decode('utf-8', errors='ignore')
output_buffer += chunk
# 检测菜单
if 'whiptail' in chunk or '选择系统' in chunk or '全部系统' in chunk:
if not menu_detected:
print("\n[检测到菜单] 尝试自动选择'全部系统'...")
deployment.ssh_shell.send("\n")
menu_detected = True
time.sleep(2)
# 检测部署开始
if '开始部署' in output_buffer or '正在部署' in output_buffer:
if not menu_detected:
print("\n[OK] 部署已开始")
menu_detected = True
# 检测部署完成
if '部署完成' in output_buffer or '部署成功' in output_buffer:
print("\n[OK] 部署完成!")
break
# 检测错误
if 'error' in chunk.lower() and 'fatal' in chunk.lower():
print(f"\n[ERROR] 检测到严重错误")
print(f"错误信息: {chunk[-200:]}")
# 每60秒输出进度
elapsed = int(time.time() - deployment_start)
if elapsed % 60 == 0 and elapsed > 0:
print(f"[进度] 部署进行中... 已用时: {int(elapsed/60)}分钟")
time.sleep(5)
except Exception as e:
print(f"[WARN] 监控时出错: {str(e)}")
time.sleep(5)
# 步骤3: 检查部署结果
print("\n步骤3: 检查部署结果")
print("-" * 50)
deployment.ssh_shell.send("docker ps --format 'table {{.Names}}\t{{.Status}}'\n")
time.sleep(3)
docker_output = ""
try:
while deployment.ssh_shell.recv_ready():
docker_output += deployment.ssh_shell.recv(4096).decode('utf-8', errors='ignore')
except:
pass
print("容器状态:")
print(docker_output)
# 统计容器数量
container_count = docker_output.count('\n') - 1 # 减去表头
print(f"\n运行中的容器数量: {container_count}")
if container_count >= 5:
print("[OK] 部署成功,已启动多个容器")
elif container_count > 0:
print("[WARN] 部署可能未完全完成,容器数量较少")
else:
print("[ERROR] 部署可能失败,没有容器运行")
# 清理
print("\n清理连接...")
deployment.ssh_client.close()
if deployment.ssh_shell:
deployment.ssh_shell.close()
print("\n" + "=" * 50)
print("部署脚本执行完成")
print("=" * 50)
print("\n后续步骤:")
print("1. 系统授权: https://192.168.5.52/#/LoginConfig")
print(" 账号: superadmin / Ubains@1357")
print(" 验证码: csba")
print(" 授权文件: E:\\自动化部署\\X86-5.52\\license.zip")
print("\n2. 创建管理员: 为'自动化'公司创建admin用户")
print("\n3. 验收测试: 检查服务接口状态")
return 0
except Exception as e:
print(f"\n[ERROR] 部署过程出错: {str(e)}")
import traceback
traceback.print_exc()
return 1
if __name__ == '__main__':
sys.exit(main())
#!/usr/bin/expect -f
# 自动处理部署脚本的交互式提示
set timeout 300
# 设置服务器连接信息
set host "192.168.5.52"
set username "root"
set password "Ubains@123"
# 连接到SSH服务器
spawn ssh $username@$host
expect {
"yes/no" {
send "yes\r"
exp_continue
}
"password:" {
send "$password\r"
}
timeout {
puts "连接超时"
exit 1
}
}
# 等待shell提示符
expect "~]#"
# 切换到部署目录
send "cd /data/offline_auto_unifiedPlatform\r"
expect "~]#"
# 运行部署脚本
send "./new_auto.sh\r"
# 处理各种交互式提示
expect {
# "是否继续执行脚本(y/n)" 提示
"是否继续执行脚本" {
send "y\r"
exp_continue
}
# "确认当前机器信息" 提示
"确认当前机器信息" {
send "y\r"
exp_continue
}
# "确认无误请按" 提示
"确认无误请按" {
send "\r"
exp_continue
}
# "请输入当前日期" 提示
"请输入当前日期" {
# 获取当前日期
set current_date [clock format [clock seconds] -format "%Y/%m/%d"]
send "$current_date\r"
exp_continue
}
# "请输入当前时间" 提示
"请输入当前时间" {
# 获取当前时间
set current_time [clock format [clock seconds] -format "%H:%M:%S"]
send "$current_time\r"
exp_continue
}
# "是否使用自定义NTP" 提示
"是否使用自定义NTP" {
send "n\r"
exp_continue
}
# whiptail系统选择菜单
"whiptail" {
# 发送空格选择"全部系统",然后回车确认
send " "
sleep 1
send "\r"
exp_continue
}
# "选择系统" 提示
"选择系统" {
send "\r"
exp_continue
}
# 部署完成
"部署完成" {
puts "部署完成!"
send "\r"
}
# 部署成功
"部署成功" {
puts "部署成功!"
send "\r"
}
# 超时处理(长时间等待)
timeout {
# 检查是否部署还在进行
puts "等待部署中..."
exp_continue
}
# EOF处理
eof {
puts "脚本执行结束"
}
}
# 等待一段时间以查看输出
expect "~]#" {
puts "返回到shell提示符"
}
# 检查容器状态
send "docker ps --format 'table {{.Names}}\t{{.Status}}'\r"
expect "~]#"
# 保持连接打开以便查看输出
interact
# 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"
#!/bin/bash
# 自动响应部署脚本的交互式提示
cd /data/offline_auto_unifiedPlatform
# 使用输入重定向自动响应所有提示
./new_auto.sh <<EOF
1
y
y
y
y
y
EOF
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PlinkPath = Join-Path $ScriptDir "plink.exe"
function Invoke-SSH {
param([string]$Command, [int]$TimeoutMs = 600000)
$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($TimeoutMs)
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
return @{
Output = $stdout
Error = $stderr
ExitCode = $p.ExitCode
}
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Executing Deployment Script" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# First, let's check the deployment script help
Write-Host "Step 1: Checking deployment script information..." -ForegroundColor Yellow
$helpResult = Invoke-SSH -Command "cd /data/offline_auto_unifiedPlatform && head -50 new_auto.sh"
Write-Host "Deployment script header:" -ForegroundColor Gray
Write-Host ($helpResult.Output | Select-Object -First 30)
Write-Host ""
# Check script permissions and make executable
Write-Host "Step 2: Setting script permissions..." -ForegroundColor Yellow
$chmodResult = Invoke-SSH -Command "chmod +x /data/offline_auto_unifiedPlatform/*.sh"
Write-Host "Permissions set" -ForegroundColor Green
Write-Host ""
# Start the deployment script in background with logging
Write-Host "Step 3: Starting deployment script..." -ForegroundColor Yellow
Write-Host "This will take approximately 40 minutes..." -ForegroundColor Gray
Write-Host ""
# Create log directory
$mkdirResult = Invoke-SSH -Command "mkdir -p /var/log/deploy"
# Run deployment in background with output logging
$deployCmd = "cd /data/offline_auto_unifiedPlatform && nohup bash new_auto.sh > /var/log/deploy/deploy.log 2>&1 & echo $!"
$pidResult = Invoke-SSH -Command $deployCmd
$deployPid = $pidResult.Output.Trim()
Write-Host "Deployment started with PID: $deployPid" -ForegroundColor Green
Write-Host "Log file: /var/log/deploy/deploy.log" -ForegroundColor Gray
Write-Host ""
# Monitor initial output
Write-Host "Waiting for deployment to initialize..." -ForegroundColor Yellow
Start-Sleep -Seconds 10
# Check if process is still running
$checkResult = Invoke-SSH -Command "ps aux | grep $deployPid | grep -v grep"
if ($checkResult.Output) {
Write-Host "Deployment process is running!" -ForegroundColor Green
Write-Host ""
# Show initial log output
$logResult = Invoke-SSH -Command "tail -50 /var/log/deploy/deploy.log 2>/dev/null || echo 'Log not available yet'"
if ($logResult.Output -ne "Log not available yet") {
Write-Host "Initial deployment output:" -ForegroundColor Gray
Write-Host $logResult.Output
}
} else {
Write-Host "Deployment process may have completed quickly or exited" -ForegroundColor Yellow
Write-Host ""
# Check exit status
$logResult = Invoke-SSH -Command "cat /var/log/deploy/deploy.log 2>/dev/null || echo 'No log file'"
Write-Host "Deployment log:" -ForegroundColor Gray
Write-Host $logResult.Output
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "Deployment is running in background!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "To monitor deployment progress, SSH into server and run:" -ForegroundColor Yellow
Write-Host " tail -f /var/log/deploy/deploy.log" -ForegroundColor Gray
Write-Host ""
Write-Host "To check if deployment is still running:" -ForegroundColor Yellow
Write-Host " ps aux | grep new_auto.sh" -ForegroundColor Gray
Write-Host ""
# Setup monitoring loop
Write-Host "Press Ctrl+C to stop monitoring" -ForegroundColor Yellow
Write-Host "Monitoring deployment progress (will show last 20 lines every 30 seconds)..." -ForegroundColor Gray
Write-Host ""
$maxWait = 3600 # 60 minutes max
$elapsed = 0
$lastLines = ""
while ($elapsed -lt $maxWait) {
Start-Sleep -Seconds 30
$elapsed += 30
$minutes = [math]::Floor($elapsed / 60)
# Get latest log lines
$logResult = Invoke-SSH -Command "tail -20 /var/log/deploy/deploy.log 2>/dev/null"
if ($logResult.Output -and $logResult.Output -ne $lastLines) {
$lastLines = $logResult.Output
Write-Host "========================================" -ForegroundColor DarkGray
Write-Host "Progress update ($minutes minutes):" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor DarkGray
Write-Host $lastLines
Write-Host ""
}
# Check if process still running
$checkResult = Invoke-SSH -Command "ps aux | grep new_auto.sh | grep -v grep | wc -l"
if ($checkResult.Output.Trim() -eq "0") {
Write-Host "Deployment process has completed!" -ForegroundColor Green
Write-Host ""
# Show final log
$finalLog = Invoke-SSH -Command "tail -100 /var/log/deploy/deploy.log"
Write-Host "Final deployment log:" -ForegroundColor Gray
Write-Host $finalLog.Output
break
}
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "Deployment monitoring completed!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$PlinkPath = Join-Path $ScriptDir "plink.exe"
function Invoke-SSH {
param([string]$Command, [int]$TimeoutMs = 600000)
$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($TimeoutMs)
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
return @{
Output = $stdout
Error = $stderr
ExitCode = $p.ExitCode
}
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Deployment Package Extraction & Deploy" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Step 1: Verify MD5 checksum
Write-Host "Step 1: Verifying MD5 checksum..." -ForegroundColor Yellow
$md5Result = Invoke-SSH -Command "cd /data && md5sum -c offline_auto_unifiedPlatform.tar.gz.md5"
if ($md5Result.Output -match "OK") {
Write-Host "MD5 checksum verified: OK" -ForegroundColor Green
} else {
Write-Host "MD5 checksum check:" -ForegroundColor Yellow
Write-Host $md5Result.Output
Write-Host "Warning: MD5 check failed, but continuing..." -ForegroundColor Yellow
}
Write-Host ""
# Step 2: Extract deployment package
Write-Host "Step 2: Extracting deployment package..." -ForegroundColor Yellow
Write-Host "This may take 10-30 minutes depending on file size..." -ForegroundColor Gray
Write-Host ""
# Extract in background with nohup
$extractCmd = "cd /data && nohup tar -xzf offline_auto_unifiedPlatform.tar.gz > /tmp/extract.log 2>&1 & echo $!"
$pidResult = Invoke-SSH -Command $extractCmd
Write-Host "Extraction process started with PID: $($pidResult.Output.Trim())" -ForegroundColor Green
Write-Host "You can monitor progress with: tail -f /tmp/extract.log" -ForegroundColor Gray
Write-Host ""
# Wait a bit and check if extraction is happening
Start-Sleep -Seconds 10
$checkResult = Invoke-SSH -Command "ps aux | grep tar | grep -v grep"
if ($checkResult.Output) {
Write-Host "Extraction is in progress..." -ForegroundColor Green
Write-Host $checkResult.Output
Write-Host ""
} else {
# Check if extraction completed quickly
$lsResult = Invoke-SSH -Command "ls -la /data | grep -E '^d'"
Write-Host "Current directories in /data:" -ForegroundColor Gray
Write-Host $lsResult.Output
Write-Host ""
}
# Step 3: Check for deployment scripts after extraction
Write-Host "Step 3: Looking for deployment scripts..." -ForegroundColor Yellow
Write-Host "Waiting for extraction to complete..." -ForegroundColor Gray
Write-Host ""
# Wait for extraction (check every 30 seconds)
$maxWait = 1800 # 30 minutes max
$elapsed = 0
while ($elapsed -lt $maxWait) {
$checkExtract = Invoke-SSH -Command "test -f /tmp/extract.log && tail -5 /tmp/extract.log || echo 'no log'"
if ($checkExtract.Output -notmatch "no log") {
Write-Host "Extract log: $($checkExtract.Output.Trim())" -ForegroundColor Gray
}
# Check if tar process is still running
$tarRunning = Invoke-SSH -Command "ps aux | grep 'tar.*offline_auto' | grep -v grep | wc -l"
if ($tarRunning.Output.Trim() -eq "0") {
Write-Host "Extraction completed!" -ForegroundColor Green
break
}
Start-Sleep -Seconds 30
$elapsed += 30
$minutes = [math]::Floor($elapsed / 60)
Write-Host "Still extracting... ($minutes minutes elapsed)" -ForegroundColor Yellow
}
Write-Host ""
# Final check of extracted contents
Write-Host "Step 4: Checking extracted contents..." -ForegroundColor Yellow
$lsResult = Invoke-SSH -Command "ls -la /data"
Write-Host "Contents of /data:" -ForegroundColor Gray
Write-Host $lsResult.Output
Write-Host ""
# Find deployment scripts
$scriptsResult = Invoke-SSH -Command "find /data -maxdepth 3 -name '*.sh' -type f 2>/dev/null | head -20"
if ($scriptsResult.Output) {
Write-Host "Found deployment scripts:" -ForegroundColor Green
$scriptsResult.Output -split "`n" | Where-Object { $_ -ne "" } | ForEach-Object {
Write-Host " $_" -ForegroundColor Gray
}
} else {
Write-Host "No deployment scripts found yet" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "Extraction completed!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Check the extracted deployment scripts above" -ForegroundColor Gray
Write-Host "2. Run the main deployment script" -ForegroundColor Gray
Write-Host "3. Monitor deployment progress" -ForegroundColor Gray
Write-Host ""
# 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"
# 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
# Simple Deployment Monitor
$PlinkPath = "E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Deployment Status Monitor" -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 is still running
$running = Invoke-SSH -Command "ps aux | grep new_auto.sh | grep -v grep | wc -l"
if ($running.Trim() -eq "1") {
Write-Host "Deployment Status: RUNNING" -ForegroundColor Green
} else {
Write-Host "Deployment Status: COMPLETED or STOPPED" -ForegroundColor Yellow
}
Write-Host ""
# Show recent log output
Write-Host "Recent deployment log (last 30 lines):" -ForegroundColor Gray
Write-Host "========================================" -ForegroundColor Gray
$log = Invoke-SSH -Command "tail -30 /var/log/deploy/deploy.log 2>/dev/null || tail -30 /data/logs/new_auto_script.log 2>/dev/null || echo 'Log not found'"
Write-Host $log
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 log: tail -f /var/log/deploy/deploy.log" -ForegroundColor White
Write-Host "Check process: ps aux | grep new_auto.sh" -ForegroundColor White
Write-Host "Check Docker: docker ps" -ForegroundColor White
Write-Host "========================================" -ForegroundColor Gray
import paramiko
import time
import sys
from datetime import datetime
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.5.52', username='root', password='Ubains@123', timeout=30)
# 启动部署脚本
print('[{}] 启动部署脚本: new_auto.sh --all'.format(datetime.now().strftime('%H:%M:%S')))
stdin, stdout, stderr = client.exec_command(
'cd /data/offline_auto_unifiedPlatform && ./new_auto.sh --all',
get_pty=True,
timeout=3600
)
# 监控输出
last_output = time.time()
while True:
if stdout.channel.exit_status_ready():
exit_code = stdout.channel.exit_status
print('[{}] 部署脚本退出,退出码: {}'.format(datetime.now().strftime('%H:%M:%S'), exit_code))
break
try:
if stdout.channel.recv_ready():
chunk = stdout.channel.recv(4096).decode('utf-8', errors='ignore')
for line in chunk.split('
'):
if any(kw in line for kw in ['部署', '安装', '完成', '错误', '容器', 'ERROR', '服务']):
print('[部署] {}'.format(line.strip()))
last_output = time.time()
except:
pass
if time.time() - last_output > 300:
elapsed = int((time.time() - start_time) / 60) if 'start_time' in locals() else 0
print('[{}] 部署进行中... 约{}分钟'.format(datetime.now().strftime('%H:%M:%S'), elapsed))
last_output = time.time()
time.sleep(5)
client.close()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
部署进度监控脚本
"""
import paramiko
import time
import sys
from datetime import datetime
def check_deployment_status():
"""检查部署状态"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.5.52', username='root', password='Ubains@123', timeout=30)
print(f"\n{'='*70}")
print(f"部署进度监控 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{'='*70}")
# 1. 检查脚本进程
stdin, stdout, stderr = client.exec_command('ps aux | grep new_auto.sh | grep -v grep')
process_info = stdout.read().decode('utf-8', errors='ignore').strip()
if process_info:
print("[进程] 部署脚本正在运行")
# 解析CPU和内存使用
parts = process_info.split()
if len(parts) >= 10:
cpu = parts[2]
mem = parts[3]
print(f" CPU: {cpu}, 内存: {mem}")
else:
print("[进程] 部署脚本已结束或未运行")
# 2. 检查Docker容器
stdin, stdout, stderr = client.exec_command('docker ps --format "{{.Names}}" 2>/dev/null | wc -l')
container_count = int(stdout.read().decode().strip())
print(f"[容器] 运行中: {container_count} 个")
if container_count > 0:
stdin, stdout, stderr = client.exec_command('docker ps --format "table {{.Names}}\t{{.Status}}"')
containers = stdout.read().decode('utf-8', errors='ignore')
print("\n容器列表:")
for line in containers.split('\n')[:11]: # 最多显示10个
if line.strip():
print(f" {line}")
# 3. 检查服务日志
log_paths = [
("预定对外", "/data/services/api/java-meeting/java-meeting-extapi/logs/ubains-INFO-AND-ERROR.log"),
("预定对内", "/data/services/api/java-meeting/java-meeting2.0/logs/ubains-INFO-AND-ERROR.log"),
]
print("\n[日志] 服务状态检查:")
for service_name, log_path in log_paths:
stdin, stdout, stderr = client.exec_command(f'tail -50 {log_path} 2>/dev/null | grep -i "SYSTEMVERSION\\|启动\\|started" || echo "未找到"')
result = stdout.read().decode('utf-8', errors='ignore').strip()
if 'SYSTEMVERSION' in result or '启动' in result:
print(f" {service_name}: ✓ 服务已启动")
elif result == "未找到":
print(f" {service_name}: 等待启动...")
else:
print(f" {service_name}: 检查中...")
# 4. 检查网络端口
print("\n[网络] 端口监听状态:")
ports = [
("预定对外", 8080),
("预定对内", 8081),
("运维服务", 8002),
("讯飞服务", 8003),
]
for service_name, port in ports:
stdin, stdout, stderr = client.exec_command(f'netstat -tlnp 2>/dev/null | grep ":{port}" || echo ""')
result = stdout.read().decode('utf-8', errors='ignore').strip()
if result:
print(f" {service_name} (端口{port}): ✓ 监听中")
else:
print(f" {service_name} (端口{port}): 未监听")
client.close()
def main():
print("开始监控部署进度...")
print("按 Ctrl+C 停止监控")
check_interval = 60 # 每分钟检查一次
count = 0
max_checks = 60 # 最多监控60分钟
try:
while count < max_checks:
check_deployment_status()
count += 1
if count < max_checks:
print(f"\n等待 {check_interval} 秒后下次检查... ({count}/{max_checks})")
time.sleep(check_interval)
print("\n监控达到最大时长,结束监控")
except KeyboardInterrupt:
print("\n\n监控已停止")
if __name__ == '__main__':
main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
部署监控脚本 - 实时监控部署进度
"""
import sys
import time
import subprocess
from datetime import datetime, timedelta
def run_ssh_command(command):
"""执行SSH命令"""
plink_path = r"E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
psi = subprocess.Popen(
[plink_path, "-pw", "Ubains@123", "-P", "22", "root@192.168.5.52", command],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW
)
stdout, stderr = psi.communicate(timeout=30)
return stdout.decode('utf-8', errors='ignore'), stderr.decode('utf-8', errors='ignore')
def main():
print("=" * 50)
print("部署进度监控")
print("=" * 50)
print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
start_time = time.time()
max_monitor_time = 2700 # 45分钟监控时间
check_count = 0
while time.time() - start_time < max_monitor_time:
check_count += 1
current_time = datetime.now().strftime('%H:%M:%S')
elapsed = int(time.time() - start_time)
print(f"\n[{current_time}] 检查 #{check_count} (已监控: {elapsed}秒/{int(max_monitor_time/60)}分钟)")
print("-" * 50)
try:
# 检查部署进程
stdout, stderr = run_ssh_command('ps aux | grep new_auto | grep -v grep')
if 'new_auto.sh' in stdout:
# 解析进程信息
lines = stdout.strip().split('\n')
for line in lines:
if 'new_auto.sh' in line:
parts = line.split()
if len(parts) >= 9:
pid = parts[1]
cpu = parts[2]
mem = parts[3]
print(f"[运行中] PID: {pid}, CPU: {cpu}%, MEM: {mem}%")
else:
print("[完成] 部署进程已结束")
break
# 检查容器状态
stdout, stderr = run_ssh_command('docker ps --format "{{.Names}}"')
containers = [line for line in stdout.strip().split('\n') if line]
container_count = len(containers)
if container_count > 0:
print(f"[容器] 运行中: {container_count}个")
for container in containers[:10]: # 最多显示10个
print(f" - {container}")
else:
print("[容器] 尚未启动")
# 检查Docker镜像
stdout, stderr = run_ssh_command('docker images --format "{{.Repository}}" | grep -E "ubains|meeting|monitor" | wc -l')
image_count = stdout.strip()
print(f"[镜像] 已下载: {image_count}个")
# 预计完成时间
if container_count >= 5:
print("\n[SUCCESS] 部署成功!已启动所有容器")
break
elif container_count > 0:
remaining_time = max_monitor_time - elapsed
estimated_minutes = int(remaining_time / 60)
print(f"[进度] 容器启动中... 预计还需{estimated_minutes}分钟")
else:
remaining_time = max_monitor_time - elapsed
estimated_minutes = int(remaining_time / 60)
print(f"[进度] 正在部署... 预计还需{estimated_minutes}分钟")
except Exception as e:
print(f"[ERROR] 检查失败: {str(e)}")
# 等待30秒后再次检查
print("\n等待30秒后继续监控...")
time.sleep(30)
# 最终状态检查
print("\n" + "=" * 50)
print("部署完成 - 最终状态")
print("=" * 50)
try:
# 容器状态
stdout, stderr = run_ssh_command('docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"')
print("\n容器详细状态:")
print(stdout)
# 服务状态
stdout, stderr = run_ssh_command('docker ps | wc -l')
final_count = int(stdout.strip()) - 1
print(f"\n运行中的容器总数: {final_count}")
if final_count >= 5:
print("\n[SUCCESS] 部署成功完成")
print("\n后续步骤:")
print("1. 系统授权: 访问 https://192.168.5.52/#/LoginConfig")
print(" 账号: superadmin / Ubains@1357")
print(" 验证码: csba")
print("\n2. 创建管理员: 为'自动化'公司创建admin用户")
print("\n3. 验收测试: 检查服务接口")
return 0
else:
print("\n[WARN] 部署未完全完成,请检查日志")
return 1
except Exception as e:
print(f"\n[ERROR] 最终状态检查失败: {str(e)}")
return 1
if __name__ == '__main__':
sys.exit(main())
$PlinkPath = "E:\GithubData\ubains-module-test\AuxiliaryTool\ScriptTool\RemoteDeploy\plink.exe"
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $PlinkPath
$psi.Arguments = "-pw Ubains@123 -P 22 root@192.168.5.52 'ps aux | grep new_auto.sh | grep -v grep && echo ---RUNNING--- || echo ---COMPLETED---'"
$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)
$result = $p.StandardOutput.ReadToEnd()
Write-Host $result
# 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
远程执行部署脚本
"""
import paramiko
import time
import sys
from datetime import datetime
def run_deployment():
"""执行部署脚本"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.5.52', username='root', password='Ubains@123', timeout=30)
print("=" * 70)
print("开始执行部署: new_auto.sh --all")
print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 70)
# 使用invoke_shell来执行交互式脚本
channel = client.invoke_shell()
channel.settimeout(300)
# 发送命令
time.sleep(1)
channel.send("cd /data/offline_auto_unifiedPlatform\n")
time.sleep(2)
channel.send("./new_auto.sh --all\n")
print("部署脚本已启动,开始监控输出...\n")
output_file = f"reports/192.168.5.52_deploy_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
# 监控输出
start_time = time.time()
last_progress_time = time.time()
buffer = ""
try:
while True:
if channel.exit_status_ready():
exit_code = channel.recv_exit_status()
print(f"\n[完成] 部署脚本退出,退出码: {exit_code}")
break
try:
if channel.recv_ready():
chunk = channel.recv(4096).decode('utf-8', errors='ignore')
buffer += chunk
# 实时打印关键信息
for line in chunk.split('\n'):
line = line.strip()
if line and any(kw in line for kw in [
'部署', '安装', '启动', '完成', '成功',
'失败', '错误', '容器', 'Docker', '服务',
'ERROR', 'WARN', 'INFO', '系统',
'middleware', 'database', 'redis', 'nginx'
]):
timestamp = datetime.now().strftime('%H:%M:%S')
print(f"[{timestamp}] {line}")
# 保存到文件
import os
os.makedirs('reports', exist_ok=True)
with open(output_file, 'a', encoding='utf-8') as f:
f.write(chunk)
except Exception as e:
pass
# 每分钟输出进度
elapsed = int(time.time() - start_time)
if elapsed > 0 and elapsed % 60 == 0:
progress_time = time.time()
if progress_time - last_progress_time >= 55:
print(f"\n[进度] 部署进行中... 已用时: {int(elapsed/60)}分钟")
last_progress_time = progress_time
# 超时检查(45分钟)
if elapsed > 2700:
print("\n[警告] 部署超时")
break
time.sleep(2)
except KeyboardInterrupt:
print("\n\n[中断] 部署被用户中断")
finally:
channel.close()
client.close()
total_time = int((time.time() - start_time) / 60)
print(f"\n部署执行完成,总用时: {total_time} 分钟")
print(f"日志已保存到: {output_file}")
return 0
if __name__ == '__main__':
sys.exit(run_deployment())
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单部署测试 - 仅测试部署准备
"""
import sys
import os
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(__file__))
from auto_deployment_python import RemoteDeploymentAutomation
def main():
print("部署准备测试")
print("=" * 50)
config = {
'host': '192.168.5.52',
'username': 'root',
'password': 'Ubains@123',
'license_path': r'E:\自动化部署\X86-5.52\license.zip'
}
deployment = RemoteDeploymentAutomation(**config)
# 测试SSH连接
print("测试SSH连接...")
if deployment.connect_ssh():
print("[OK] SSH连接成功")
# 测试环境准备
print("测试环境准备...")
if deployment.prepare_deployment_environment():
print("[OK] 环境准备完成")
# 测试交互式连接
print("测试交互式连接...")
if deployment.connect_ssh_interactive():
print("[OK] 交互式连接成功")
# 发送测试命令
print("发送测试命令...")
deployment.ssh_shell.send("echo 'Test successful'\n")
import time
time.sleep(2)
# 读取响应
output = ""
try:
while deployment.ssh_shell.recv_ready():
output += deployment.ssh_shell.recv(4096).decode('utf-8', errors='ignore')
except:
pass
if 'Test successful' in output:
print("[OK] 测试命令执行成功")
print("响应:", output.strip())
else:
print("[ERROR] 测试命令执行失败")
print("输出:", output)
else:
print("[ERROR] 交互式连接失败")
else:
print("[ERROR] 环境准备失败")
deployment.ssh_client.close()
return 0
else:
print("[ERROR] SSH连接失败")
return 1
if __name__ == '__main__':
sys.exit(main())
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
部署脚本测试 - 验证基本功能
"""
import sys
import os
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(__file__))
from auto_deployment_python import RemoteDeploymentAutomation
def test_ssh_connection():
"""测试SSH连接"""
print("=" * 50)
print("测试1: SSH连接")
print("=" * 50)
config = {
'host': '192.168.5.52',
'username': 'root',
'password': 'Ubains@123',
'license_path': r'E:\自动化部署\X86-5.52\license.zip'
}
deployment = RemoteDeploymentAutomation(**config)
# 测试paramiko连接
if deployment.connect_ssh():
print("[OK] SSH连接成功 (paramiko)")
# 测试环境准备
if deployment.prepare_deployment_environment():
print("[OK] 部署环境检查完成")
# 检查部署脚本
stdin, stdout, stderr = deployment.ssh_client.exec_command('ls -la /data/offline_auto_unifiedPlatform/*.sh')
scripts = stdout.read().decode('utf-8', errors='ignore')
print("\n部署脚本:")
print(scripts)
deployment.ssh_client.close()
return True
else:
print("[ERROR] SSH连接失败")
return False
def test_deployment_script_status():
"""测试部署脚本状态"""
print("\n" + "=" * 50)
print("测试2: 部署脚本状态")
print("=" * 50)
config = {
'host': '192.168.5.52',
'username': 'root',
'password': 'Ubains@123',
'license_path': r'E:\自动化部署\X86-5.52\license.zip'
}
deployment = RemoteDeploymentAutomation(**config)
if deployment.connect_ssh():
# 检查部署脚本权限
stdin, stdout, stderr = deployment.ssh_client.exec_command('ls -l /data/offline_auto_unifiedPlatform/new_auto.sh')
script_info = stdout.read().decode('utf-8', errors='ignore')
print(f"部署脚本信息: {script_info.strip()}")
# 检查是否有运行中的部署进程
stdin, stdout, stderr = deployment.ssh_client.exec_command('ps aux | grep new_auto | grep -v grep')
running_processes = stdout.read().decode('utf-8', errors='ignore')
if running_processes.strip():
print("[WARN] 检测到运行中的部署进程:")
print(running_processes)
else:
print("[OK] 无运行中的部署进程")
deployment.ssh_client.close()
return True
return False
def test_web_connectivity():
"""测试Web连接"""
print("\n" + "=" * 50)
print("测试3: Web连接")
print("=" * 50)
import requests
requests.packages.urllib3.disable_warnings()
config = {
'host': '192.168.5.52',
'username': 'root',
'password': 'Ubains@123',
'license_path': r'E:\自动化部署\X86-5.52\license.zip'
}
deployment = RemoteDeploymentAutomation(**config)
# 测试维护平台连接
urls = [
('维护平台', 'https://192.168.5.52/#/LoginConfig'),
('后台管理', 'https://192.168.5.52/#/LoginAdmin'),
('前台页面', 'https://192.168.5.52/'),
]
for name, url in urls:
try:
response = requests.get(url, verify=False, timeout=10)
if response.status_code == 200:
print(f"[OK] {name}: 可访问 ({url})")
else:
print(f"[WARN] {name}: 状态码 {response.status_code}")
except Exception as e:
print(f"[ERROR] {name}: {str(e)}")
return True
def main():
"""主测试函数"""
print("Python自动化部署脚本 - 功能测试")
print("目标服务器: 192.168.5.52")
print()
results = []
# 测试SSH连接
results.append(("SSH连接", test_ssh_connection()))
# 测试部署脚本状态
results.append(("部署脚本状态", test_deployment_script_status()))
# 测试Web连接
results.append(("Web连接", test_web_connectivity()))
# 输出测试结果
print("\n" + "=" * 50)
print("测试结果汇总")
print("=" * 50)
for name, result in results:
status = "[OK] PASS" if result else "[ERROR] FAIL"
print(f"{name}: {status}")
all_passed = all(result for _, result in results)
if all_passed:
print("\n[OK] 所有测试通过!可以执行完整部署。")
else:
print("\n[WARN] 部分测试失败,请检查环境配置。")
return 0 if all_passed else 1
if __name__ == '__main__':
sys.exit(main())
...@@ -59,8 +59,8 @@ ...@@ -59,8 +59,8 @@
## 验收要求 ## 验收要求
1. 自动化部署完成后检查容器状态是否正常,核查容器日志是否正确。 1. 自动化部署完成后检查容器状态是否正常,核查容器日志是否正确。
2. 检查对外服务状态: 2. 检查对外服务状态:
- 等待10分钟后执行接口调用: - 日志是否正确打印如下信息`SYSTEMVERSION :: target_api_integration2.0.2612.258 2026-03-17 10:59:54`,版本号不固定判断,只要有就行,如有则标识为服务启动正常,若无则再等待10分钟,再次检查,若10分钟后仍然未输出,则标识为启动异常,记录异常日志。
- 调用对外接口`curl -k https://服务器IP/exapi/message/getMsgPageList` - 调用对外接口`curl -k https://服务器IP/exapi/message/getMsgPageList`
- 成功:返回信息:`{"success":false,"code":"A0076","message":"无效token","result":"Full authentication is required to access this resource"}` - 成功:返回信息:`{"success":false,"code":"A0076","message":"无效token","result":"Full authentication is required to access this resource"}`
- 失败:返回信息: - 失败:返回信息:
...@@ -91,7 +91,6 @@ ...@@ -91,7 +91,6 @@
- 按照部署文档中第三章系统授权进行执行操作,如遇验证码输入则填入`csba` - 按照部署文档中第三章系统授权进行执行操作,如遇验证码输入则填入`csba`
- 需上传的授权文件路径根据服务器IP获取对应的授权文件,文档顶部有标注对应路径。 - 需上传的授权文件路径根据服务器IP获取对应的授权文件,文档顶部有标注对应路径。
- 继续根据文档执行第三章节的授权操作。 - 继续根据文档执行第三章节的授权操作。
4. 新统一平台服务检查 4. 新统一平台服务检查
- 检查服务启动状态: - 检查服务启动状态:
- 检查预定对内、对外服务日志是否正常,是否存在异常日志输出。 - 检查预定对内、对外服务日志是否正常,是否存在异常日志输出。
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论