今天简单的写了个python的mysql备份脚本,其实也不是很难呀。比shell简洁了很多!
开整:
注释都用英文写了,有些英语基础的朋友应该都可以看得懂了!
#!/usr/bin/env python #backup the gtshop #author:ley #encoding=utf8 #date:2015-06 import os,sys,datetime,time from stat import * #mysqlbackup user User = ‘root‘ #mysqlbackup password Password = ‘root‘ #mysqlbackup command Mysqlcommand = ‘/usr/local/mysql/bin/mysqldump‘ #gzip command Gzipcommand = ‘/bin/gzip‘ #backup mysql database Mysqldata = [‘gtshop‘] #backup dir Tobackup = ‘/home/gtshop_backup/‘ for DB in Mysqldata: #backup file name Backupfile = Tobackup + DB + ‘-‘ + time.strftime(‘%Y-%m-%d‘) + ‘.sql‘ #gzip file name Gzipfile = Backupfile + ‘.gz‘ if os.path.isfile(Gzipfile): print Gzipfile + "is already backup" else: #backup command Back_command = Mysqlcommand + ‘ -u‘ + User + ‘ -p‘ + Password + ‘ --events ‘ + ‘ --master-data=2 ‘ + ‘ --single-transaction ‘ + DB + ‘ > ‘ + Backupfile if os.system(Back_command) == 0: print ‘Sucessful backup gtshop‘ else: print ‘Backup failed‘ #gzip command Gzip_command = Gzipcommand + ‘ ‘ + Backupfile if os.system(Gzip_command) == 0: print ‘sucessful gzip gtshop‘ else: print ‘gzip failed‘
执行结果:
[[email protected] script]# python mysql_backup.py Sucessful backup gtshop sucessful gzip gtshop
最后还可以根据需求,添加到任务计划中!
时间: 2024-10-11 21:26:20