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()