码迷,mamicode.com
首页 > 数据库 > 详细

mongodb远程备份

时间:2018-07-12 13:19:59      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:else   dmi   any   str   popen   cal   mongodb   mongod   ODB   

创建备份用户

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远程备份

标签:else   dmi   any   str   popen   cal   mongodb   mongod   ODB   

原文地址:https://www.cnblogs.com/guigujun/p/9239040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!