文件
yjyf/scratch/deploy_all.py
MiAn c664d0a5de feat(sms): 集成腾讯云短信插件并打通双端短信验证码业务链路
- 插件管理:集成 qcloudsms 腾讯云短信发送插件,配置应用AppID/AppKey、短信签名及各业务模板ID(登录、修改密码、重置密码、支付密码、订单核销通知)
- 业务封装:新增 SmsService 统一业务短信服务,实现防刷限流、冷却控制、短信验证码发送与防重放校验,支持完工订单自动下发客户核销码
- 接口层:恢复并升级 Sms 控制器,并在 Auth/MasterAuth/Security 控制器中支持手机验证码登录、找回登录密码及短信验证设置/修改支付密码
- 小程序端:用户端与师傅端登录页、账号安全中心、支付密码组件全面适配短信验证码交互,优化用户找回密码与支付密码安全操作流程
- 部署脚本:优化 deploy_all.py 打包剪枝逻辑,全局过滤深层 .git 目录并规范打包相对路径
2026-11-26 15:54:15 +08:00

212 行
8.8 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

import os
import sys
import tarfile
import time
import subprocess
import paramiko
# 按照用户要求:默认不自动同步数据库;只有显式指定 --sync-db 参数时才同步数据库
SYNC_DB = '--sync-db' in sys.argv
SERVER_IP = '8.137.181.63'
SSH_PORT = 22
SSH_USER = 'root'
SSH_PASS = 'liyanxia@6688'
REMOTE_SITE_DIR = '/www/wwwroot/yjyf.gzyakj.com.cn'
BACKUP_DIR = '/www/backup'
LOCAL_SERVER_DIR = r'd:\Projects\phpstudy_pro\WWW\yjyf\server'
LOCAL_SQL_PATH = r'd:\Projects\phpstudy_pro\WWW\yjyf\db\local_yjyf_deploy.sql'
LOCAL_TAR_PATH = r'd:\Projects\phpstudy_pro\WWW\yjyf\server_deploy.tar.gz'
print("==================================================")
if SYNC_DB:
print("=== 开始部署最新代码【包含数据库同步】到测试服务器 ===")
else:
print("=== 开始部署最新代码【纯代码部署,不同步数据库】到测试服务器 ===")
print("==================================================")
# 1. 本地数据库导出(仅在指定同步数据库时执行)
if SYNC_DB:
print("\n[步骤 1] 检查并导出本地数据库 yjyf...")
dump_cmd = [
'mysqldump.exe',
'-h127.0.0.1',
'-P3306',
'-uyjyf',
'-p4bRz2NYz6pDhsCk4',
'--column-statistics=0',
'--default-character-set=utf8mb4',
'--single-transaction',
'--quick',
'yjyf',
f'--result-file={LOCAL_SQL_PATH}'
]
ret = subprocess.run(dump_cmd, capture_output=True, text=True)
if ret.returncode != 0:
print(f"导出失败: {ret.stderr}")
exit(1)
sql_size = os.path.getsize(LOCAL_SQL_PATH)
print(f"本地数据库导出完成,文件路径: {LOCAL_SQL_PATH},大小: {sql_size / 1024:.2f} KB")
else:
print("\n[步骤 1] 跳过本地数据库导出(未开启数据库同步)")
# 2. 本地项目代码打包
print("\n[步骤 2] 打包本地 server 目录...")
exclude_dir_names = {'.git', 'runtime', '.idea', '.vscode', 'temp'}
exclude_files = {'.env', 'composer.phar'}
file_count = 0
with tarfile.open(LOCAL_TAR_PATH, 'w:gz') as tar:
for root, dirs, files in os.walk(LOCAL_SERVER_DIR):
# 深度剪枝:跳过任何匹配的目录(包括子模块的 .git)
dirs[:] = [d for d in dirs if d not in exclude_dir_names]
for file in files:
if file in exclude_files or file.endswith('.log') or file.endswith('.tmp'):
continue
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, LOCAL_SERVER_DIR).replace('\\', '/')
tar.add(full_path, arcname=rel_path)
file_count += 1
tar_size = os.path.getsize(LOCAL_TAR_PATH)
print(f"本地代码打包完成,共打包 {file_count} 个文件,压缩包大小: {tar_size / (1024 * 1024):.2f} MB")
# 3. 连接远程测试服务器
print("\n[步骤 3] 连接远程测试服务器 (8.137.181.63:22)...")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(SERVER_IP, port=SSH_PORT, username=SSH_USER, password=SSH_PASS, timeout=20)
def run_ssh(cmd, fail_on_err=False):
stdin, stdout, stderr = ssh.exec_command(cmd)
out = stdout.read().decode('utf-8', errors='ignore')
err = stderr.read().decode('utf-8', errors='ignore')
exit_status = stdout.channel.recv_exit_status()
if fail_on_err and exit_status != 0:
raise RuntimeError(f"命令执行失败 (code {exit_status}): {cmd}\nStdout: {out}\nStderr: {err}")
return out, err, exit_status
# 4. 远程测试环境全量备份(保障其它站点与原有数据绝不受损)
print("\n[步骤 4] 远程安全备份:仅备份 yjyf 站点代码(及按需备份数据库)...")
timestamp = time.strftime('%Y%m%d_%H%M%S')
run_ssh(f"mkdir -p {BACKUP_DIR}")
if SYNC_DB:
remote_db_bak = f"{BACKUP_DIR}/yjyf_db_backup_{timestamp}.sql"
print(f" 正在备份远程 yjyf 数据库至 {remote_db_bak} ...")
run_ssh(f"mysqldump -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf > {remote_db_bak}")
out_db, _, _ = run_ssh(f"ls -lh {remote_db_bak}")
print(f" 远程数据库备份完成: {out_db.strip()}")
# 备份站点代码
remote_site_bak = f"{BACKUP_DIR}/yjyf_site_backup_{timestamp}.tar.gz"
print(f" 正在备份远程 yjyf 站点代码至 {remote_site_bak} ...")
run_ssh(f"tar -zcf {remote_site_bak} -C /www/wwwroot yjyf.gzyakj.com.cn")
out_site, _, _ = run_ssh(f"ls -lh {remote_site_bak}")
print(f" 远程站点代码备份完成: {out_site.strip()}")
# 5. 上传并导入数据库(仅在 SYNC_DB 为 True 时执行)
if SYNC_DB:
print("\n[步骤 5] 上传并导入本地数据库至测试服务器 yjyf 库...")
sftp = ssh.open_sftp()
remote_tmp_sql = '/tmp/local_yjyf_deploy.sql'
print(f" 正在通过 SFTP 上传 {LOCAL_SQL_PATH} 到 {remote_tmp_sql} ...")
sftp.put(LOCAL_SQL_PATH, remote_tmp_sql)
print(" 上传完成,执行数据库导入...")
out_sql, err_sql, code_sql = run_ssh(f"mysql -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf < {remote_tmp_sql}")
if err_sql and 'Warning' not in err_sql:
print(f" [警告] 导入信息: {err_sql.strip()}")
else:
print(" 数据库导入成功!")
run_ssh(f"rm -f {remote_tmp_sql}")
sftp.close()
else:
print("\n[步骤 5] 跳过数据库上传与导入(保持测试服务器现有数据不变)")
# 6. 上传并解压站点代码,更新配置与权限
print("\n[步骤 6] 上传并部署后端代码到 /www/wwwroot/yjyf.gzyakj.com.cn ...")
remote_tmp_tar = '/tmp/server_deploy.tar.gz'
print(f" 正在通过 SFTP 上传 {LOCAL_TAR_PATH} 到 {remote_tmp_tar} ...")
sftp = ssh.open_sftp()
sftp.put(LOCAL_TAR_PATH, remote_tmp_tar)
print(" 上传完成,正在解压部署...")
run_ssh(f"tar -zxf {remote_tmp_tar} -C {REMOTE_SITE_DIR}")
run_ssh(f"rm -f {remote_tmp_tar}")
# 检查远程 .env 是否存在,若不存在则创建安全底线配置
check_env_out, _, _ = run_ssh(f"test -f {REMOTE_SITE_DIR}/.env && echo 'EXISTS' || echo 'MISSING'")
if check_env_out.strip() != 'EXISTS':
print(" 远程 .env 缺失,重新生成基础连接配置...")
remote_env_content = """[app]
debug = false
trace = false
[database]
hostname = 127.0.0.1
database = yjyf
username = yjyf
password = yjyf
hostport = 3306
prefix = fa_
"""
with sftp.file(f"{REMOTE_SITE_DIR}/.env", 'w') as f:
f.write(remote_env_content)
sftp.close()
# 保持 admin.php 与 s.php
run_ssh(f"cp -f {REMOTE_SITE_DIR}/public/s.php {REMOTE_SITE_DIR}/public/admin.php")
# 清理缓存,设置权限
print(" 清理 runtime 缓存并设置 www 用户权限...")
run_ssh(f"mkdir -p {REMOTE_SITE_DIR}/runtime/cache {REMOTE_SITE_DIR}/runtime/temp {REMOTE_SITE_DIR}/runtime/log")
run_ssh(f"rm -rf {REMOTE_SITE_DIR}/runtime/cache/* {REMOTE_SITE_DIR}/runtime/temp/*")
run_ssh(f"chown -R www:www {REMOTE_SITE_DIR}")
run_ssh(f"chmod -R 755 {REMOTE_SITE_DIR}")
# 重载 PHP-FPM
print(" 重载 PHP-FPM 服务...")
out_fpm, _, _ = run_ssh("/etc/init.d/php-fpm-85 reload")
print(f" PHP-FPM 重载状态: {out_fpm.strip()}")
time.sleep(2)
# 7. 部署后验证与质检
print("\n[步骤 7] 执行部署后全链路验证...")
# 7.1 验证 HTTP 服务响应
print(" 测试 HTTP 访问响应:")
out_http1, _, _ = run_ssh("curl -k -s -o /dev/null -w '%{http_code}' https://yjyf.gzyakj.com.cn/")
print(f" - 首页 (https://yjyf.gzyakj.com.cn/): HTTP {out_http1.strip()}")
out_http2, _, _ = run_ssh("curl -k -s -o /dev/null -w '%{http_code}' https://yjyf.gzyakj.com.cn/s.php/index/login")
print(f" - 后台登录页面 (https://yjyf.gzyakj.com.cn/s.php/index/login): HTTP {out_http2.strip()}")
out_cats, _, _ = run_ssh("curl -k -s https://yjyf.gzyakj.com.cn/api/home/cats")
print(f" - 分类接口 (/api/home/cats): {out_cats[:120]}...")
out_home, _, _ = run_ssh("curl -k -s https://yjyf.gzyakj.com.cn/api/home/index")
print(f" - 首页接口 (/api/home/index): {out_home[:120]}...")
out_master_auth, _, _ = run_ssh("curl -k -s -X POST https://yjyf.gzyakj.com.cn/api/master_auth/login -d 'mobile=18888888888'")
print(f" - 师傅端登录接口 (/api/master_auth/login): {out_master_auth[:120]}...")
# 7.2 验证 think 控制台指令
print("\n 测试 ThinkPHP 控制台命令:")
out_cmd, _, _ = run_ssh("php /www/wwwroot/yjyf.gzyakj.com.cn/think order:autoclose")
print(f" - php think order:autoclose: {out_cmd.strip()}")
# 7.3 验证其他站点未受影响
print("\n 验证其他站点未受影响:")
other_sites = ['fenleixinxi.gzyakj.com.cn', 'huaqiapp.gzyakj.com.cn', 'renqing', 'rqzb.gyscwl.com']
for s in other_sites:
out_s, _, _ = run_ssh(f"test -d /www/wwwroot/{s} && echo 'EXISTS' || echo 'NOT_FOUND'")
print(f" - 目录 /www/wwwroot/{s}: {out_s.strip()}")
# 清理本地临时压缩包
if os.path.exists(LOCAL_TAR_PATH):
os.remove(LOCAL_TAR_PATH)
ssh.close()
print("\n==================================================")
print("=== 部署全部圆满完成! ===")
print("==================================================")