python 自动备份mysql数据库并上传到FTP服务器上

时间:2021-07-24 21:18:19
 
#!/usr/bin/env python
import sys,os,time
from ftplib import FTP
mysql_usr='root'
mysql_pwd='dingjia'
mysql_db='test'
mysql_charset='gb2312'
bk_path='/home/hzhida/FTPFile/backup'
logs_path=bk_path+'Logs'

def writeLogs(filename,contents):
    f=file(filename,'aw')
    f.write(contents)
    f.close()

today=bk_path+time.strftime('%Y-%m-%d')
fname=today+os.sep+time.strftime('%H%M%S')+'.gz'

if not os.path.exists(today):
    Msg='-'*30+time.strftime('%Y-%m-%d,%H:%M:%S')+'-'*30+'n'
    if(os.mkdir(today))==None:
        Msg+='**succeed to create dir:'+today+'nn'
        writeLogs(logs_path,Msg)
    else:
        Msg+='!!create backup dir:'+today+'failed,check whether dir can write! nn'
        writeLogs(logs_path,Msg)
    sys.exit()

cmd_dump='mysqldump -u%s -p%s %s |gzip > %s' %(mysql_usr,mysql_pwd,mysql_db,fname)

if os.system(cmd_dump)==0:
    writeLogs(logs_path,'database backup: '+fname+'n')
else:
    writeLogs(logs_path,'database backup failed! n')

#上传到FTP服务器上,并确保有权限写 ftp
=FTP() ftp.set_debuglevel(2) ftp.connect('localhost','21') ftp.login('hzhida','36039975') print ftp.getwelcome() ftp.cwd('Downloads') bufsize=1024 file_handler=open(fname,'rb') ftp.storbinary('STOR sql.gz',file_handler,bufsize) ftp.set_debuglevel(0) file_handler.close()