此腳本可自動建立 MySQL 資料庫的備份、還原它們以及管理目標 MySQL 伺服器上的資料庫和使用者建立。
import subprocess import datetime import sys import os def check_and_create_database(host, port, username, password, database): # Command to check if the database exists check_database_command = f"mysql -sN --host={host} --port={port} --user={username} --password={password} -e \"SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{database}')\" 2>/dev/null" # Execute the command output = subprocess.check_output(check_database_command, shell=True) # If the output contains b'1', the database exists if b'1' in output: subprocess.run(check_database_command, shell=True, check=True) print(f"Database '{database}' already exists.") sys.exit(1) else: # If the command fails, the database does not exist print(f"Database '{database}' does not exist. Creating...") # Command to create the database create_database_command = f"mysql --host={host} --port={port} --user={username} --password={password} -e 'CREATE DATABASE {database}' 2>/dev/null" subprocess.run(create_database_command, shell=True) def check_and_create_user(host, port, username, password, database, new_username, new_password): # Command to check if the user exists check_user_command = f"mysql -sN --host={host} --port={port} --user={username} --password={password} -e \"SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '{new_username}')\" 2>/dev/null" # Execute the command output = subprocess.check_output(check_user_command, shell=True) # If the output contains b'1', the user exists if b'1' in output: print(f"User '{new_username}' already exists.") sys.exit(1) else: # The user does not exist, create it print(f"User '{new_username}' does not exist. Creating...") # Command to create the user and grant privileges create_user_command = f"mysql --host={host} --port={port} --user={username} --password={password} -e \"CREATE USER '{new_username}'@'%' IDENTIFIED BY '{new_password}'; GRANT ALL PRIVILEGES ON {database}.* TO '{new_username}'@'%'; FLUSH PRIVILEGES;\" 2>/dev/null" subprocess.run(create_user_command, shell=True) def backup_mysql_database(host, port, username, password, database, backup_path): # Check if the backup directory exists if not os.path.exists(backup_path): print(f"Error: Backup directory '{backup_path}' does not exist.") sys.exit(1) # Create a filename for the backup with the current date and time timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") backup_file = f"{backup_path}/{database}_{timestamp}.sql" # Command to create a database backup using mysqldump dump_command = f"mysqldump --no-tablespaces --host={host} --port={port} --user={username} --password={password} {database} > {backup_file} 2>/dev/null" # Execute the mysqldump command subprocess.run(dump_command, shell=True) return backup_file def restore_mysql_database(host, port, username, password, database, backup_file): # Command to restore a database from a backup using mysql restore_command = f"mysql --host={host} --port={port} --user={username} --password={password} {database} < {backup_file} 2>/dev/null" # Execute the mysql command subprocess.run(restore_command, shell=True) def main(): # Connection parameters to the source MySQL database source_host = "127.0.0.1" source_port = "3309" source_username = "my_user" source_password = "my_password" source_database = "my_database" # Connection parameters to the target MySQL database target_host = "127.0.0.1" target_port = "3309" new_username = "new_username" new_password = "new_password" target_database = "my_database_two" target_username = "root" target_password = "root_password" # Path to save the backup locally backup_path = "my_dbs_dumps" # Check if source_database is different from target_database if source_database == target_database: print("Error: Source database should be different from target database.") sys.exit(1) # Check and create the target database if it does not exist check_and_create_database(target_host, target_port, target_username, target_password, target_database) # Check and create the target user if it does not exist check_and_create_user(target_host, target_port, target_username, target_password, target_database, new_username, new_password) # Create a backup of the MySQL database backup_file = backup_mysql_database(source_host, source_port, source_username, source_password, source_database, backup_path) print(f"Database backup created: {backup_file}") # Restore the database on the target server from the backup restore_mysql_database(target_host, target_port, target_username, target_password, target_database, backup_file) print("Database backup restored on the target server.") if __name__ == "__main__": main()
檢查並建立_資料庫:
此函數檢查 MySQL 伺服器上是否存在資料庫。如果資料庫不存在,則會建立它。它需要主機、連接埠、使用者名稱、密碼和資料庫名稱等參數來檢查或建立。
檢查並建立_使用者:
與資料庫函數一樣,函數會檢查 MySQL 伺服器上是否存在使用者。如果使用者不存在,它將建立使用者並授予特定資料庫的權限。它還接受主機、連接埠、使用者名稱、密碼、資料庫名稱、新使用者名稱和新密碼等參數。
備份_mysql_資料庫:
此函數使用 mysqldump 執行 MySQL 資料庫的備份。它接受主機、連接埠、使用者名稱、密碼、資料庫名稱和保存備份檔案的路徑等參數。
restore_mysql_database:
此函數從備份檔案還原 MySQL 資料庫。它接受主機、連接埠、使用者名稱、密碼、資料庫名稱和備份檔案路徑等參數。
主要:
這是該腳本的主要功能。它為來源和目標 MySQL 資料庫設定參數,包括連接詳細資訊、資料庫名稱和備份路徑。然後,它執行檢查以確保來源資料庫和目標資料庫不同,如果目標資料庫和用戶不存在,則建立目標資料庫和用戶,建立來源資料庫的備份,最後將備份還原到目標資料庫。
此外,此腳本使用 subprocess 模組執行 MySQL 操作(mysql、mysqldump)的 shell 指令,並執行錯誤處理和輸出重定向(2>/dev/null)以抑制不必要的輸出。
如果您正在使用 MySQL 資料庫並想要建立自動化,此程式碼將為您提供協助。
此程式碼是一個很好的起始模板,用於建立管理 MySQL 資料庫的自動化腳本。
dmi@dmi-laptop:~/my_python$ python3 mysql_backup_restore.py Database 'my_database_two' does not exist. Creating... User 'new_username' does not exist. Creating... Database backup created: my_dbs_dumps/my_database_2024-05-13_20-05-24.sql Database backup restored on the target server. dmi@dmi-laptop:~/my_python$
ask_dima@yahoo.com
以上是Python。自動建立 MySQL 資料庫的備份。的詳細內容。更多資訊請關注PHP中文網其他相關文章!