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_prefixes = [ os.path.join(LOCAL_SERVER_DIR, 'runtime'), os.path.join(LOCAL_SERVER_DIR, '.git'), os.path.join(LOCAL_SERVER_DIR, '.idea'), os.path.join(LOCAL_SERVER_DIR, '.vscode') ] 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): if any(root.startswith(p) for p in exclude_prefixes): continue 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) 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("==================================================")