1. 程式人生 > >python mysql備份指令碼

python mysql備份指令碼

#!/usr/bin/env python
# encoding: utf-8

#@author: 東哥加油
#@file: pyinnobackup.py
#@time: 2018/12/11 11:34

import datetime
import os
import pymysql
import subprocess
import re
import sys


#從庫備份
innobackupex = '/usr/bin/innobackupex'
mysql_user = 'root'
mysql_password = 'mysqlpassword'
defaults_file='/usr/local/mysql/mysql3316.cnf'
mysql_host = '127.0.0.1'
mysql_port = 3316
fullback_dir = '/data/bktest/full'
increback_dir = '/data/bktest/incre'
log_text = '/data/bktest/backup.'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'.txt'
logger = open(log_text, 'a+')


#環境檢查:
def check_env():
print('日誌檔案:',log_text)
chk_1 = not os.path.exists(innobackupex)
chk_2 = not os.path.exists(fullback_dir)
chk_3 = not os.path.exists(increback_dir)
if chk_1:
logger.write(get_now_time()+':'+innobackupex+'檔案不存在'+'\n')

if chk_2:
logger.write(get_now_time()+':'+fullback_dir+'全量備份目錄不存在'+'\n')

if chk_3:
logger.write(get_now_time()+':'+increback_dir+'增量備份目錄不存在'+'\n')

conn = None
chk_4 = False
try:
conn = pymysql.connect(
host=mysql_host,
port=mysql_port,
user=mysql_user,
passwd=mysql_password,
charset="utf8",
)
except Exception as err:
logger.write(get_now_time()+':'+str(err)+'\n')
chk_4 = True

if(chk_1 or chk_2 or chk_3 or chk_4):
#檢查命令,目錄是否存在,檢查Mysql是否可以連線,如果否終止備份程式
print(get_now_time()+':'+'請配置相關環境')
logger.write(get_now_time()+':'+'請配置相關環境'+'\n')
exit()

def get_now_time():
str_now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return str_now_time;


#執行全量備份
def fullbackup():
full_backup = innobackupex+''' --no-lock --safe-slave-backup --parallel=4 --safe-slave-backup --slave-info --defaults-file=%s --user=%s --password='%s' %s >> %s 2>&1 '''%(defaults_file,mysql_user,mysql_password,fullback_dir,log_text)
logger.write('全量備份使用命令:'+full_backup+'\n')
logger.write('################################全量備份開始################################\n')
logger.write('全量備份開始時間:' + get_now_time() + '\n')
logger.flush()
subprocess.call(full_backup,shell=True)
logger.write("################################全量備份結束################################\n")
logger.write('全量備份結束時間:' + get_now_time()+'\n')
logger.close()

#檢查備份是否生效
def check_bakcup_success():
file = open(log_text, 'r', encoding='UTF-8')
succ = False
for (num, line) in enumerate(file):
if (re.search(r'innobackupex: completed OK!', line)):
succ = True
file.close()
if succ:
print('備份成功')
else:
print('備份失敗')
return succ


#執行增量備份,需要檢查最近的全量備份
def incre_backup():
fullback_dir='/data/bktest/full'
sonfiles = os.listdir(fullback_dir)
date_strs = []
for i in sonfiles:
child = os.path.join(fullback_dir, i)
if os.path.isdir(child ):
if(re.search(r'[2][0][1-9][0-9]\-[0-1][0-9]\-[0-3][0-9]\_[0-2][0-9]\-[0-5][0-9]\-[0-5][0-9]', str(child))):
date_strs.append(i)

if len(date_strs) == 0:
print('沒有全量備份')
exit()
date_str = max(date_strs)
incremental_basedir = os.path.join(fullback_dir,date_str)
increback_dir_1 = os.path.join(increback_dir,date_str)
if not os.path.exists(increback_dir_1):
os.makedirs(increback_dir_1)
full_backup = innobackupex+''' --no-lock --safe-slave-backup --parallel=4 --safe-slave-backup --slave-info '''\
'''--defaults-file=%s --user=%s --password='%s' --incremental-basedir=%s --incremental %s >> %s 2>&1 '''%(defaults_file,mysql_user,mysql_password,incremental_basedir,increback_dir_1,log_text)
logger.write('增量備份使用命令:'+full_backup+'\n')
logger.write('################################增量備份開始################################\n')
logger.write('增量備份開始時間:' + get_now_time() + '\n')
logger.flush()
subprocess.call(full_backup,shell=True)
logger.write("################################增量備份結束################################\n")
logger.write('增量備份結束時間:' + get_now_time()+'\n')
logger.close()


def del_expire_bk():
print('刪除過期備份')



if __name__ == '__main__':
if len(sys.argv) == 1:
print('請輸入引數 full or incr')
exit()

if sys.argv[1] == 'full':
check_env()
fullbackup()
check_bakcup_success()
del_expire_bk()
elif sys.argv[1] == 'incr':
incre_backup()
check_bakcup_success()
del_expire_bk()
else:
print('請輸入引數 full or incr')