您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)使用Python怎么對Mongodb數(shù)據(jù)定時備份,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
1. 環(huán)境
Python:3.6.1Python IDE:pycharm系統(tǒng):win7
注意:要全部展開,勾選上。
# python3.6.1 import zipfile import os import datetime from ftplib import FTP
# 定義配置信息 srcFolder = r"F:\Data" # 被壓縮的源數(shù)據(jù),文件夾形式 desFolder = r'F:\MongoDbData\\' # 壓縮好的數(shù)據(jù)臨時存放的位置 ftp_url = "192.168.0.101" # FTP服務(wù)器地址 ftp_port = 21 # FTP服務(wù)端口號 ftpUploadFolder = "MongoDBup" # 壓縮數(shù)據(jù)在FTP服務(wù)器上存放的位置
# 壓縮文件夾 def zipFolder(srcFolder, desFolder, date): ''' :param srcFolder: 被壓縮的源數(shù)據(jù)位置 :param desFolder: 壓縮之后文件的存放路徑 :param date: 執(zhí)行壓縮的當前時間,datetime產(chǎn)生(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" # 檢查是否已經(jīng)壓縮過了 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在運行時,有幾個關(guān)于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
# 上傳文件至FTP服務(wù)器 def ftpUpload(filename, folder, ftp_url, ftp_port): ''' :param filename: 待上傳文件路徑 :param folder: 文件上傳至FTP服務(wù)器上的存儲目錄 :param ftp_url: FTP服務(wù)器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 # 設(shè)置緩沖塊大小 file_handler = open(filename, 'rb') # 讀模式在本地打開文件 res = -1 try: # 為了避免程序終止,忽略可能出現(xiàn)的錯誤 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) # 關(guān)閉debug信息 file_handler.close() ftp.quit() endTime = datetime.datetime.now() print(f"Upload done, leave func ftpUpload, time:{endTime}, usedTime:{endTime-startTime}") return res
# 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}")
位置:開始 ——> 附件 ——> 系統(tǒng)工具 ——> 任務(wù)計劃程序
不需要時,右鍵——>刪除任務(wù) 即可
日志信息:
源文件data總共8.7G,壓縮后5.3G,壓縮時間20m,局域網(wǎng)內(nèi)上傳時間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.1.1. 第一步,修改FTP服務(wù)器站點配置。
6.1.2. 第二步,修改代碼中FTP登錄IP
ftp.connect("172.16.7.107", 21)
6.1.3. 出錯信息 如果只是單純按照6.1.2 修改登錄IP,沒有修改FTP服務(wù)器站點設(shè)置的話,將會出現(xiàn)如下莫名其妙的錯誤:
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] 由于連接方在一段時間后沒有正確答復或連接的主機沒 有反應(yīng),連接嘗試失敗。
看完上述內(nèi)容,你們對使用Python怎么對Mongodb數(shù)據(jù)定時備份有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。