python写的备份mysql自动上传ftp服务器

这几天没有怎么去研究nginx,闲来无事,写了一个 python脚本・写的有点乱,以后慢慢精简,慢慢进化.
功能:
备份 mysql 的数据库,备份到 /home/eric 目录下,保留5天的备份文件过期删除,自动上传到 ftp server 服务器。

#!/usr/bin/python
# Filename: mysqlbackup-ftp.py
# version 0.01
# QQ:277057817
import    os
import    time
import    sys
import    datetime
from stat import *
from ftplib import FTP

## mysql user
User = 'root'

## mysql password
Passwd = '123456'

## mysqldump command
Mysqlcommand = '/usr/bin/mysqldump'

## you want backup mysql database
Mysqldata = 'mysql'

## you want    backup to dir
tobackup = '/home/eric/'

## backup file name
backfilename = tobackup + time.strftime('%Y-%m-%d')+'.gz'

## backup gzip command
gzip_command = "%s -u%s -p%s --opt %s |gzip >%s" %(Mysqlcommand,User,Passwd,Mysqldata,backfilename)

if os.system(gzip_command)==0:
                print 'Successful backup to',backfilename
else:
                print 'Backup FAILED'

# ################删除过期备份文件#############################
# 创建文件列表
filelist=[]
filelist=os.listdir(tobackup)
## 循环删除本地前5天的备份数据
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

########### FTP 上传#####################
## upload ftp server
ftp=FTP()

ftp.set_debuglevel(2)
ftp.connect('192.168.6.2','21')
ftp.login('eric','123456')

#ftp.cwd()
bufsize = 1024
file_handler = open(backfilename,'rb')
ftp.storbinary('STOR %s' % os.path.basename(backfilename),file_handler,bufsize)
ftp.set_debuglevel(0)

file_handler.close()
ftp.quit()

你可能感兴趣的:(mysql,数据库,python,备份)