diff --git a/README.md b/README.md index 42f2e6d..c50cc04 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ AutoDeploy 是一个面向 Windows 的 Spring Boot / SSM + Vue 本地自动化 - 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。 - 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。 - 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。 -- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 通过 `winget` 固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码;JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。 +- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 从 Oracle 官方归档下载安装包并校验 SHA-256,固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码;JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。 - 使用 Maven 或 Gradle 构建后端;已有可运行 JAR/WAR 时自动跳过重复构建。 - 将传统 SSM 项目的 WAR 发布到 Tomcat 9,并等待 8080 端口就绪。 - 前端缺少 `node_modules` 时自动执行 `npm install`,随后运行 `serve`、`dev` 或 `start` 脚本。 diff --git a/deploy_tool/gui.py b/deploy_tool/gui.py index 78b6a87..ccc6b22 100644 --- a/deploy_tool/gui.py +++ b/deploy_tool/gui.py @@ -366,40 +366,41 @@ class DeployWorkbench(tk.Tk): if tool_name == "Tomcat": self.install_tomcat_async() return + if tool_name == "MySQL": + self.install_mysql_async() + return try: command = build_install_command(tool_name) except ValueError as exc: messagebox.showwarning("暂不支持自动安装", str(exc)) return - mysql_note = "" - if tool_name == "MySQL": - mysql_note = ( - f"\n\n将安装 MySQL Community Server {MYSQL_VERSION},默认把 root 密码设置为 {MYSQL_ROOT_PASSWORD}," - "并永久允许 6 位弱密码。MySQL 仅开放本机连接,不自动开放 Windows 防火墙端口。" - ) - command_preview = " ".join(command).replace( - f"root_passwd={MYSQL_ROOT_PASSWORD}", "root_passwd=******" - ) if not messagebox.askyesno( f"确认安装 {tool_name}", f"即将通过 winget 安装 {tool_name}。\n\n" - f"命令: {command_preview}" - f"{mysql_note}\n\n" + f"命令: {' '.join(command)}\n\n" "安装可能需要管理员权限,并可能修改 PATH。是否继续?", ): return self._append_log(f"开始安装 {tool_name}...") - if tool_name == "MySQL": - threading.Thread(target=self._install_mysql_worker, args=(command,), daemon=True).start() - return threading.Thread( target=lambda: self.ui_queue.put(("install_done", (tool_name, run_install_command(command, self._thread_log)))), daemon=True, ).start() - def _install_mysql_worker(self, command: list[str]) -> None: + def install_mysql_async(self) -> None: + if not messagebox.askyesno( + "确认安装 MySQL", + f"将从 MySQL 官方归档下载 MySQL Community Server {MYSQL_VERSION} 完整安装包(约 354 MB)," + f"校验 SHA-256 后安装。\n\nroot 默认密码为 {MYSQL_ROOT_PASSWORD},并永久允许 6 位弱密码;" + "仅开放本机连接,不自动开放 Windows 防火墙端口。\n\n安装时会请求管理员权限,是否继续?", + ): + return + self._append_log(f"开始安装 MySQL {MYSQL_VERSION}...") + threading.Thread(target=self._install_mysql_worker, daemon=True).start() + + def _install_mysql_worker(self) -> None: try: - executable = install_mysql(command, self._thread_log) + executable = install_mysql(self._thread_log) except Exception as exc: self.ui_queue.put(("mysql_install_done", (None, str(exc)))) return diff --git a/deploy_tool/installer.py b/deploy_tool/installer.py index 54e9414..3f1b50e 100644 --- a/deploy_tool/installer.py +++ b/deploy_tool/installer.py @@ -27,7 +27,6 @@ WINGET_PACKAGES = { "Gradle": "Gradle.Gradle", "Node.js": "OpenJS.NodeJS.LTS", "Git": "Git.Git", - "MySQL": "Oracle.MySQL", } MAVEN_VERSION = "3.10.0" @@ -38,6 +37,12 @@ TOMCAT_ARCHIVE_NAME = f"apache-tomcat-{TOMCAT_VERSION}-windows-x64.zip" TOMCAT_DOWNLOAD_BASE = f"https://dlcdn.apache.org/tomcat/tomcat-9/v{TOMCAT_VERSION}/bin" MYSQL_VERSION = "8.0.43" MYSQL_ROOT_PASSWORD = "123456" +MYSQL_INSTALLER_ARCHIVE_NAME = f"mysql-installer-community-{MYSQL_VERSION}.0.msi" +MYSQL_INSTALLER_URL = ( + "https://downloads.mysql.com/archives/get/p/25/file/" + f"{MYSQL_INSTALLER_ARCHIVE_NAME}" +) +MYSQL_INSTALLER_SHA256 = "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80" ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%") @@ -86,14 +91,6 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st "--id", package_id, ] - if tool_name == "MySQL": - command.extend(["--version", MYSQL_VERSION]) - console_args = ( - f'CONSOLEARGS="install server;{MYSQL_VERSION};x64:*:' - "type=config;open_win_firewall=false;tcp_ip=true;port=3306;" - f'root_passwd={MYSQL_ROOT_PASSWORD} --silent --auto-handle-prereqs"' - ) - command.extend(["--override", console_args]) command.extend([ "--accept-source-agreements", "--accept-package-agreements", @@ -102,6 +99,22 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st return command +def build_mysql_installer_command(installer_path: Path) -> list[str]: + console_args = ( + f"CONSOLEARGS=install server;{MYSQL_VERSION};x64:*:" + "type=config;open_win_firewall=false;tcp_ip=true;port=3306;" + f"root_passwd={MYSQL_ROOT_PASSWORD} --silent --auto-handle-prereqs" + ) + return [ + "msiexec.exe", + "/i", + str(installer_path), + "/qn", + "/norestart", + console_args, + ] + + def find_mysql_executable() -> Path | None: discovered = shutil.which("mysql") if discovered: @@ -197,15 +210,81 @@ def configure_mysql_weak_password_policy( on_output("MySQL 已永久允许 6 位弱密码,root 默认密码配置完成。") -def install_mysql(command: list[str], on_output: Callable[[str], None]) -> Path: - exit_code = run_install_command(command, on_output) - if exit_code != 0: +def install_mysql( + on_output: Callable[[str], None], + opener: Callable[..., BinaryIO] | None = None, + elevated_runner: Callable[[list[str]], int] | None = None, +) -> Path: + open_url = opener or urllib.request.urlopen + run_elevated = elevated_runner or run_elevated_command + with tempfile.TemporaryDirectory(prefix="autodeploy-mysql-") as temporary: + installer_path = Path(temporary) / MYSQL_INSTALLER_ARCHIVE_NAME + on_output(f"正在从 MySQL 官方归档地址下载 MySQL Installer {MYSQL_VERSION}...") + _download_to_file(MYSQL_INSTALLER_URL, installer_path, open_url, on_output) + actual_checksum = _sha256(installer_path) + if actual_checksum.lower() != MYSQL_INSTALLER_SHA256.lower(): + raise RuntimeError("MySQL 安装包 SHA-256 校验失败,已停止安装。") + on_output("MySQL 安装包校验通过,正在请求管理员权限安装...") + exit_code = run_elevated(build_mysql_installer_command(installer_path)) + if exit_code not in {0, 1641, 3010}: raise RuntimeError(f"MySQL 安装命令失败,退出码: {exit_code}") + if exit_code in {1641, 3010}: + on_output("MySQL 安装完成,Windows 提示稍后需要重新启动。") executable = wait_for_mysql_executable() configure_mysql_weak_password_policy(executable, on_output) return executable +def run_elevated_command(command: list[str]) -> int: + if os.name != "nt": + return subprocess.run(command, shell=False).returncode + + from ctypes import wintypes + + class ShellExecuteInfo(ctypes.Structure): + _fields_ = [ + ("cbSize", wintypes.DWORD), + ("fMask", wintypes.ULONG), + ("hwnd", wintypes.HWND), + ("lpVerb", wintypes.LPCWSTR), + ("lpFile", wintypes.LPCWSTR), + ("lpParameters", wintypes.LPCWSTR), + ("lpDirectory", wintypes.LPCWSTR), + ("nShow", ctypes.c_int), + ("hInstApp", wintypes.HINSTANCE), + ("lpIDList", wintypes.LPVOID), + ("lpClass", wintypes.LPCWSTR), + ("hkeyClass", wintypes.HKEY), + ("dwHotKey", wintypes.DWORD), + ("hIcon", wintypes.HANDLE), + ("hProcess", wintypes.HANDLE), + ] + + shell_execute = ctypes.windll.shell32.ShellExecuteExW + shell_execute.argtypes = [ctypes.POINTER(ShellExecuteInfo)] + shell_execute.restype = wintypes.BOOL + info = ShellExecuteInfo() + info.cbSize = ctypes.sizeof(info) + info.fMask = 0x00000040 # SEE_MASK_NOCLOSEPROCESS + info.lpVerb = "runas" + info.lpFile = command[0] + info.lpParameters = subprocess.list2cmdline(command[1:]) + info.nShow = 0 + if not shell_execute(ctypes.byref(info)): + error_code = ctypes.windll.kernel32.GetLastError() + if error_code == 1223: + raise RuntimeError("用户取消了 MySQL 安装所需的管理员授权。") + raise OSError(error_code, "无法以管理员权限启动 MySQL 安装程序") + try: + ctypes.windll.kernel32.WaitForSingleObject(info.hProcess, 0xFFFFFFFF) + exit_code = wintypes.DWORD() + if not ctypes.windll.kernel32.GetExitCodeProcess(info.hProcess, ctypes.byref(exit_code)): + raise OSError(ctypes.windll.kernel32.GetLastError(), "无法读取 MySQL 安装程序退出码") + return int(exit_code.value) + finally: + ctypes.windll.kernel32.CloseHandle(info.hProcess) + + def _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]: environment = os.environ.copy() environment["MYSQL_PWD"] = password @@ -368,6 +447,14 @@ def _sha512(path: Path) -> str: return digest.hexdigest() +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + def _safe_extract_zip(archive_path: Path, destination: Path) -> None: destination.mkdir(parents=True, exist_ok=True) destination_resolved = destination.resolve() diff --git a/tests/test_installer.py b/tests/test_installer.py index 49f2551..4f75b82 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -11,9 +11,13 @@ from deploy_tool.installer import ( MAVEN_ARCHIVE_NAME, MYSQL_VERSION, MYSQL_ROOT_PASSWORD, + MYSQL_INSTALLER_SHA256, + MYSQL_INSTALLER_URL, + build_mysql_installer_command, configure_mysql_weak_password_policy, TOMCAT_VERSION, install_maven, + install_mysql, install_tomcat, build_install_command, explain_install_failure, @@ -104,18 +108,45 @@ class InstallerTests(unittest.TestCase): self.assertIn("--accept-package-agreements", command) self.assertIn("--disable-interactivity", command) - def test_builds_unattended_mysql_winget_install_command(self): - command = build_install_command("MySQL") + def test_builds_unattended_mysql_msi_install_command(self): + command = build_mysql_installer_command(Path("mysql-installer.msi")) - self.assertEqual(command[0:5], ["winget", "install", "--exact", "--id", "Oracle.MySQL"]) - self.assertEqual(command[command.index("--version") + 1], MYSQL_VERSION) + self.assertEqual(command[0:3], ["msiexec.exe", "/i", "mysql-installer.msi"]) self.assertEqual(MYSQL_VERSION, "8.0.43") - override = command[command.index("--override") + 1] - self.assertIn("root_passwd=123456", override) - self.assertIn("open_win_firewall=false", override) - self.assertIn("--accept-source-agreements", command) - self.assertIn("--accept-package-agreements", command) - self.assertIn("--disable-interactivity", command) + self.assertIn("root_passwd=123456", command[-1]) + self.assertIn("open_win_firewall=false", command[-1]) + self.assertEqual(MYSQL_INSTALLER_SHA256, "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80") + self.assertIn("downloads.mysql.com/archives/", MYSQL_INSTALLER_URL) + + def test_mysql_is_not_installed_from_stale_winget_manifest(self): + with self.assertRaises(ValueError): + build_install_command("MySQL") + + def test_installs_mysql_from_verified_official_archive(self): + installer_bytes = b"verified-mysql-installer" + checksum = hashlib.sha256(installer_bytes).hexdigest() + commands = [] + + def opener(_url, timeout): + return io.BytesIO(installer_bytes) + + def elevated_runner(command): + commands.append(command) + self.assertTrue(Path(command[2]).exists()) + return 0 + + with ( + patch("deploy_tool.installer.MYSQL_INSTALLER_SHA256", checksum), + patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")), + patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, + ): + messages = [] + executable = install_mysql(messages.append, opener=opener, elevated_runner=elevated_runner) + + self.assertEqual(executable, Path("mysql.exe")) + self.assertEqual(commands[0][0], "msiexec.exe") + self.assertTrue(any("校验通过" in message for message in messages)) + configure.assert_called_once() def test_persists_six_character_mysql_password_policy(self): query_result = CompletedProcess(