用Python实现定时备份Mongodb数据并上传到FTP服务器
实现的功能:在win7下,每天晚上1点,自动将 F:/data中所有文件进行压缩,以[mongodb+日期]命名,将压缩好的文件存储在本地目录 F:MongoDbData,然后将这个压缩好的文件上传到ftp://192.168.0.101/MongoDBup/目录下
分三步:
第一步:搭建FTP服务器,配置好FTP环境。 第二步:用python编写压缩文件并实现FTP上传的脚本第三步:使用win7自带的任务计划程序定时执行python脚本
1. 环境Python:3.6.1Python IDE:pycharm系统:win7
2. 搭建FTP服务器,配置好FTP环境2.1. 启用FTP和IIS服务器
注意:要全部展开,勾选上。
2.2. 添加FTP服务器 2.3. 设置参数 2.4. 设置成功,访问 3. 用python编写压缩文件并实现FTP上传的脚本3.1. Import包:# python3.6.1import zipfileimport osimport datetimefrom ftplib import FTP3.2. 定义配置信息:
# 定义配置信息srcFolder = r'F:Data' # 被压缩的源数据,文件夹形式desFolder = r’F:MongoDbData’ # 压缩好的数据临时存放的位置ftp_url = '192.168.0.101' # FTP服务器地址ftp_port = 21 # FTP服务端口号ftpUploadFolder = 'MongoDBup' # 压缩数据在FTP服务器上存放的位置3.3. 压缩数据源(文件夹):
# 压缩文件夹def zipFolder(srcFolder, desFolder, date): ’’’ :param srcFolder: 被压缩的源数据位置 :param desFolder: 压缩之后文件的存放路径 :param date: 执行压缩的当前时间,datetime产生(ext:2017-08-16 14:56:40.872613) :return: 压缩文件的路径 ’’’ startTime = datetime.datetime.now() print(f'Enter func zipFolder, time:{startTime}') desName = f'{desFolder}mongodb{date.year}{date.month}{date.day}.zip' # 检查是否已经压缩过了 if os.path.exists(desName): endTime = datetime.datetime.now() print(f'Already exsist, leave func zipFolder, time:{endTime}, usedTime:{endTime-startTime}') return desName z = zipfile.ZipFile(desName, ’w’, zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(srcFolder): print(f'dirpath:{dirpath}, dirnames:{dirnames}, filenames:{filenames}') for filename in filenames: try:# Mongodb在运行时,有几个关于lock的文件无法压缩,为了避免程序终止,忽略这几个文件z.write(os.path.join(dirpath, filename)) except Exception as e:print(f'except: {e}, cannot zip file: {dirpath}{filename}') z.close() endTime = datetime.datetime.now() print(f'zip done, leave func zipFolder, time:{endTime}, usedTime:{endTime-startTime}') return desName3.4. 文件上传到FTP服务器上:
# 上传文件至FTP服务器def ftpUpload(filename, folder, ftp_url, ftp_port): ’’’ :param filename: 待上传文件路径 :param folder: 文件上传至FTP服务器上的存储目录 :param ftp_url: FTP服务器IP :param ftp_port: 端口号,默认为21 :return: status code ’’’ startTime = datetime.datetime.now() print(f'Enter func ftpUpload, time:{startTime}') ftp = FTP() ftp.set_debuglevel(2) # set debug level, detail info:2, close:0 ftp.connect(ftp_url, ftp_port) ftp.login(’’, ’’) # 登录,如果匿名登录则用空串代替 print(ftp.getwelcome()) # ext: *welcome* ’220 Microsoft FTP Service’ ftp.cwd(folder) # Change to a directory on FTP server bufsize = 1024 # 设置缓冲块大小 file_handler = open(filename, ’rb’) # 读模式在本地打开文件 res = -1 try: # 为了避免程序终止,忽略可能出现的错误 res = ftp.storbinary(f'STOR {os.path.basename(filename)}', file_handler, bufsize) # upload file except Exception as e: print(f'except: {e}, cannot upload file: {ftp_url}:{ftp_port} {filename}') finally: ftp.set_debuglevel(0) # 关闭debug信息 file_handler.close() ftp.quit() endTime = datetime.datetime.now() print(f'Upload done, leave func ftpUpload, time:{endTime}, usedTime:{endTime-startTime}') return res3.5. 主程序:
# mainbackupTime = datetime.datetime.now()zip_des_name = zipFolder(srcFolder, desFolder, backupTime)print(zip_des_name)ftp_res = ftpUpload(zip_des_name, ftpUploadFolder, ftp_url, ftp_port)print(f'ftp_res: {ftp_res}')4. 使用win7自带的任务计划程序定时执行python脚本
位置:开始 ——> 附件 ——> 系统工具 ——> 任务计划程序
不需要时,右键——>删除任务 即可
5. 效果5.1. 本地生成的压缩文件 5.2. 上传至FTP服务器的压缩文件 5.3. 详细信息-性能-时间日志信息:
源文件data总共8.7G,压缩后5.3G,压缩时间20m,局域网内上传时间18m。
E:Minicondapython.exe E:/PyCharmCode/Justtest/bak.pyEnter func zipFolder, time:2017-08-16 19:48:39.331200dirpath:F:Data, dirnames:[’diagnostic.data’, ’journal’], filenames:[’collection-0--394122179086539486.wt’, ’collection-102--394122179086539486.wt’, ’collection-104--394122179086539486.wt’, ’collection-106--394122179086539486.wt’, ’collection-108--394122179086539486.wt’], ’_mdb_catalog.wt’]except: [Errno 13] Permission denied: ’F:Datamongod.lock’, cannot zip file: F:Datamongod.lockexcept: [Errno 13] Permission denied, cannot zip file: F:DataWiredTiger.lockdirpath:F:Datadiagnostic.data, dirnames:[], filenames:[’metrics.2017-08-04T07-04-29Z-00000’, ’metrics.2017-08-05T10-47-22Z-00000’, ’metrics.2017-08-06T14-52-22Z-00000’, ’metrics.2017-08-07T18-17-22Z-00000’, ’metrics.2017-08-15T06-09-26Z-00000’, ’metrics.2017-08-16T09-51-29Z-00000’]dirpath:F:Datajournal, dirnames:[], filenames:[’WiredTigerLog.0000000247’, ’WiredTigerPreplog.0000000006’, ’WiredTigerPreplog.0000000007’, ’WiredTigerPreplog.0000000008’]zip done, leave func zipFolder, time:2017-08-16 20:08:22.728200, usedTime:0:19:43.397000F:MongoDbDatamongodb2017816.zipEnter func ftpUpload, time:2017-08-16 20:08:22.728200*get* ’220 Microsoft FTP Servicen’*resp* ’220 Microsoft FTP Service’*cmd* ’USER anonymous’*put* ’USER anonymousrn’*get* ’331 Anonymous access allowed, send identity (e-mail name) as password.n’*resp* ’331 Anonymous access allowed, send identity (e-mail name) as password.’*cmd* ’PASS **********’*put* ’PASS **********rn’*get* ’230 User logged in.n’*resp* ’230 User logged in.’*welcome* ’220 Microsoft FTP Service’220 Microsoft FTP Service*cmd* ’CWD MongoDBup’*put* ’CWD MongoDBuprn’*get* ’250 CWD command successful.n’*resp* ’250 CWD command successful.’*cmd* ’TYPE I’*put* ’TYPE Irn’*get* ’200 Type set to I.n’*resp* ’200 Type set to I.’*cmd* ’PASV’*put* ’PASVrn’*get* ’227 Entering Passive Mode (192,168,0,101,11,221).n’*resp* ’227 Entering Passive Mode (192,168,0,101,11,221).’*cmd* ’STOR mongodb2017816.zip’*put* ’STOR mongodb2017816.ziprn’*get* ’125 Data connection already open; Transfer starting.n’*resp* ’125 Data connection already open; Transfer starting.’*get* ’226 Transfer complete.n’*resp* ’226 Transfer complete.’Upload done, leave func ftpUpload, time:2017-08-16 20:26:20.125200, usedTime:0:17:57.397000ftp_res: 226 Transfer complete.
6. 注意事项 6.1. FTP服务器IP地址变更处理6.1.1. 第一步,修改FTP服务器站点配置。
6.1.2. 第二步,修改代码中FTP登录IP
ftp.connect('172.16.7.107', 21)
6.1.3. 出错信息 如果只是单纯按照6.1.2 修改登录IP,没有修改FTP服务器站点设置的话,将会出现如下莫名其妙的错误:
enter ftpUpload*get* ’’Traceback (most recent call last): File 'AutoBackupMongoTest.py', line 64, in <module> ftp_res = ftpUpload(zip_des_name, ftpUploadFolder) File 'AutoBackupMongoTest.py', line 42, in ftpUpload ftp.connect(’172.16.7.107’, 21) File 'E:Minicondalibftplib.py', line 155, in connect self.welcome = self.getresp() File 'E:Minicondalibftplib.py', line 234, in getresp resp = self.getmultiline() File 'E:Minicondalibftplib.py', line 220, in getmultiline line = self.getline() File 'E:Minicondalibftplib.py', line 208, in getline raise EOFErrorEOFError
或者是如下错误:
enter ftpUploadTraceback (most recent call last): File 'AutoBackupMongoTest.py', line 63, in <module> ftp_res = ftpUpload(zip_des_name, ftpUploadFolder) File 'AutoBackupMongoTest.py', line 41, in ftpUpload ftp.connect('192.168.0.101', 21) File 'E:Minicondalibftplib.py', line 152, in connect source_address=self.source_address) File 'E:Minicondalibsocket.py', line 722, in create_connection raise err File 'E:Minicondalibsocket.py', line 713, in create_connection sock.connect(sa)TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
到此这篇关于用Python实现定时备份Mongodb数据并上传到FTP服务器的文章就介绍到这了,更多相关Python 定时备份Mongodb内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章: