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

@@ -6,6 +6,7 @@ import os
import shutil
import subprocess
import tempfile
import time
import urllib.request
import zipfile
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_DOWNLOAD_BASE = f"https://dlcdn.apache.org/tomcat/tomcat-9/v{TOMCAT_VERSION}/bin"
MYSQL_VERSION = "8.0.43"
MYSQL_ROOT_PASSWORD = "123456"
ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
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":
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",
@@ -94,6 +102,136 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st
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:
local_app_data = os.environ.get("LOCALAPPDATA", "").strip()
base = Path(local_app_data) if local_app_data else Path.home() / ".autodeploy"