mysql增量备份脚本(python3)

#!/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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值