>  기사  >  데이터 베이스  >  파이썬. MySQL 데이터베이스 생성 백업을 자동화합니다.

파이썬. MySQL 데이터베이스 생성 백업을 자동화합니다.

王林
王林원래의
2024-07-18 21:53:21968검색

Python. Automating creation backups of MySQL database.

이 스크립트는 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()

check_and_create_database:
이 함수는 MySQL 서버에 데이터베이스가 존재하는지 확인합니다. 데이터베이스가 존재하지 않으면 데이터베이스를 생성합니다. 확인하거나 생성하려면 호스트, 포트, 사용자 이름, 비밀번호, 데이터베이스 이름과 같은 매개변수가 필요합니다.

check_and_create_user:
데이터베이스 기능과 마찬가지로 이 기능은 MySQL 서버에 사용자가 존재하는지 확인합니다. 사용자가 존재하지 않는 경우 사용자를 생성하고 특정 데이터베이스에 권한을 부여합니다. 또한 호스트, 포트, 사용자 이름, 비밀번호, 데이터베이스 이름, 새 사용자 이름, 새 비밀번호와 같은 매개변수도 사용합니다.

backup_mysql_database:
mysqldump를 사용하여 MySQL 데이터베이스를 백업하는 기능입니다. 호스트, 포트, 사용자 이름, 비밀번호, 데이터베이스 이름, 백업 파일 저장 경로와 같은 매개변수를 사용합니다.

restore_mysql_database:
이 기능은 백업 파일에서 MySQL 데이터베이스를 복원합니다. 호스트, 포트, 사용자 이름, 비밀번호, 데이터베이스 이름, 백업 파일 경로와 같은 매개변수를 사용합니다.

메인:
이것이 스크립트의 주요 기능입니다. 연결 세부 정보, 데이터베이스 이름 및 백업 경로를 포함하여 소스 및 대상 MySQL 데이터베이스에 대한 매개변수를 설정합니다. 그런 다음 소스 데이터베이스와 대상 데이터베이스가 다른지 확인하고, 존재하지 않는 경우 대상 데이터베이스와 사용자를 생성하고, 소스 데이터베이스의 백업을 생성한 후 마지막으로 백업을 대상 데이터베이스에 복원합니다.

또한 스크립트는 subprocess 모듈을 사용하여 MySQL 작업(mysql, mysqldump)에 대한 셸 명령을 실행하고 오류 처리 및 출력 리디렉션(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

위 내용은 파이썬. MySQL 데이터베이스 생성 백업을 자동화합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.