#!/usr/bin/python3 import time import mysql.connector import os import zipfile binlog_path = '/var/lib/mysql' backup_path = '/root' time_YMD = time.strftime("/%Y/%m/%d", time.localtime()) time_MHS = time.strftime("_%H-%M-%S", time.localtime()) def mysql_conn(): mydb = mysql.connector.connect( host="127.0.0.1", user="root", passwd="cbst789", port="3360" ) return mydb def binlog_zip(inpath,outpath): db_file = zipfile.ZipFile(outpath,'w',zipfile.ZIP_DEFLATED) db_file.write(inpath) db_file.close() def get_binlog(sql): mydb = mysql_conn() mycursor = mydb.cursor() mycursor.execute(sql) for i in mycursor: binlog = i mycursor.close() return binlog def flush_binlog(sql): mydb = mysql_conn() mycursor = mydb.cursor() mycursor.execute(sql) mycursor.close() def start_backup(): binlog_file = get_binlog('show master status') in_name = binlog_path + '/' + binlog_file[0] out_name = backup_path + time_YMD + '/binlog' + time_MHS + '.zip' if not os.path.isdir(backup_path + time_YMD): os.makedirs(backup_path + time_YMD) binlog_zip(in_name,out_name) if os.path.isfile(out_name): flush_binlog('flush logs') new_binlog = get_binlog('show master status') print ('备份成功,路径为 {0} 最新binlog日志为 {1}'.format(out_name,new_binlog[0])) #os.remove(in_name) #删除原binlog文件 else: print ('备份失败') start_backup()