备份数据库压缩备份文件上传备份文件
#!/usr/bin/evn python3 # -*- coding :utf-8 -*- import time import os from zipfile import ZipFile from os import listdir from os.path import isfile, isdir, join from ftplib import FTP mon = str(time.localtime().tm_mon) if int(mon) <= 9: mon = '0'+mon date = str(time.localtime().tm_year) + mon + str(time.localtime().tm_mday) date_del = time.time() - 60 * 60 * 24 * 3 mondel = str(time.localtime(date_del).tm_mon) if int(mondel) <= 9: mondel = '0'+mondel date_del = str(time.localtime(date_del).tm_year) + mondel + str(time.localtime(date_del).tm_mday) bak_dir = 'D:\\mysql_bak' + '\\' + date + '\\' del_dir = 'D:\\mysql_bak' + '\\' + date_del if not os.path.isdir(bak_dir): os.mkdir(bak_dir) mysqldump = 'D:\\app\\mysql56\\bin\\mysqldump --defaults-extra-file=D:\\mysql_bak\\x5m_db_user.cnf --default-character-set=utf8 --quote-names -R --opt -A > ' + bak_dir + 'all_databases.sql' os.system(mysqldump) if os.path.isdir(del_dir): os.remove(os.path.join(del_dir, 'all_databases.sql')) os.rmdir(del_dir) def addFileIntoZipfile(srcDir, fp): for subpath in listdir(srcDir): subpath = join(srcDir, subpath) if isfile(subpath): fp.write(subpath) elif isdir(subpath): fp.write(subpath) addFileIntoZipfile(subpath, fp) def zipCompress(srcDir, desZipfile): with ZipFile(desZipfile, mode='a') as fp: addFileIntoZipfile(srcDir, fp) zipdir = 'D:\\mysql_bak' + '\\' + date + '.zip' delzipdir = 'D:\\mysql_bak' + '\\' + date_del + '.zip' filedeletename = date_del + '.zip' datehome = 'D:\\mysql_bak' paths = [bak_dir] for path in paths: zipCompress(path, zipdir) if filedeletename in os.listdir(datehome): os.remove(delzipdir) else: print('do not find file %s!' % filedeletename) host = '172.16.60.205' username = 'jfedu1' password = '123456' ftpuploadhome = '/home/jfedu1' ftp = FTP() timeout = 30 port = 21 ftp.connect(host) ftp.login(username, password) print(ftp.getwelcome()) ftp.cwd(ftpuploadhome) path = zipdir filename = date + '.zip' ftp.storbinary('STOR ' + filename, open(path, 'rb')) uploadfile = ftpuploadhome + '/' + filename if uploadfile in ftp.nlst(ftpuploadhome): print('upload success!') else: ftp.storbinary('STOR ' + filename, open(path, 'rb')) ftp.quit()
笔记解决问题思路;首先是备份数据库,要求用完全备份,备份后删除3天前的备份数据,然后是压缩文件,同样删除3天前压缩的文件
最后是吧压缩的文件上传到ftp服务器,检查上传是否成功!