Create a backup user
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' }]})
Command backup
mongodump -h 10.92.0.26 --port=27017 -ubackup -pbackup123 --authenticationDatabase admin -o /opt/data/back/
Backup scripts
#coding: Utf-8import sys,subprocess,os,time,datetimeimport shutildef pay_mongodb_back (): Try:db_host = ' 10.92.0. 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 (' This time {ip}mongodb backup successfully executed '). Format (ip=db_host) time.sleep (0.5) Shutil.rmtree (Tmp_dir) exce PT Exception as E:print (' Backup failed, Reason: ', e) if __name__ = = ' __main__ ': Date =time.strftime ('%y-%m-%d-%h:%m:%s ', time. LocalTime (Time.time ())) print (' Backup time: ', date) Pay_mongodb_back ()
MongoDB Remote Backup