#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
import sys
import commands
import getopt
innobackupex = ‘/usr/local/percona-xtrabackup-2.3.3-Linux-x86_64/bin/innobackupex‘
# 全备函数
def full_backup(host, port, user, password, full_backup_dir):
os.system(innobackupex + ‘ --host=‘ + host + ‘ --port=‘ + port + ‘ --user=‘ +
user + ‘ --password=‘ + password + ‘ ‘ + full_backup_dir + ‘ --no-timestamp >/tmp/backup.log 2>&1‘)
# 增备函数
def incr_backup(host, port, user, password, incr_backup_dir,base_backup_dir):
os.system(innobackupex + ‘ --incremental ‘ + incr_backup_dir + ‘ --incremental-basedir=‘ +
base_backup_dir + ‘ --host=‘ + host + ‘ --port=‘ + port + ‘ --user=‘ + user + ‘ --password=‘ + password + ‘ >/tmp/backup.log 2>&1‘)
# 主函数
if __name__ == ‘__main__‘:
config = {
"host":"",
"port":"",
"user":"",
"password":"",
}
opts,args = getopt.getopt(sys.argv[1:],‘a:P:u:p:‘,
[
‘host=‘,
‘port=‘,
‘user=‘,
‘password=‘
])
for option, value in opts:
if option in ["-a","--host"]:
config["host"]=value
elif option in [‘--port‘, ‘-P‘]:
config["port"] = value
elif option in [‘--user‘, ‘-u‘]:
config["user"] = value
elif option in [‘--password‘, ‘-p‘]:
config["password"] = value
backup_dir=‘/data/backup/‘
wday = time.localtime().tm_wday
week_of_dir = backup_dir + time.strftime("%U", time.localtime()) + "/" + config[‘port‘]
full_backup_dir = week_of_dir + ‘/full‘
# 增备寻找最新的上一次备份的基准目录
base_backup_dir = commands.getoutput(
‘find ‘ + week_of_dir + ‘ -mindepth 1 -maxdepth 1 -type d -printf "%P\n" | sort -nr | head -1‘)
# 探测mysql实例是否存活,如果存活继续下面的程序执行,如果不存活则直接退出程序
mysql_stat = commands.getoutput(
‘/bin/netstat -anp|grep ‘ + port + ‘ |grep -v unix|wc -l‘)
if mysql_stat >= 1:
print "mysql实例存活,可进行备份操作!"
else:
print "mysql实例不存在,备份操作终止!"
sys.exit()
# 每周生成一个周备份目录,全备和增备目录都放在此目录下面
if os.path.exists(week_of_dir):
print "周备份目录已经生成,可进行相应的全备或者增量备份"
else:
print "周备份目录未产生,创建周备份目录..."
os.makedirs(week_of_dir)
# 判断是否周日,如果是周日,直接进行全备,如果不是周日,先检查全备是否存在,不存在则进行全备,存在则进行增备
print "备份开始"
if wday == 6:
full_backup(config[‘host‘], config[‘port‘], config[‘user‘], config[‘password‘], full_backup_dir)
else:
if os.path.exists(full_backup_dir):
incr_backup(config[‘host‘], config[‘port‘], config[‘user‘], config[‘password‘],base_backup_dir,week_of_dir)
else:
full_backup(config[‘host‘], config[‘port‘], config[‘user‘], config[‘password‘],full_backup_dir)
print "备份结束,判断备份是否成功"
try:
with open("/tmp/backup.log") as f:
f.seek(-14, 2)
backup_results = f.readline().strip()
if backup_results == "completed OK!":
print "备份成功"
else:
print "备份失败"
except Error:
sys.exit()
原文:http://gaoquan.blog.51cto.com/4503718/1749931