# filename: mysqlbackup.py
# version 0.01
# author:robert lin
# email:linlianpengit@sina.com
# date:2013-08-09
import os
import time
import sys
import datetime
from stat import *
# mysql user
user = 'root'
# mysql password
passwd = '123456'
# mysqldump command
mysqlcommand = '/usr/bin/mysqldump'
# gzip command
gzipcommand = '/bin/gzip'
# you want backup mysql database
mysqldata = ['hq', 'forum_us']
# you want backup to dir
tobackup = '/dbbak/'
for db in mysqldata:
# backup file name
backfile = tobackup db '-' time.strftime('%y-%m-%d') '.sql'
# gzip file name
gzfile = backfile '.gz'
if os.path.isfile(gzfile):
print gzfile " is already backup"
else:
# backup command
back_command = mysqlcommand ' -u' user ' -p' passwd ' -p3306 ' db ' > ' backfile
if os.system(back_command)==0:
print 'successful backup to', db ' to ' backfile
else:
print 'backup failed'
# gzip command
gzip_command = gzipcommand ' ' backfile
if os.system(gzip_command)==0:
print 'successful gzip to',gzfile
else:
print 'gzip failed'
# delete back file
# show file list
filelist=[]
filelist=os.listdir(tobackup)
# delete gzfile 5 days ago
for i in range(len(filelist)):
ft=time.gmtime(os.stat(tobackup filelist[i])[st_mtime])
ftl=time.strftime('%y-%m-%d',ft)
year,month,day=ftl.split('-')
ftll=datetime.datetime(int(year),int(month),int(day))
localt=time.gmtime()
localtl=time.strftime('%y-%m-%d',localt)
year,month,day=localtl.split('-')
localtll=datetime.datetime(int(year),int(month),int(day))
days=(localtll-ftll).days
if days >5:
try:
os.remove(tobackup filelist[i])
print 'delete is ok'
except:
log=datetime.datetime.now().strftime('%y-%m-%d %h:%m:%s') " remove " tobackup filelist[i] " fail \n"
print log