Enable six character MySQL passwords by default

This commit is contained in:
王鹏
2026-10-09 09:09:47 +08:00
parent 5e5e075d33
commit 3116ba81c5
4 changed files with 213 additions and 5 deletions

View File

@@ -8,7 +8,7 @@ AutoDeploy 是一个面向 Windows 的 Spring Boot / SSM + Vue 本地自动化
- 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。 - 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。
- 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。 - 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。
- 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。 - 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。
- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 通过 `winget` 固定安装 8.0.43,JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。 - Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 通过 `winget` 固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码;JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。
- 使用 Maven 或 Gradle 构建后端;已有可运行 JAR/WAR 时自动跳过重复构建。 - 使用 Maven 或 Gradle 构建后端;已有可运行 JAR/WAR 时自动跳过重复构建。
- 将传统 SSM 项目的 WAR 发布到 Tomcat 9,并等待 8080 端口就绪。 - 将传统 SSM 项目的 WAR 发布到 Tomcat 9,并等待 8080 端口就绪。
- 前端缺少 `node_modules` 时自动执行 `npm install`,随后运行 `serve`、`dev` 或 `start` 脚本。 - 前端缺少 `node_modules` 时自动执行 `npm install`,随后运行 `serve`、`dev` 或 `start` 脚本。

View File

