From 9d00c0b58e25a072c632cb1fc872d1ea026292d1 Mon Sep 17 00:00:00 2001 From: huangzhenpc Date: Wed, 2 Apr 2025 10:45:19 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=9D=E5=AD=98=E7=8E=B0=E6=9C=89=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=20=E5=A2=9E=E5=8A=A0=E5=9F=9F=E5=90=8D=E5=92=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=B6=E9=97=B4=E5=85=B3=E8=81=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DEPLOYMENT_README.md | 283 +++++++++++++++++++++++++++++++++++++++++++ fix_setup.py | 186 ++++++++++++++++++++++++++++ setup_environment.py | 100 +++++++++++++-- setup_patch.py | 225 ++++++++++++++++++++++++++++++++++ 4 files changed, 785 insertions(+), 9 deletions(-) create mode 100644 DEPLOYMENT_README.md create mode 100644 fix_setup.py create mode 100644 setup_patch.py diff --git a/DEPLOYMENT_README.md b/DEPLOYMENT_README.md new file mode 100644 index 0000000..651ec4d --- /dev/null +++ b/DEPLOYMENT_README.md @@ -0,0 +1,283 @@ +# Cursor自动化服务部署指南 + +本文档详细说明如何在新服务器上从零开始部署Cursor自动化服务,包括环境准备、数据库配置、服务启动等各个步骤。 + +## 系统要求 + +- **操作系统**: Linux (推荐Ubuntu/Debian),也支持Windows和macOS +- **Python版本**: 3.7+ +- **数据库**: MySQL 5.7+ 或 MariaDB 10+ +- **缓存系统**: Redis 5+ (可选但推荐) +- **内存**: 至少2GB RAM +- **存储**: 至少1GB可用空间 +- **网络**: 稳定的互联网连接 + +## 部署流程概述 + +1. 安装必要的系统依赖 +2. 准备Python环境 +3. 下载代码并安装依赖 +4. 配置和初始化数据库 +5. 导入邮箱账号 +6. 启动服务 +7. 设置为系统服务(可选) + +## 详细部署步骤 + +### 1. 安装必要的系统依赖 + +#### Ubuntu/Debian系统: + +```bash +# 更新系统包 +sudo apt update + +# 安装Python、MySQL和Redis +sudo apt install -y python3 python3-venv python3-full mysql-server redis-server + +# 安装pip和开发库 +sudo apt install -y python3-pip python3-dev default-libmysqlclient-dev build-essential +``` + +#### CentOS/RHEL系统: + +```bash +# 安装Python +sudo yum install -y python3 python3-devel + +# 安装MySQL +sudo yum install -y mariadb-server mariadb-devel + +# 安装Redis +sudo yum install -y redis + +# 启动服务 +sudo systemctl start mariadb +sudo systemctl start redis +sudo systemctl enable mariadb +sudo systemctl enable redis +``` + +### 2. 准备Python环境 + +```bash +# 创建项目目录 +mkdir -p /opt/cursor-service +cd /opt/cursor-service + +# 创建并激活虚拟环境 +python3 -m venv venv +source venv/bin/activate +``` + +### 3. 下载代码并安装依赖 + +```bash +# 下载代码(示例使用git,也可以直接上传文件) +git clone https://your-repo-url.git . +# 或者直接解压上传的zip文件 + +# 安装依赖 +pip install -r requirements.txt +pip install cryptography # 确保安装cryptography包 +``` + +### 4. 配置和初始化数据库 + +我们提供了两种初始化数据库的方式: + +#### 方式一:使用交互式设置向导(推荐) + +```bash +# 修复可能的MySQL格式化问题 +python fix_setup.py + +# 运行设置向导 +python setup_environment.py +``` + +设置向导将引导您完成: +- 配置服务器标识 +- 设置MySQL数据库连接信息 +- 配置Redis(可选) +- 创建数据库和表结构 + +#### 方式二:手动执行初始化脚本 + +```bash +# 直接运行数据库初始化脚本 +python init_database.py +``` + +脚本会交互式地询问: +- MySQL root用户名和密码 +- 应用数据库名和用户信息 +- Redis配置(可选) + +### 5. 导入邮箱账号 + +```bash +# 准备email.txt文件,格式为: +# email@example.com----密码----client_id----refresh_token + +# 运行导入脚本 +python import_emails.py +``` + +### 6. 启动服务 + +有多种方式可以启动服务: + +#### 方式一:使用统一管理脚本(推荐) + +```bash +# 启用并启动服务 +python start.py --enable + +# 或者直接启动(会根据数据库中的启用状态决定是否启动服务) +python start.py +``` + +#### 方式二:直接启动自动服务 + +```bash +# 直接启动自动化服务 +python auto_cursor_service.py +``` + +#### 方式三:仅运行注册进程 + +```bash +# 仅启动注册进程 +python main.py +``` + +### 7. 设置为系统服务(可选但推荐) + +#### 创建系统服务文件: + +```bash +sudo nano /etc/systemd/system/cursor-service.service +``` + +添加以下内容: + +```ini +[Unit] +Description=Cursor Auto Registration Service +After=network.target mysql.service redis.service + +[Service] +Type=simple +User=your_username +WorkingDirectory=/opt/cursor-service +ExecStart=/opt/cursor-service/venv/bin/python start.py +Restart=on-failure +RestartSec=10 + +[Install] +WantedBy=multi-user.target +``` + +#### 启动并设置开机自启: + +```bash +sudo systemctl daemon-reload +sudo systemctl start cursor-service +sudo systemctl enable cursor-service +``` + +## 管理服务 + +### 检查服务状态 + +```bash +# 查看服务状态 +python start.py --status + +# 如果设置为系统服务,可以使用 +sudo systemctl status cursor-service +``` + +### 启用/禁用服务 + +```bash +# 启用服务 +python start.py --enable + +# 禁用服务 +python start.py --disable +``` + +### 手动上传账号 + +```bash +python start.py --upload +``` + +## 数据库升级 + +如果您从旧版本升级,需要运行数据库升级脚本: + +```bash +python upgrade_database.py +``` + +这会添加新的`extracted`字段和相关索引,以支持账号上传功能。 + +## 监控与故障排除 + +### 日志文件 + +主要日志文件: +- `auto_cursor_service.log` - 自动服务日志 +- `upload_accounts.log` - 账号上传日志 +- `register.log` - 注册进程日志 + +### 常见问题解决 + +1. **数据库连接失败** + - 检查MySQL服务是否运行: `sudo systemctl status mysql` + - 验证数据库用户名和密码是否正确 + +2. **Redis连接失败** + - 检查Redis服务是否运行: `sudo systemctl status redis` + - 如不需要Redis,可在config.yaml中设置`use_redis: false` + +3. **服务无法启动** + - 检查日志文件中的具体错误信息 + - 确保所有依赖包都已安装: `pip install -r requirements.txt` + +4. **账号注册失败率高** + - 检查网络连接和代理设置 + - 查看注册日志中的具体错误信息 + +5. **邮箱账号不足** + - 手动导入更多邮箱账号: `python import_emails.py` + - 检查API获取邮箱是否正常 + +## 备份与维护 + +建议定期备份数据库: + +```bash +# MySQL备份 +mysqldump -u [用户名] -p [数据库名] > backup_$(date +%Y%m%d).sql +``` + +## 安全考虑 + +1. 使用强密码保护数据库 +2. 限制MySQL和Redis只接受本地连接 +3. 保护config.yaml文件,不要泄露API密钥和数据库密码 +4. 定期更新系统和依赖包 + +## 更新服务 + +更新服务代码后,请按以下步骤操作: + +1. 停止服务: `python start.py --disable` 或 `sudo systemctl stop cursor-service` +2. 更新代码 +3. 如有新的依赖,安装: `pip install -r requirements.txt` +4. 如有数据库结构变更,运行升级脚本: `python upgrade_database.py` +5. 重新启动服务: `python start.py --enable` 或 `sudo systemctl start cursor-service` \ No newline at end of file diff --git a/fix_setup.py b/fix_setup.py new file mode 100644 index 0000000..4c9366b --- /dev/null +++ b/fix_setup.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +""" +Cursor自动化服务 - 修复脚本 +添加虚拟环境支持并修复MySQL连接问题 +""" +import os +import sys +import subprocess +import shutil +import time + +# 彩色输出函数 +class Colors: + GREEN = '\033[92m' + YELLOW = '\033[93m' + RED = '\033[91m' + BLUE = '\033[94m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def print_success(msg): + print(f"{Colors.GREEN}✓ {msg}{Colors.ENDC}") + +def print_warning(msg): + print(f"{Colors.YELLOW}⚠ {msg}{Colors.ENDC}") + +def print_error(msg): + print(f"{Colors.RED}✗ {msg}{Colors.ENDC}") + +def print_title(title): + print("\n" + "=" * 60) + print(f"{Colors.BOLD}{Colors.BLUE}{title.center(60)}{Colors.ENDC}") + print("=" * 60 + "\n") + +def check_virtual_env(): + """检查是否在虚拟环境中运行""" + return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix) + +def setup_virtual_env(): + """设置Python虚拟环境""" + print_title("虚拟环境设置") + + if check_virtual_env(): + print_success("当前已在虚拟环境中运行") + return True + + print_warning("当前未在虚拟环境中运行") + create_venv = input("是否创建虚拟环境? (推荐) (y/n, 默认: y): ").strip().lower() + if create_venv == 'n': + print_warning("跳过虚拟环境创建") + return True + + venv_path = input("请输入虚拟环境路径 (默认: ./venv): ").strip() or "./venv" + + try: + # 创建虚拟环境 + print(f"创建虚拟环境: {venv_path}") + subprocess.check_call([sys.executable, "-m", "venv", venv_path]) + + # 获取激活脚本路径 + if sys.platform.startswith('win'): + activate_script = os.path.join(venv_path, "Scripts", "activate.bat") + python_exe = os.path.join(venv_path, "Scripts", "python.exe") + else: + activate_script = os.path.join(venv_path, "bin", "activate") + python_exe = os.path.join(venv_path, "bin", "python") + + # 创建安装脚本 + print("创建安装脚本...") + setup_script = "setup_venv.sh" + with open(setup_script, "w") as f: + if sys.platform.startswith('win'): + f.write(f"@echo off\n") + f.write(f"call {activate_script}\n") + f.write(f"pip install -r requirements.txt\n") + f.write(f"pip install cryptography\n") + f.write(f"python setup_environment.py\n") + f.write(f"pause\n") + else: + f.write(f"#!/bin/bash\n") + f.write(f"source {activate_script}\n") + f.write(f"pip install -r requirements.txt\n") + f.write(f"pip install cryptography\n") + f.write(f"python setup_environment.py\n") + + if not sys.platform.startswith('win'): + os.chmod(setup_script, 0o755) + + print_success(f"虚拟环境创建成功: {venv_path}") + print_success(f"安装脚本已创建: {setup_script}") + + print("\n请运行以下命令完成安装:") + if sys.platform.startswith('win'): + print(f" {setup_script}") + else: + print(f" ./{setup_script}") + + return False + except Exception as e: + print_error(f"创建虚拟环境失败: {str(e)}") + return True + +def fix_mysql_format_issue(): + """修复MySQL格式化问题""" + print_title("修复MySQL连接问题") + + if not os.path.exists("setup_environment.py"): + print_error("未找到setup_environment.py文件") + return False + + backup_file = f"setup_environment.py.bak.{int(time.time())}" + try: + # 创建备份 + shutil.copy2("setup_environment.py", backup_file) + print_success(f"已创建备份: {backup_file}") + + # 读取文件内容 + with open("setup_environment.py", "r", encoding="utf-8") as f: + content = f.read() + + # 修复格式化问题 + fixed_content = content + + # 1. 添加cryptography到required_packages + if "cryptography" not in content: + fixed_content = fixed_content.replace( + 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml"', + 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml",\n "cryptography"' + ) + print_success("已添加cryptography到依赖包列表") + + # 2. 修复CREATE USER语句的格式化问题 + if "cursor.execute(f\"CREATE USER '{db_user}'@'%'" in content: + fixed_content = fixed_content.replace( + "cursor.execute(f\"CREATE USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", + "cursor.execute(\"CREATE USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" + ) + print_success("已修复CREATE USER语句") + + # 3. 修复ALTER USER语句的格式化问题 + if "cursor.execute(f\"ALTER USER '{db_user}'@'%'" in content: + fixed_content = fixed_content.replace( + "cursor.execute(f\"ALTER USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", + "cursor.execute(\"ALTER USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" + ) + print_success("已修复ALTER USER语句") + + # 写入修复后的内容 + with open("setup_environment.py", "w", encoding="utf-8") as f: + f.write(fixed_content) + + print_success("MySQL连接问题修复完成") + return True + except Exception as e: + print_error(f"修复过程出错: {str(e)}") + try: + if os.path.exists(backup_file): + shutil.copy2(backup_file, "setup_environment.py") + print_warning("已恢复原始文件") + except: + pass + return False + +def main(): + print_title("Cursor自动化服务 - 修复工具") + + # 设置虚拟环境 + if not setup_virtual_env(): + # 如果创建了虚拟环境并生成了安装脚本,直接退出 + sys.exit(0) + + # 修复MySQL格式化问题 + if not fix_mysql_format_issue(): + print_error("修复失败,请手动检查setup_environment.py文件") + sys.exit(1) + + print_title("修复完成") + print("现在可以安全地运行设置向导:") + print(" python setup_environment.py") + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\n\n操作已取消") + sys.exit(1) \ No newline at end of file diff --git a/setup_environment.py b/setup_environment.py index 2fc518d..76e86bb 100644 --- a/setup_environment.py +++ b/setup_environment.py @@ -14,15 +14,6 @@ import random import string from typing import Dict, Any, Optional, Tuple -# 尝试导入必要的库,如果不存在则安装 -required_packages = [ - "loguru", - "pymysql", - "aiomysql", - "redis", - "pyyaml" -] - # 设置颜色输出 class Colors: HEADER = '\033[95m' @@ -61,6 +52,97 @@ def print_error(message): """打印错误信息""" print(f"{Colors.RED}✗ {message}{Colors.ENDC}") +# 检测虚拟环境 +def is_in_virtualenv(): + """检查是否在虚拟环境中运行""" + return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix) + +def setup_virtualenv(): + """设置虚拟环境""" + print_title("虚拟环境检测") + + if is_in_virtualenv(): + print_success("已在虚拟环境中运行") + return True + + print_warning("当前不在虚拟环境中运行") + create_venv = input("是否创建并使用虚拟环境? (推荐) (y/n, 默认: y): ").strip().lower() + + if create_venv == 'n': + print_warning("跳过虚拟环境创建,将直接在系统Python环境中安装依赖") + return True + + venv_path = input("请输入虚拟环境路径 (默认: ./venv): ").strip() or "./venv" + + try: + # 检查venv模块 + try: + import venv + has_venv = True + except ImportError: + has_venv = False + + if not has_venv: + print_warning("Python venv模块不可用,尝试安装...") + if sys.platform.startswith('linux'): + print("在Linux上安装venv模块...") + try: + subprocess.check_call(["sudo", "apt", "install", "-y", "python3-venv", "python3-full"]) + except: + try: + subprocess.check_call(["sudo", "yum", "install", "-y", "python3-venv"]) + except: + print_error("无法自动安装venv模块,请手动安装后重试") + print_warning("Ubuntu/Debian: sudo apt install python3-venv python3-full") + print_warning("CentOS/RHEL: sudo yum install python3-venv") + return False + else: + print_error("请安装Python venv模块后重试") + return False + + # 创建虚拟环境 + print_step("创建", f"正在创建虚拟环境: {venv_path}") + if sys.platform.startswith('win'): + subprocess.check_call([sys.executable, "-m", "venv", venv_path]) + else: + subprocess.check_call([sys.executable, "-m", "venv", venv_path]) + + # 计算激活脚本路径 + if sys.platform.startswith('win'): + activate_script = os.path.join(venv_path, "Scripts", "activate.bat") + python_path = os.path.join(venv_path, "Scripts", "python.exe") + else: + activate_script = os.path.join(venv_path, "bin", "activate") + python_path = os.path.join(venv_path, "bin", "python") + + print_success(f"虚拟环境创建成功: {venv_path}") + print_warning("请退出当前程序,然后执行以下命令激活虚拟环境并重新运行:") + + if sys.platform.startswith('win'): + print(f"\n{Colors.BOLD}Windows:{Colors.ENDC}") + print(f" {activate_script}") + print(f" python setup_environment.py") + else: + print(f"\n{Colors.BOLD}Linux/Mac:{Colors.ENDC}") + print(f" source {activate_script}") + print(f" python setup_environment.py") + + return False + + except Exception as e: + print_error(f"创建虚拟环境失败: {str(e)}") + return False + +# 尝试导入必要的库,如果不存在则安装 +required_packages = [ + "loguru", + "pymysql", + "aiomysql", + "redis", + "pyyaml", + "cryptography" # 添加这一行 +] + def check_and_install_packages(): """检查并安装必要的Python包""" print_step(1, "检查并安装必要的Python包") diff --git a/setup_patch.py b/setup_patch.py new file mode 100644 index 0000000..3a455d5 --- /dev/null +++ b/setup_patch.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +""" +Cursor自动化服务 - 设置脚本补丁 +修复MySQL连接和添加虚拟环境支持 +""" +import os +import sys +import subprocess +import shutil + +# 彩色输出 +class Colors: + GREEN = '\033[92m' + YELLOW = '\033[93m' + RED = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def print_title(title): + """打印标题""" + print(f"\n{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.ENDC}") + print(f"{Colors.BOLD}{Colors.GREEN}{title.center(60)}{Colors.ENDC}") + print(f"{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.ENDC}\n") + +def print_success(message): + """打印成功信息""" + print(f"{Colors.GREEN}✓ {message}{Colors.ENDC}") + +def print_warning(message): + """打印警告信息""" + print(f"{Colors.YELLOW}⚠ {message}{Colors.ENDC}") + +def print_error(message): + """打印错误信息""" + print(f"{Colors.RED}✗ {message}{Colors.ENDC}") + +def is_in_virtualenv(): + """检查是否在虚拟环境中运行""" + return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix) + +def setup_virtualenv(): + """设置虚拟环境""" + print_title("虚拟环境设置") + + if is_in_virtualenv(): + print_success("已在虚拟环境中运行") + return True + + print_warning("当前不在虚拟环境中运行") + create_venv = input("是否创建并使用虚拟环境? (推荐) (y/n, 默认: y): ").strip().lower() + + if create_venv == 'n': + print_warning("跳过虚拟环境创建,将直接在系统Python环境中安装依赖") + return True + + venv_path = input("请输入虚拟环境路径 (默认: ./venv): ").strip() or "./venv" + + try: + # 检查venv模块 + try: + subprocess.check_call([sys.executable, "-m", "venv", "--help"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + has_venv = True + except (subprocess.SubprocessError, ImportError): + has_venv = False + + if not has_venv: + print_warning("Python venv模块不可用,尝试安装...") + if sys.platform.startswith('linux'): + print("在Linux上安装venv模块...") + try: + subprocess.check_call(["sudo", "apt", "install", "-y", "python3-venv", "python3-full"], stdout=subprocess.DEVNULL) + print_success("venv模块安装成功") + except: + try: + subprocess.check_call(["sudo", "yum", "install", "-y", "python3-venv"], stdout=subprocess.DEVNULL) + print_success("venv模块安装成功") + except: + print_error("无法自动安装venv模块,请手动安装后重试") + print_warning("Ubuntu/Debian: sudo apt install python3-venv python3-full") + print_warning("CentOS/RHEL: sudo yum install python3-venv") + return False + else: + print_error("请安装Python venv模块后重试") + return False + + # 创建虚拟环境 + print("\n正在创建虚拟环境...") + subprocess.check_call([sys.executable, "-m", "venv", venv_path]) + + # 计算激活脚本路径 + if sys.platform.startswith('win'): + activate_script = os.path.join(venv_path, "Scripts", "activate.bat") + pip_path = os.path.join(venv_path, "Scripts", "pip.exe") + python_path = os.path.join(venv_path, "Scripts", "python.exe") + else: + activate_script = os.path.join(venv_path, "bin", "activate") + pip_path = os.path.join(venv_path, "bin", "pip") + python_path = os.path.join(venv_path, "bin", "python") + + print_success(f"虚拟环境创建成功: {venv_path}") + + # 安装依赖 + print("\n正在安装依赖包...") + if os.path.exists("requirements.txt"): + try: + if sys.platform.startswith('win'): + subprocess.check_call([pip_path, "install", "-r", "requirements.txt"]) + else: + script = f"""#!/bin/bash +source "{activate_script}" +pip install -r requirements.txt +pip install cryptography +echo "依赖安装完成,请运行以下命令启动设置向导:" +echo "source {activate_script}" +echo "python setup_environment.py" +""" + with open("setup_venv.sh", "w") as f: + f.write(script) + os.chmod("setup_venv.sh", 0o755) + print_success("已创建安装脚本: setup_venv.sh") + print("\n请运行以下命令完成安装并启动设置向导:") + print(f" bash ./setup_venv.sh") + except Exception as e: + print_error(f"安装依赖失败: {str(e)}") + print("\n请手动运行以下命令:") + print(f" source {activate_script}") + print(f" pip install -r requirements.txt") + print(f" pip install cryptography") + print(f" python setup_environment.py") + else: + print_warning("未找到requirements.txt文件") + print("\n请手动运行以下命令:") + print(f" source {activate_script}") + print(f" pip install loguru pymysql aiomysql redis pyyaml cryptography") + print(f" python setup_environment.py") + + return False + + except Exception as e: + print_error(f"创建虚拟环境失败: {str(e)}") + return False + +def patch_setup_script(): + """修补setup_environment.py脚本""" + print_title("修补设置脚本") + + if not os.path.exists("setup_environment.py"): + print_error("未找到setup_environment.py文件") + return False + + # 备份原始文件 + backup_file = f"setup_environment.py.bak.{int(os.path.getmtime('setup_environment.py'))}" + try: + shutil.copy2("setup_environment.py", backup_file) + print_success(f"已备份原始文件: {backup_file}") + except Exception as e: + print_error(f"备份文件失败: {str(e)}") + return False + + # 修改required_packages列表 + try: + with open("setup_environment.py", "r", encoding="utf-8") as f: + content = f.read() + + # 添加cryptography包 + if "cryptography" not in content: + content = content.replace( + 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml"', + 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml",\n "cryptography"' + ) + print_success("已添加cryptography包到依赖列表") + + # 修复MySQL字符串格式化问题 + if "CREATE USER '{db_user}'@'%'" in content: + content = content.replace( + "cursor.execute(f\"CREATE USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", + "cursor.execute(\"CREATE USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" + ) + print_success("已修复MySQL用户创建语句的格式化问题") + + if "ALTER USER '{db_user}'@'%'" in content: + content = content.replace( + "cursor.execute(f\"ALTER USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", + "cursor.execute(\"ALTER USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" + ) + print_success("已修复MySQL用户更新语句的格式化问题") + + # 写回文件 + with open("setup_environment.py", "w", encoding="utf-8") as f: + f.write(content) + + print_success("设置脚本修补完成") + return True + except Exception as e: + print_error(f"修补文件失败: {str(e)}") + try: + # 恢复备份 + shutil.copy2(backup_file, "setup_environment.py") + print_warning("已恢复原始文件") + except: + pass + return False + +def main(): + """主函数""" + print_title("Cursor自动化服务 - 设置补丁工具") + + # 设置虚拟环境 + if not setup_virtualenv(): + return + + # 修补设置脚本 + if not patch_setup_script(): + return + + print_title("补丁应用完成") + print("现在您可以安全地运行设置向导:") + print(" python setup_environment.py") + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("\n\n操作已取消") + sys.exit(1) \ No newline at end of file