Python を使用して MySQL データベースを構成する: 自動ユーザー認証ツール

ここに画像の説明を挿入

まず、mysql-connector-python ライブラリがインストールされていることを確認します。インストールされていない場合は、次のコマンドを使用してインストールできます。

pip install mysql-connector-python

それでは、Pythonスクリプトの内容を記載します。

import mysql.connector
from mysql.connector import Error

def create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name):
    # 创建数据库连接
    connection = mysql.connector.connect(host=host_name, 
                                         user=user_name, 
                                         passwd=user_password)
    cursor = connection.cursor()
    try:
        # 创建新用户
        cursor.execute(f"CREATE USER '{
      
      new_user_name}'@'localhost' IDENTIFIED BY '{
      
      new_user_password}';")
        
        # 授予新用户对指定数据库的所有权限
        cursor.execute(f"GRANT ALL PRIVILEGES ON {
      
      db_name} . * TO '{
      
      new_user_name}'@'localhost';")
        
        # 提交修改
        connection.commit()
        
        print(f"User {
      
      new_user_name} created successfully.")
    except Error as e:
        print(f"Error: '{
      
      e}'")
    finally:
        # 关闭数据库连接
        cursor.close()
        connection.close()

# 使用你的MySQL服务器详细信息替换下面的值
host_name = "localhost"
user_name = "root"
user_password = "rootpassword"

# 创建的新用户的用户名和密码
new_user_name = "newuser"
new_user_password = "newpassword"

# 要授予权限的数据库
db_name = "mydatabase"

create_user(host_name, user_name, user_password, new_user_name, new_user_password, db_name)

このスクリプトを実行すると、MySQL サーバーに接続し、新しいユーザーを作成し、そのユーザーに指定されたデータベースに対するすべての権限を付与します。

注: ユーザーを作成して権限を付与するのに十分な権限があることを確認してください。また、データベースのセキュリティに関係するため、このスクリプトを使用する場合は十分に注意してください。

おすすめ

転載: blog.csdn.net/tuzajun/article/details/130980193