#!/usr/bin/python
#! _*_ coding:utf-8 _*_
from datetime import date, datetime, timedelta
import os,time
user = ‘dbuser‘
passw = ‘password‘
ip = ‘10.8.8.8‘
dir = ‘/data/backup/db/tmp‘
mysqlbase = ‘/usr/local/mysql/bin/‘
if os.path.isdir(dir):
print("dir ok")
else:
os.makedirs(dir)
DBNAME=[‘db1‘,‘db2‘,‘db3‘]
os.chdir(dir)
for dbname in DBNAME:
print(passw)
ad = os.popen(mysqlbase+‘mysql -h‘+ip+‘ -u‘+user+‘ -p‘+passw+‘ -e "use ‘ + dbname + ‘;show tables "|grep -v Tables_in‘).read()
ad1=ad.replace(‘\n‘,‘,‘).rstrip(‘,‘).split(‘,‘)
for tabname in ad1:
os.system(mysqlbase+‘mysqldump -h‘+ip+‘ -u‘+user+‘ -p‘+passw+‘ --set-gtid-purged=off --single-transaction -R ‘+dbname+‘ ‘ + tabname+‘ > ‘+dir+ ‘/‘+dbname + ‘.‘+ tabname +‘.sql‘)
dat = time.strftime(‘%Y%m%d_%H%M‘,time.localtime(time.time()))
os.system(‘cd ‘+dir+‘;tar zcvf ‘+dat+dbname+‘.tar.gz *sql; rm -f *.sql‘)
设置计划任务每小时备份一次方便恢复单表:
0 */1 * * * /root/python/mysqldump_table.py >/dev/null 2>&1
欢迎各位一起交流。