python-备份mysql数据库

python-备份mysql数据库

1. python-备份mysql数据库

  • 源码安装python3环境

    • 下载版本:https://www.python.org/downloads/source/
      image

      wget https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tgz
      yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
      tar zxvf Python-3.8.6.tgz
      cd Python-3.8.6
      ./configure
      make && make install
      
    • liunx下执行命令尝试
      image

  • 使用pip3安装连接mysql工具

    pip3 install pymysql
    
  • 创建mysql备份文件

    cd /root/
    touch backup_db.py
    
  • 编写backup_db.py备份mysql数据库文件

    #!/usr/bin/env python
    # coding: utf-8
    
    import os
    import pymysql
    import time
    
    ''' 定义变量 '''
    databases = ["test-cmdb","vuecli_shop"]  # 定义要备份的数据库名
    sql_host = '127.0.0.1'
    sql_user = 'root'  # 数据库登陆用户
    sql_pwd = '123456'  # 数据库登陆密码
    root_dir = '/tmp/baksql/'  # 存放sql文件的地址
    
    
    ''' 创建存放备份文件的文件夹 '''
    if not os.path.exists(root_dir):  # 判断如果没有目录
        os.mkdir(root_dir)  # 创建
    print('创建文件夹成功:', os.path.abspath(root_dir))  # 打印创建成功
    
    
    ''' 开始备份到指定文件夹 '''
    os.chdir(root_dir)  # 改变当前工作目录到指定的路径
    for database_name in databases:  # 循环数据库
        today_sql = time.strftime('%Y%m%d')+'_'+database_name+'.sql'   # 定义数据库文件名变量
        # 编写cmd语句 
        sql_comm="mysqldump -u%s -p%s %s > %s"%(sql_user,sql_pwd,database_name,today_sql) # 定义备份数据库变量 
        if os.system(sql_comm) == 0: # 如果上一条执行结果等于0,表示成功 
            print(database_name, 'is backup successfully!') # 打印成功信息 
            print('备份文件地址:',os.path.abspath('./')+today_sql)
        else: # 备份失败 
            print(database_name, 'is backup fai!') # 打印成功信息
    
  • 执行结果

    (python_3.8_base) [admin@shichaodeMacBook-Pro 01-python-基础]# python backup_db.py
    创建文件夹成功: /tmp/backup_sql
    mysqldump: [Warning] Using a password on the command line interface can be insecure.
    test-cmdb is backup successfully!
    备份文件地址: /private/tmp/backup_sql20220623_test-cmdb.sql
    mysqldump: [Warning] Using a password on the command line interface can be insecure.
    vuecli_shop is backup successfully!
    备份文件地址: /private/tmp/backup_sql20220623_vuecli_shop.sql
    
posted @ 2023-01-13 10:36  七月流星雨  阅读(606)  评论(0编辑  收藏  举报