python實現mongodb的備份與導入
python實現mongodb的備份與導入
背景:
192.168.122.1 python
192.168.122.11 mongodb
Python備份mongo
代碼:
# -*- coding:utf-8 -*-
import time import os DBUSER='myadmin' #用戶
DBPASS='redhat' #密碼
IP='192.168.122.11' #主機
DATA_DIR='/data' #目錄
PATH_DUMP='/usr/local/mongodb/bin/mongodump' #命令路徑
BACKITEMS=[ "%s -h %s:27017 -u %s -p %s -o %s" % (PATH,IP,DBUSER,DBPASS,DATA_DIR)
]
def backData():
try:
for item in BACKITEMS:
print item
print os.system(item)
except RuntimeError,e:
print str(e)
if __name__=="__main__":
backData()
運行結果:
如下,已經備份到主機目錄下;
Python導入mongodb數據
代碼:
# -*- coding:utf-8 -*-
import time
import os
DBUSER='myadmin'
DBPASS='redhat'
IP='192.168.122.1' #將數據導入改主機
DATA_DIR='/data'
PATH_RES='/usr/local/mongodb/bin/mongorestore'
BACKITEMS=[
"%s -h %s:27017 --dir %s" % (PATH_RES,IP,DATA_DIR)
]
def backData():
try:
for item in BACKITEMS:
print item
print os.system(item)
except RuntimeError,e:
print str(e)
if __name__=="__main__":
backData()
運行結果:
沒有運行代碼這是一個全新的主機,mongodb中沒有數據
導入數據後:
python實現mongodb的備份與導入