用python写的一个数据库定时备份脚本...
时间:2010-08-13 来源:kunp
用Python写了一个定时备份Mysql的脚本,Python的好处就是代码简单,而且一看就懂。
这个程序基本上改改基本的配置,就能完成绝大多数的Mysql定期备份的需求了。
把代码贴在下面:
#! /usr/bin/env python #coding=utf-8 """ 本程序用于每日备份牧场数据库 1、备份Mysqldump每日的数据库 2、讲备份出来的数据库文件进行压缩 3、删除已压缩的原始文件 4、删除15天前生成的压缩文件 author:kunp email:[email protected] date:2010-08-14 """ import datetime import os StrBackupDir = "/data/dbbak/" StrBackupFile = "zoo" StrBackupCMD = "mysqldump -h127.0.0.1 -P3306 zoo > " StrTarCMD = "tar cvzf " IntOlddayCount = 15 if __name__ == '__main__': #get the file name for yesterday today = datetime.date.today( ) yesterday = today - datetime.timedelta( days = 1 ) strSqlFile = StrBackupFile + str( yesterday ) + ".sql" strSqlFile = StrBackupDir + strSqlFile strBackupCMD = StrBackupCMD + strSqlFile print strBackupCMD #mysqldump the DB to the new sql file os.system( strBackupCMD ) #tar the sql file to the zip file strTarFile = StrBackupFile + str( yesterday ) + ".tar.gz" strTarFile = StrBackupDir + strTarFile strTarCMD = StrTarCMD + strTarFile + " " + strSqlFile print strTarCMD #execute the tar cmd os.system( strTarCMD ) #rm the sql file after zip strDelSqlCMD = "rm " + strSqlFile print strDelSqlCMD #execute the del cmd os.system( strDelSqlCMD ) #rm the old zip file which is born 15 days ago oldday = today - datetime.timedelta( days = IntOlddayCount ) strOldTarFile = StrBackupFile + str( oldday ) + ".tar.gz" strOldTarFile = StrBackupDir + strOldTarFile strDelOldTarCMD = "rm " + strOldTarFile print strDelOldTarCMD #execute the del old zip file cmd os.system( strDelOldTarCMD )