@@ -10,10 +10,12 @@ from .deployer import DeploymentConfig, build_deployment_plan, run_steps
from .environment import EnvironmentCheck, check_environment, load_tool_paths, save_tool_paths from .environment import EnvironmentCheck, check_environment, load_tool_paths, save_tool_paths
from .installer import ( from .installer import (
MAVEN_VERSION, MAVEN_VERSION,
MYSQL_ROOT_PASSWORD,
MYSQL_VERSION, MYSQL_VERSION,
TOMCAT_VERSION, TOMCAT_VERSION,
build_install_command, build_install_command,
install_maven, install_maven,
install_mysql,
install_tomcat, install_tomcat,
recommend_jdk_version, recommend_jdk_version,
run_install_command, run_install_command,
@@ -54,7 +56,7 @@ class DeployWorkbench(tk.Tk):
self.user_frontend_port = tk.StringVar(value="8082") self.user_frontend_port = tk.StringVar(value="8082")
self.admin_frontend_port = tk.StringVar(value="8081") self.admin_frontend_port = tk.StringVar(value="8081")
self.mysql_user = tk.StringVar(value="root") self.mysql_user = tk.StringVar(value="root")
self.mysql_password = tk.StringVar() self.mysql_password = tk.StringVar(value=MYSQL_ROOT_PASSWORD)
self.mysql_database = tk.StringVar() self.mysql_database = tk.StringVar()
self.output_dir = tk.StringVar() self.output_dir = tk.StringVar()
self.jdk_version = tk.StringVar(value="8") self.jdk_version = tk.StringVar(value="8")
@@ -372,23 +374,37 @@ class DeployWorkbench(tk.Tk):
mysql_note = "" mysql_note = ""
if tool_name == "MySQL": if tool_name == "MySQL":
mysql_note = ( mysql_note = (
f"\n\n将安装 MySQL Community Server {MYSQL_VERSION} 及官方工具。首次安装后,请在部署配置中填写实际的 " f"\n\n将安装 MySQL Community Server {MYSQL_VERSION},默认把 root 密码设置为 {MYSQL_ROOT_PASSWORD},"
"root 用户密码;程序不会生成、保存或显示默认数据库密码。" "并永久允许 6 位弱密码。MySQL 仅开放本机连接,不自动开放 Windows 防火墙端口。"
) )
command_preview = " ".join(command).replace(
f"root_passwd={MYSQL_ROOT_PASSWORD}", "root_passwd=******"
)
if not messagebox.askyesno( if not messagebox.askyesno(
f"确认安装 {tool_name}", f"确认安装 {tool_name}",
f"即将通过 winget 安装 {tool_name}。\n\n" f"即将通过 winget 安装 {tool_name}。\n\n"
f"命令: {' '.join(command)}" f"命令: {command_preview}"
f"{mysql_note}\n\n" f"{mysql_note}\n\n"
"安装可能需要管理员权限,并可能修改 PATH。是否继续?", "安装可能需要管理员权限,并可能修改 PATH。是否继续?",
): ):
return return
self._append_log(f"开始安装 {tool_name}...") 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( threading.Thread(
target=lambda: self.ui_queue.put(("install_done", (tool_name, run_install_command(command, self._thread_log)))), target=lambda: self.ui_queue.put(("install_done", (tool_name, run_install_command(command, self._thread_log)))),
daemon=True, daemon=True,
).start() ).start()
def _install_mysql_worker(self, command: list[str]) -> None:
try:
executable = install_mysql(command, self._thread_log)
except Exception as exc:
self.ui_queue.put(("mysql_install_done", (None, str(exc))))
return
self.ui_queue.put(("mysql_install_done", (executable, "")))
def install_maven_async(self) -> None: def install_maven_async(self) -> None:
if not messagebox.askyesno( if not messagebox.askyesno(
"确认安装 Maven", "确认安装 Maven",
@@ -621,6 +637,18 @@ class DeployWorkbench(tk.Tk):
self._append_log(f"Tomcat 路径已保存: {executable}") self._append_log(f"Tomcat 路径已保存: {executable}")
self.check_environment_async() self.check_environment_async()
self.after(1800, lambda: self._prompt_add_tool_after_install("Tomcat")) self.after(1800, lambda: self._prompt_add_tool_after_install("Tomcat"))
elif event == "mysql_install_done":
executable, error = payload # type: ignore[misc]
if error:
self._append_log(f"MySQL 安装或配置失败: {error}")
messagebox.showerror("MySQL 安装或配置失败", str(error))
continue
self.tool_path_vars["MySQL"].set(str(executable))
self.save_tool_path_settings(silent=True)
self.mysql_password.set(MYSQL_ROOT_PASSWORD)
self._append_log(f"MySQL 路径已保存: {executable}")
self.check_environment_async()
self.after(1800, lambda: self._prompt_add_tool_after_install("MySQL"))
self.after(120, self._drain_queue) self.after(120, self._drain_queue)
def _prompt_add_tool_after_install(self, tool_name: str) -> None: def _prompt_add_tool_after_install(self, tool_name: str) -> None:

View File

@@ -6,6 +6,7 @@ import os
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
import time
import urllib.request import urllib.request
import zipfile import zipfile
from dataclasses import dataclass from dataclasses import dataclass
@@ -36,6 +37,7 @@ TOMCAT_VERSION = "9.0.122"
TOMCAT_ARCHIVE_NAME = f"apache-tomcat-{TOMCAT_VERSION}-windows-x64.zip" 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" TOMCAT_DOWNLOAD_BASE = f"https://dlcdn.apache.org/tomcat/tomcat-9/v{TOMCAT_VERSION}/bin"
MYSQL_VERSION = "8.0.43" MYSQL_VERSION = "8.0.43"
MYSQL_ROOT_PASSWORD = "123456"
ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%") PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%")
@@ -86,6 +88,12 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st
] ]
if tool_name == "MySQL": if tool_name == "MySQL":
command.extend(["--version", MYSQL_VERSION]) 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([ command.extend([
"--accept-source-agreements", "--accept-source-agreements",
"--accept-package-agreements", "--accept-package-agreements",
@@ -94,6 +102,136 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st
return command return command
def find_mysql_executable() -> Path | None:
discovered = shutil.which("mysql")
if discovered:
return Path(discovered)
roots = [
Path(os.environ.get("ProgramFiles", r"C:\Program Files")),
Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")),
]
for root in roots:
for relative in (
Path("MySQL") / "MySQL Server 8.0" / "bin" / "mysql.exe",
Path("MySQL") / "MySQL Server 8.4" / "bin" / "mysql.exe",
):
candidate = root / relative
if candidate.exists():
return candidate
return None
def wait_for_mysql_executable(timeout: float = 90.0, poll_interval: float = 1.0) -> Path:
deadline = time.monotonic() + timeout
while True:
executable = find_mysql_executable()
if executable is not None:
return executable
if time.monotonic() >= deadline:
raise RuntimeError("MySQL 安装命令已结束,但未找到 mysql.exe。")
time.sleep(poll_interval)
def configure_mysql_weak_password_policy(
mysql_executable: Path,
on_output: Callable[[str], None],
password: str = MYSQL_ROOT_PASSWORD,
attempts: int = 30,
retry_delay: float = 2.0,
) -> None:
on_output("正在连接 MySQL,并永久启用 6 位弱密码策略...")
variables_result: subprocess.CompletedProcess[str] | None = None
for attempt in range(max(attempts, 1)):
variables_result = _run_mysql_sql(
mysql_executable,
"SHOW VARIABLES LIKE 'validate_password%';",
password,
)
if variables_result.returncode == 0:
break
if attempt + 1 < max(attempts, 1):
time.sleep(retry_delay)
assert variables_result is not None
if variables_result.returncode != 0:
detail = _process_error(variables_result)
raise RuntimeError(f"无法使用 root 账号连接 MySQL,不能写入弱密码策略。{detail}")
variable_names = variables_result.stdout.lower()
statements: list[str] = []
if "validate_password.policy" in variable_names:
statements.extend(
[
"SET PERSIST validate_password.policy = 'LOW'",
"SET PERSIST validate_password.length = 6",
"SET PERSIST validate_password.mixed_case_count = 0",
"SET PERSIST validate_password.number_count = 0",
"SET PERSIST validate_password.special_char_count = 0",
]
)
elif "validate_password_policy" in variable_names:
statements.extend(
[
"SET PERSIST validate_password_policy = 'LOW'",
"SET PERSIST validate_password_length = 6",
"SET PERSIST validate_password_mixed_case_count = 0",
"SET PERSIST validate_password_number_count = 0",
"SET PERSIST validate_password_special_char_count = 0",
]
)
else:
on_output("MySQL 未启用 validate_password 组件,当前已允许 6 位弱密码。")
escaped_password = password.replace("'", "''")
statements.append(f"ALTER USER 'root'@'localhost' IDENTIFIED BY '{escaped_password}'")
configure_result = _run_mysql_sql(mysql_executable, ";\n".join(statements) + ";\n", password)
if configure_result.returncode != 0:
detail = _process_error(configure_result)
raise RuntimeError(f"MySQL 弱密码策略配置失败。{detail}")
verify_result = _run_mysql_sql(mysql_executable, "SELECT 1;", password)
if verify_result.returncode != 0:
detail = _process_error(verify_result)
raise RuntimeError(f"MySQL 已配置,但 root 登录验证失败。{detail}")
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:
raise RuntimeError(f"MySQL 安装命令失败,退出码: {exit_code}")
executable = wait_for_mysql_executable()
configure_mysql_weak_password_policy(executable, on_output)
return executable
def _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]:
environment = os.environ.copy()
environment["MYSQL_PWD"] = password
return subprocess.run(
[
str(mysql_executable),
"--protocol=TCP",
"--host=127.0.0.1",
"--user=root",
"--batch",
"--skip-column-names",
],
input=sql,
capture_output=True,
text=True,
timeout=15,
shell=False,
env=environment,
)
def _process_error(completed: subprocess.CompletedProcess[str]) -> str:
detail = (completed.stderr or completed.stdout or "").strip()
return f" 错误: {detail}" if detail else ""
def default_maven_install_root() -> Path: def default_maven_install_root() -> Path:
local_app_data = os.environ.get("LOCALAPPDATA", "").strip() local_app_data = os.environ.get("LOCALAPPDATA", "").strip()
base = Path(local_app_data) if local_app_data else Path.home() / ".autodeploy" base = Path(local_app_data) if local_app_data else Path.home() / ".autodeploy"

View File

@@ -4,10 +4,14 @@ import tempfile
import unittest import unittest
import zipfile import zipfile
from pathlib import Path from pathlib import Path
from subprocess import CompletedProcess
from unittest.mock import patch
from deploy_tool.installer import ( from deploy_tool.installer import (
MAVEN_ARCHIVE_NAME, MAVEN_ARCHIVE_NAME,
MYSQL_VERSION, MYSQL_VERSION,
MYSQL_ROOT_PASSWORD,
configure_mysql_weak_password_policy,
TOMCAT_VERSION, TOMCAT_VERSION,
install_maven, install_maven,
install_tomcat, install_tomcat,
@@ -106,10 +110,48 @@ class InstallerTests(unittest.TestCase):
self.assertEqual(command[0:5], ["winget", "install", "--exact", "--id", "Oracle.MySQL"]) self.assertEqual(command[0:5], ["winget", "install", "--exact", "--id", "Oracle.MySQL"])
self.assertEqual(command[command.index("--version") + 1], MYSQL_VERSION) self.assertEqual(command[command.index("--version") + 1], MYSQL_VERSION)
self.assertEqual(MYSQL_VERSION, "8.0.43") 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-source-agreements", command)
self.assertIn("--accept-package-agreements", command) self.assertIn("--accept-package-agreements", command)
self.assertIn("--disable-interactivity", command) self.assertIn("--disable-interactivity", command)
def test_persists_six_character_mysql_password_policy(self):
query_result = CompletedProcess(
[],
0,
stdout="validate_password.length\t8\nvalidate_password.policy\tMEDIUM\n",
stderr="",
)
success = CompletedProcess([], 0, stdout="1\n", stderr="")
with patch("deploy_tool.installer.subprocess.run", side_effect=[query_result, success, success]) as run:
messages = []
configure_mysql_weak_password_policy(Path("mysql.exe"), messages.append, attempts=1)
configure_call = run.call_args_list[1]
sql = configure_call.kwargs["input"]
self.assertIn("SET PERSIST validate_password.policy = 'LOW'", sql)
self.assertIn("SET PERSIST validate_password.length = 6", sql)
self.assertIn("ALTER USER 'root'@'localhost' IDENTIFIED BY '123456'", sql)
self.assertEqual(configure_call.kwargs["env"]["MYSQL_PWD"], MYSQL_ROOT_PASSWORD)
self.assertNotIn(MYSQL_ROOT_PASSWORD, configure_call.args[0])
self.assertTrue(any("永久允许 6 位弱密码" in message for message in messages))
def test_mysql_without_validation_component_still_sets_and_verifies_password(self):
no_component = CompletedProcess([], 0, stdout="", stderr="")
success = CompletedProcess([], 0, stdout="1\n", stderr="")
with patch("deploy_tool.installer.subprocess.run", side_effect=[no_component, success, success]) as run:
messages = []
configure_mysql_weak_password_policy(Path("mysql.exe"), messages.append, attempts=1)
sql = run.call_args_list[1].kwargs["input"]
self.assertNotIn("SET PERSIST", sql)
self.assertIn("ALTER USER", sql)
self.assertTrue(any("未启用 validate_password" in message for message in messages))
def test_maven_is_not_offered_as_an_invalid_winget_package(self): def test_maven_is_not_offered_as_an_invalid_winget_package(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
build_install_command("Maven") build_install_command("Maven")