蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线服务命令矩阵、SQLite RBAC 用户权限生命周期、my.cnf 8.x 审计与元数据目录查询

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-administration.py
explore-administration.py245 行
"""MySQL 管理离线实验:校验跨平台服务启停命令、在内存 SQLite 中模拟用户与权限 RBAC 生命周期、解析 my.cnf 配置并校验元信息命令等价查询。"""
import configparser
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    cases = []

    # Case 1: Cross-platform MySQL service lifecycle commands (Windows / Linux / macOS)
    service_cmds = {
        "windows": {"start": "net start mysql", "stop": "net stop mysql"},
        "linux_systemd": {
            "start": "sudo systemctl start mysql",
            "stop": "sudo systemctl stop mysql",
            "restart": "sudo systemctl restart mysql",
            "status": "sudo systemctl status mysql",
        },
        "linux_sysv": {
            "start": "sudo service mysql start",
            "stop": "sudo service mysql stop",
            "restart": "sudo service mysql restart",
            "status": "sudo service mysql status",
        },
        "macos": {
            "start": "sudo /usr/local/mysql/support-files/mysql.server start",
            "stop": "sudo /usr/local/mysql/support-files/mysql.server stop",
            "restart": "sudo /usr/local/mysql/support-files/mysql.server restart",
            "status": "sudo /usr/local/mysql/support-files/mysql.server status",
        },
    }
    exp1 = {
        "platforms": ["linux_systemd", "linux_sysv", "macos", "windows"],
        "linux_systemd_action_count": 4,
        "macos_script_path": "/usr/local/mysql/support-files/mysql.server",
    }
    act1 = {
        "platforms": sorted(service_cmds.keys()),
        "linux_systemd_action_count": len(service_cmds["linux_systemd"]),
        "macos_script_path": service_cmds["macos"]["start"].split()[1],
    }
    cases.append(
        {
            "name": "service_start_stop_commands_matrix",
            "summary": "核对 Windows、Linux(systemd/service) 与 macOS 下 MySQL 服务启停、重启与状态查询命令",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: User & privilege lifecycle modeled in isolated SQLite tables (CREATE/GRANT/SHOW/REVOKE/ALTER/DROP)
    conn.executescript(
        """
        CREATE TABLE mysql_users (
            username TEXT NOT NULL,
            host TEXT NOT NULL,
            auth_hash TEXT NOT NULL,
            with_grant_option INTEGER NOT NULL DEFAULT 0,
            PRIMARY KEY (username, host)
        );
        CREATE TABLE mysql_grants (
            username TEXT NOT NULL,
            host TEXT NOT NULL,
            scope TEXT NOT NULL,
            privilege TEXT NOT NULL,
            PRIMARY KEY (username, host, scope, privilege)
        );
        """
    )
    # CREATE USER 'john'@'localhost' IDENTIFIED BY 'password123'
    conn.execute("INSERT INTO mysql_users VALUES ('john', 'localhost', 'hash_pw123', 0);")
    # GRANT ALL PRIVILEGES ON test_db.* TO 'john'@'localhost'
    conn.execute("INSERT INTO mysql_grants VALUES ('john', 'localhost', 'test_db.*', 'ALL PRIVILEGES');")
    grants_before = [
        list(r)
        for r in conn.execute(
            "SELECT scope, privilege FROM mysql_grants WHERE username='john' AND host='localhost';"
        ).fetchall()
    ]
    # ALTER USER password
    conn.execute(
        "UPDATE mysql_users SET auth_hash='hash_new456' WHERE username='john' AND host='localhost';"
    )
    new_hash = conn.execute(
        "SELECT auth_hash FROM mysql_users WHERE username='john' AND host='localhost';"
    ).fetchone()[0]
    # REVOKE ALL PRIVILEGES
    conn.execute(
        "DELETE FROM mysql_grants WHERE username='john' AND host='localhost' AND scope='test_db.*';"
    )
    grants_after = conn.execute(
        "SELECT COUNT(*) FROM mysql_grants WHERE username='john' AND host='localhost';"
    ).fetchone()[0]
    # Change host: DROP + CREATE (or RENAME USER in MySQL 8)
    conn.execute("DELETE FROM mysql_users WHERE username='john' AND host='localhost';")
    conn.execute("INSERT INTO mysql_users VALUES ('john', '%', 'hash_pw123', 1);")
    final_user = list(
        conn.execute("SELECT username, host, with_grant_option FROM mysql_users;").fetchone()
    )

    exp2 = {
        "grants_before_revoke": [["test_db.*", "ALL PRIVILEGES"]],
        "password_updated": "hash_new456",
        "grants_after_revoke": 0,
        "migrated_user": ["john", "%", 1],
    }
    act2 = {
        "grants_before_revoke": grants_before,
        "password_updated": new_hash,
        "grants_after_revoke": grants_after,
        "migrated_user": final_user,
    }
    cases.append(
        {
            "name": "user_and_privilege_lifecycle_model",
            "summary": "在内存 SQLite 中验证用户创建、授权、改密、撤权、删除及主机迁移状态流转",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: /etc/my.cnf sections & MySQL 8.x deprecated options audit
    my_cnf_text = """
[mysqld]
basedir=/usr
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
pid-file=/var/run/mysqld/mysqld.pid
port=3306
bind-address=127.0.0.1
server-id=1
default-storage-engine=InnoDB
max_connections=151
thread_cache_size=9
character-set-server=utf8mb4
collation-server=utf8mb4_0900_ai_ci
innodb_buffer_pool_size=256M
table_open_cache=4000
log_error=/var/log/mysqld.log
general_log=0
slow_query_log=1
log_queries_not_using_indexes=1
"""
    cfg = configparser.ConfigParser()
    cfg.read_string(my_cnf_text)
    deprecated_in_mysql8 = {
        "query_cache_size": "removed_in_8.0",
        "thread_concurrency": "removed_in_5.7",
        "master_host": "replaced_by_CHANGE_REPLICATION_SOURCE_TO",
        "auth_native_password": "invalid_option_use_caching_sha2_password",
    }
    exp3 = {
        "port": 3306,
        "engine": "InnoDB",
        "charset": "utf8mb4",
        "slow_query_log": 1,
        "deprecated_items_flagged": 4,
    }
    act3 = {
        "port": cfg.getint("mysqld", "port"),
        "engine": cfg.get("mysqld", "default-storage-engine"),
        "charset": cfg.get("mysqld", "character-set-server"),
        "slow_query_log": cfg.getint("mysqld", "slow_query_log"),
        "deprecated_items_flagged": len(deprecated_in_mysql8),
    }
    cases.append(
        {
            "name": "my_cnf_sections_and_mysql8_audit",
            "summary": "解析 /etc/my.cnf 六大类核心参数并标出 MySQL 8.x 中已移除或替代的旧选项",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    # Case 4: Metadata inspection commands (USE / SHOW DATABASES / SHOW TABLES / SHOW COLUMNS / SHOW INDEX / SHOW TABLE STATUS)
    conn.executescript(
        """
        CREATE TABLE demo_articles (
            article_id INTEGER PRIMARY KEY,
            article_title TEXT NOT NULL,
            article_author TEXT NOT NULL,
            submission_date TEXT
        );
        CREATE INDEX idx_author ON demo_articles(article_author);
        INSERT INTO demo_articles VALUES
            (1, 'MySQL 架构', '蓝色天空', '2026-01-01'),
            (2, '索引原理', '蓝色天空', '2026-01-02');
        """
    )
    tables = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='demo_articles';"
        ).fetchall()
    ]
    columns = [
        [r[1], r[2], r[5]]
        for r in conn.execute("PRAGMA table_info(demo_articles);").fetchall()
    ]
    indexes = [
        r[1] for r in conn.execute("PRAGMA index_list(demo_articles);").fetchall()
    ]
    row_count = conn.execute("SELECT COUNT(*) FROM demo_articles;").fetchone()[0]
    exp4 = {
        "tables": ["demo_articles"],
        "columns": [
            ["article_id", "INTEGER", 1],
            ["article_title", "TEXT", 0],
            ["article_author", "TEXT", 0],
            ["submission_date", "TEXT", 0],
        ],
        "indexes": ["idx_author"],
        "table_rows": 2,
    }
    act4 = {
        "tables": tables,
        "columns": columns,
        "indexes": indexes,
        "table_rows": row_count,
    }
    cases.append(
        {
            "name": "metadata_show_commands_sqlite_equivalent",
            "summary": "以 SQLite 目录视图与 PRAGMA 实测表清单、列结构、索引与表统计元信息查询",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mysql-administration-lab/explore-administration.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-administration.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MySQL

课程关联工程包(登记关联41章) · 含当前章节或实例 · mbskycom202612a1590.zip

下载课程关联工程包:MySQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1588.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习