import os import tarfile import time import subprocess import paramiko 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("==================================================") print("=== 开始自动化重新部署最新代码与数据库到测试服务器 ===") print("==================================================") # 1. 本地数据库导出 print("\n[步骤 1/7] 检查并导出本地数据库 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") # 2. 本地项目代码打包 print("\n[步骤 2/7] 打包本地 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/7] 连接远程测试服务器 (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/7] 远程安全备份:仅备份 yjyf 数据库与 yjyf 站点代码...") timestamp = time.strftime('%Y%m%d_%H%M%S') run_ssh(f"mkdir -p {BACKUP_DIR}") # 备份数据库 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. 上传并导入数据库(仅作用于 yjyf 数据库) print("\n[步骤 5/7] 上传并导入本地数据库至测试服务器 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}") # 6. 上传并解压站点代码,更新配置与权限 print("\n[步骤 6/7] 上传并部署后端代码到 /www/wwwroot/yjyf.gzyakj.com.cn ...") remote_tmp_tar = '/tmp/server_deploy.tar.gz' print(f" 正在通过 SFTP 上传 {LOCAL_TAR_PATH} 到 {remote_tmp_tar} ...") 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 配置 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_ [wechat] appid = wx40ca4b02d4d1cb58 secret = f661146ce627e2c57770b7d80164dd65 mch_id = 1119105317 key = ffyqcyyszhdhi398672363efnwvikxlv key_v3 = ffyqcyyszhdhi398672363efnwvikxlv public_key_id = PUB_KEY_ID_0111191053172026102200381630000600 notify_domain = https://yjyf.gzyakj.com.cn transfer_scene_id = 1005 transfer_single_limit = 200.00 transfer_daily_user_limit = 200.00 [tianditu] key = 55aee666be14cd0100874d6faf3c963c [sms] mock = 1 mock_code = 123456 """ 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(1) # 7. 部署后验证与质检 print("\n[步骤 7/7] 执行部署后全链路验证...") # 7.1 验证数据库表数量与核心表统计 out_tb, _, _ = run_ssh("mysql -uyjyf -pyjyf yjyf -e 'SHOW TABLES;'") remote_tables = [l.strip() for l in out_tb.strip().splitlines() if l.strip() and l.strip() != 'Tables_in_yjyf'] print(f" 远程 yjyf 数据库表数量: {len(remote_tables)}") # 验证 pricing_config 字段是否存在 out_col, _, _ = run_ssh("mysql -uyjyf -pyjyf yjyf -e \"SHOW COLUMNS FROM fa_service LIKE 'pricing_config';\"") print(f" fa_service.pricing_config 字段验证:\n{out_col.strip()}") check_sql = ( "SELECT 'fa_user' AS tb, COUNT(*) AS cnt FROM fa_user UNION ALL " "SELECT 'fa_master', COUNT(*) FROM fa_master UNION ALL " "SELECT 'fa_order', COUNT(*) FROM fa_order UNION ALL " "SELECT 'fa_service', COUNT(*) FROM fa_service UNION ALL " "SELECT 'fa_service_type', COUNT(*) FROM fa_service_type UNION ALL " "SELECT 'fa_agreement', COUNT(*) FROM fa_agreement UNION ALL " "SELECT 'fa_admin', COUNT(*) FROM fa_admin;" ) out_cnt, _, _ = run_ssh(f"mysql -uyjyf -pyjyf yjyf -e \"{check_sql}\"") print(f" 核心表统计:\n{out_cnt.strip()}") # 7.2 验证 HTTP 服务响应 print("\n 测试 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_dicts, _, _ = run_ssh("curl -k -s https://yjyf.gzyakj.com.cn/api/common/dicts") print(f" - 字典接口 (/api/common/dicts): {out_dicts[:120]}...") # 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("==================================================")