python备份binlog
mysql备份每天进行一次全备份,服务器故障后,没有binlog的情况下,存在一天的数据丢失情况,所以每一小时或几小时备份binlog到备份服务器。当然,有主从可不备份binlog。#!/usr/bin/python#--*-- coding:utf-8 --*--import osimport timeimport loggingfrom datetime import da...
·
mysql备份每天进行一次全备份,服务器故障后,没有binlog的情况下,存在一天的数据丢失情况,所以每一小时或几小时备份binlog到备份服务器。当然,有主从可不备份binlog。
#!/usr/bin/python
#--*-- coding:utf-8 --*--
import os
import time
import logging
from datetime import datetime
# LOG INFO
log='/data/scripts/logs/'
isExists = os.path.exists(log)
if not isExists:
os.makedirs(log)
logging.basicConfig(level=logging.INFO,
format='%(asctime)s: %(levelname)-4s %(message)s',
filename= log + 'backup_binlog_' + time.strftime('%Y%m%d_%H%M%S', time.localtime()) + '.log',
filemode='w',
datefmt='%Y%m%d %X')
def main():
# get local ip
ip = os.popen("/sbin/ifconfig | grep 'inet '| grep -v '127.0.0.1'| awk '{print $2}'").read().replace('\n','')
# 备份开始点
lastlog = "/data/scripts/lastlog"
with open(lastlog, 'r') as f:
bf = f.read()
f.close()
# 所有binlog,用于备份,由近到远排序后存到mysqlbin文件
mysqlbin = "/data/scripts/mysqlbin"
cmd = "/usr/local/mysql/bin/mysql -e \"show master logs;\" | grep mysql | awk '{print $1}' |sort -r > %s"%(mysqlbin)
os.system(cmd)
# 生成新binlog,记录备份位置,此binlog下次备份
cmd = "/usr/local/mysql/bin/mysql -e \"flush logs;\""
os.system(cmd)
# 备份结束点
cmd = "/usr/local/mysql/bin/mysql -e \"show master logs;\" | grep mysql | tail -1|awk '{print $1}'|awk -F. '{print $2}' > %s"%(lastlog)
os.system(cmd)
with open(lastlog, 'r') as f:
ef = f.read()
f.close()
# 此次备份的binlog数量
num = int(ef) - int(bf)
binlog = "/data/mysql/"
path = "/media/dbbackup/" + ip + "/binlogs/"
isExists = os.path.exists(path)
logging.info("backup binlog mount: " + str(num))
if not isExists:
os.makedirs(path)
# 删除不需要备份的记录
cmd = "sed -i ''%d' , $d' %s "%(num + 1,mysqlbin)
logging.info(cmd)
os.system(cmd)
# 开始备份
f=open(mysqlbin,'r')
lines = f.readlines()
for line in lines:
fname = binlog + line.strip()
cmd = 'cp ' + fname + ' ' + path
logging.info(cmd)
os.system(cmd)
f.close()
if __name__ == '__main__':
logging.info('##################################################')
main()
logging.info('##################################################')
脚本用到两个临时文件
1、lastlog(上次备份到的日志后几位)初始化如下:
echo 000004 > /data/scripts/lastlog
2、mysqlbin存放当次需要备份的所有binlog文件名
更多推荐
已为社区贡献3条内容
所有评论(0)