mysql 备份脚本(python)

本文介绍了一个使用Python编写的MySQL备份脚本,通过mysqldump命令获取数据库并压缩为.tar.gz文件,同时处理备份失败和清理旧备份。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mysql 备份脚本(python)

import warnings
warnings.filterwarnings('ignore')
import os
import sys
import time
import tarfile
import datetime

mysql_host = "数据库服务器ip地址"
mysql_user = "备份用户"
mysql_pwd = "'密码'"
mysql_port = 端口
new_date = time.strftime("%Y:%m:%d:%H:%M:%S")
file_date = time.strftime("%Y-%m-%d-%H")
back_path = "备份目录"
back_log = "备份日志路径"
db_name = "all-databases"


def baklog (output):
    logfile = open(back_log,"a+")
    logfile.write(output)
    logfile.close()

def mysqldump ():
    backpath = os.path.exists(back_path)
    if backpath == True :
       None   
    else:
       os.makedirs(back_path)
       
    output1 = "\nStart Backup,start time:%s" % new_date
    baklog(output1)
    back_file = back_path+"/"+db_name+"_"+file_date+".sql"
    back_file1 = db_name+"_"+file_date+".sql"
    os.system("mysqldump -u%s -p%s -P%s --all-databases > %s" % (mysql_user,mysql_pwd,mysql_port,back_file))
    judge = os.path.exists(back_file)
    if judge == True :
       size = os.path.getsize(back_file)
       if size == 0 :
          end_date11 = time.strftime("%Y:%m:%d:%H:%M:%S")
          output11 = "\nBackup failed,Script Exit,Failure time: %s" % end_date11
          baklog(output11)
          sys.exit()
       else:
          output12 = "\nBackup succeeded! Backup file size: %s" % size
          baklog(output12)
    else:
       end_date12 = time.strftime("%Y:%m:%d:%H:%M:%S")
       output13 = "\nBackup failed,Script Exit,Failure time: %s" % end_date11
       baklog(output13)
       sys.exit()
    tar_file(back_file1)
    os.system("find %s -mtime +7 -name .tar.gz -exec rm -rf {} \;" % back_path)
    output14 = "\nThe file was deleted seven days ago"
    baklog(output14)
    end_date = time.strftime("%Y:%m:%d:%H:%M:%S")
    output2 = "\nEnd of backup,end time:%s" % end_date
    baklog(output2)

def tar_file (file_name):
    os.chdir(back_path)
    tar_name = db_name+"_"+file_date+".sql"+".tar"+".gz"
    tar = tarfile.open(tar_name,"w:gz")
    tar.add(file_name)
    tar.close()
    output4 = "\nThe backup file is compressed file name: %s" % tar_name
    baklog(output4)
    os.remove(file_name)
    output5 = "\nBackup source file deleted : %s" % file_name
    baklog(output5)

mysqldump()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值