zoukankan      html  css  js  c++  java
  • mongodb远程备份

    创建备份用户

    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()
    
    
    
  • 相关阅读:
    Python中常用的模块(sys模块)
    Python中常用的模块(OS模块)
    Python中常用的模块(time模块)
    Python中常用的模块(random模块)
    Python生成器详解
    Python装饰器详解
    python 两个list 求交集,并集,差集
    数据库中的视图索引
    数据库中的外键和主键理解
    mssql学习
  • 原文地址:https://www.cnblogs.com/guigujun/p/9239040.html
Copyright © 2011-2022 走看看