用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.1 import zipfile import os import datetime from ftplib import ftp
3.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 desname
3.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 res
3.5. 主程序:
# main backuptime = 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:\miniconda\python.exe e:/pycharmcode/justtest/bak.py
enter func zipfolder, time:2017-08-16 19:48:39.331200
dirpath: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:\\data\\mongod.lock', cannot zip file: f:\datamongod.lock
except: [errno 13] permission denied, cannot zip file: f:\datawiredtiger.lock
dirpath:f:\data\diagnostic.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:\data\journal, 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.397000
f:\mongodbdata\\mongodb2017816.zip
enter func ftpupload, time:2017-08-16 20:08:22.728200
*get* '220 microsoft ftp service\n'
*resp* '220 microsoft ftp service'
*cmd* 'user anonymous'
*put* 'user anonymous\r\n'
*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 **********\r\n'
*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 mongodbup\r\n'
*get* '250 cwd command successful.\n'
*resp* '250 cwd command successful.'
*cmd* 'type i'
*put* 'type i\r\n'
*get* '200 type set to i.\n'
*resp* '200 type set to i.'
*cmd* 'pasv'
*put* 'pasv\r\n'
*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.zip\r\n'
*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.397000
ftp_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:\miniconda\lib\ftplib.py", line 155, in connect self.welcome = self.getresp() file "e:\miniconda\lib\ftplib.py", line 234, in getresp resp = self.getmultiline() file "e:\miniconda\lib\ftplib.py", line 220, in getmultiline line = self.getline() file "e:\miniconda\lib\ftplib.py", line 208, in getline raise eoferror eoferror
或者是如下错误:
enter ftpupload traceback (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:\miniconda\lib\ftplib.py", line 152, in connect source_address=self.source_address) file "e:\miniconda\lib\socket.py", line 722, in create_connection raise err file "e:\miniconda\lib\socket.py", line 713, in create_connection sock.connect(sa) timeouterror: [winerror 10060] 由于连接方在一段时间后没有正确答复或连接的主机没 有反应,连接尝试失败。
到此这篇关于用python实现定时备份mongodb数据并上传到ftp服务器的文章就介绍到这了,更多相关python 定时备份mongodb内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!