mongodb遠程備份
阿新 • • 發佈:2018-07-12
stderr shutil exce god else port main true make
創建備份用戶
db.createUser({user: 'backup',pwd: 'back123' ,roles : [{role : 'userAdminAnyDatabase' ,db : 'admin' },{role : 'readAnyDatabase' ,db : 'admin' },{role : 'dbOwner' ,db : 'admin' },{role : 'userAdmin' ,db : 'admin' },{role : 'root' ,db : 'admin' },{role : 'dbAdmin' ,db : 'admin' }]})
命令備份
mongodump -h 10.92.0.26 --port=27017 -ubackup -pbackup123 --authenticationDatabase admin -o /opt/data/back/
備份腳本
#coding:utf-8 import sys,subprocess,os,time,datetime import shutil def pay_mongodb_back(): try: db_host = '10.92.0.26' db_port = '27017' db_user = 'backup' db_pass = 'backup123' back_dir = '/opt/data/back/{0}/'.format(db_host) + time.strftime('%Y-%m-%d', time.localtime(time.time())) date =time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time())) TAR_BAK="mongodb_bak_{0}.zip".format(date) tmp_dir= '/tmp/{ip}tmp_mongodb_bak'.format(ip=db_host) if os.path.exists(back_dir): pass else: os.makedirs(back_dir) if os.path.exists(tmp_dir): pass else: os.makedirs(tmp_dir) ret = subprocess.Popen('mongodump -h {0} --port={1} -u {2} -p {3} --authenticationDatabase admin -o {4} &&cd {5} && zip -r {6}/{7} {8}/*'.format(db_host,db_port,db_user,db_pass,tmp_dir,tmp_dir,back_dir,TAR_BAK,tmp_dir),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE) print ('本次{ip}mongodb備份成功執行').format(ip=db_host) time.sleep(0.5) shutil.rmtree(tmp_dir) except Exception as e: print ('備份失敗,原因:',e) if __name__ == '__main__': date =time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time())) print ('備份時間:',date) pay_mongodb_back()
mongodb遠程備份