deploy.ps1 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # 前端部署脚本
  2. # 日期:2025-08-07
  3. # ========== 🛠️ 配置参数 ==========
  4. $sourceDir = "D:\project\ln-web\dist"
  5. $remoteUser = "liujia"
  6. $remoteIP = "43.137.10.199"
  7. $remotePath = "/work/web/dist" # 实际路径 /work/web/dist
  8. $sshPort = 22
  9. # === 准备文件 ===
  10. $timestamp = Get-Date -Format "yyyyMMddHHmmss"
  11. $zipPath = "D:\project\dist-$timestamp.zip"
  12. Write-Host "`n🗜️ 正在压缩 dist..." -ForegroundColor Cyan
  13. Compress-Archive -Path "$sourceDir\*" -DestinationPath $zipPath -CompressionLevel Optimal
  14. $zipSizeMB = [math]::Round((Get-Item $zipPath).Length / 1MB, 2)
  15. Write-Host "`n🚀 上传压缩包到服务器 ($zipSizeMB MB)..." -ForegroundColor Cyan
  16. scp -P $sshPort $zipPath "${remoteUser}@${remoteIP}:~/dist-latest.zip"
  17. # === 生成远程 bash 部署脚本 ===
  18. $remoteScript = @'
  19. #!/bin/bash
  20. set -e
  21. timestamp={0}
  22. tmpdir="/tmp/dist-temp-$timestamp"
  23. echo "📁 创建临时目录 $tmpdir"
  24. mkdir -p "$tmpdir"
  25. echo "📦 解压上传文件"
  26. unzip -qo ~/dist-latest.zip -d "$tmpdir"
  27. echo "🔒 设置 root 权限"
  28. sudo chown -R root:root "$tmpdir"
  29. if [ -d "{1}" ]; then
  30. echo "🕐 备份旧目录"
  31. sudo mv "{1}" "{1}-backup-$timestamp"
  32. fi
  33. echo "🚀 替换新目录"
  34. sudo mv "$tmpdir" "{1}"
  35. echo "🧹 删除压缩包"
  36. rm ~/dist-latest.zip
  37. echo "✅ 远程部署完成: {1} 替换成功"
  38. '@ -f $timestamp, $remotePath
  39. # === 写入为 LF 格式(避免 \r 问题)===
  40. $localScriptPath = "D:\project\deploy-temp.sh"
  41. $remoteScriptLF = $remoteScript -replace "`r", ""
  42. Set-Content -Path $localScriptPath -Value $remoteScriptLF -Encoding UTF8
  43. # === 上传并执行远程脚本 ===
  44. Write-Host "`n📤 上传远程部署脚本..." -ForegroundColor Cyan
  45. scp -P $sshPort $localScriptPath "${remoteUser}@${remoteIP}:~/deploy-temp.sh"
  46. Write-Host "`n📦 正在服务器上原子部署 ..." -ForegroundColor Cyan
  47. ssh -p $sshPort ${remoteUser}@${remoteIP} "bash ~/deploy-temp.sh"
  48. # === 清理 ===
  49. Write-Host "`n🧹 清理临时文件..." -ForegroundColor DarkGray
  50. ssh -p $sshPort ${remoteUser}@${remoteIP} 'rm ~/deploy-temp.sh'
  51. Remove-Item $zipPath, $localScriptPath -Force -ErrorAction SilentlyContinue
  52. Write-Host "`n✅ 部署完成,压缩包大小:$zipSizeMB MB" -ForegroundColor Green