1. 程式人生 > 實用技巧 >MySQL按天備份二進位制日誌

MySQL按天備份二進位制日誌

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:guozhen.zhang

import MySQLdb
import time
import os

# 建立備份binlog目錄
project_path = '/data/binlog_back' # 定義備份日誌的目錄
binlog_file = "/data/binlog_back/binlog_file" # 定義獲取日誌的存放檔案
last_binlog_file = "/data/binlog_back/last_binlog_file" # 獲取binlog日誌的最後一個日誌檔案
dir_time = time.strftime('%Y%m%d-%H%M', time.localtime(time.time())) # 返回當前時間的年月日作為目錄名稱
isExists = os.path.exists(project_path + '/' + dir_time) # 判斷該目錄是否存在
if not isExists:
os.makedirs(project_path + '/' + dir_time)
print(project_path + '/' + dir_time + "目錄建立成功")

# 定義執行備份指令碼
def back_binlog():
# 建立MySQL連線
conn = MySQLdb.connect(host='192.168.1.20', port=3306, user='root', passwd='123a456b')

# 重新整理master的二進位制日誌
cursor = conn.cursor()
cursor.execute("flush logs;")

# 獲取binlog的存放路徑
cursor1 = conn.cursor()
cursor1.execute("show variables like 'log_bin_basename'")
row1 = cursor1.fetchone()[1]

# 獲取masterbinlog日誌的最後一個日誌檔案
cmd = 'find %s* -mtime 0 -exec ls {} \;|grep -v index|tail -1 > %s' % (row1, last_binlog_file)

os.popen(cmd).read()

# 獲取master前一天的二進位制日誌

cmd = 'find %s* -mtime 0 -exec ls {} \;|grep -v `cat %s` |grep -v index> %s' % (
row1, last_binlog_file, binlog_file)

os.popen(cmd)

f = open(binlog_file, mode="r")
lines = f.readlines()
for line in lines:
fname = line.strip()
cmd = 'cp ' + fname + ' ' + (project_path + '/' + dir_time)
os.system(cmd)
f.close()

# 關閉資料庫連線
conn.close()


# 備份二進位制檔案存在就執行備份,否則退出
if os.path.exists(binlog_file):
back_binlog()
print("backup success!")
else:
print("binlog file not found")
exit()