python实现mongodb的备份与导

发布时间:2019-09-15 09:57:05编辑:auto阅读(1901)


                                        python实现mongodb的备份与导入


    背景:

    192.168.122.1    python

    192.168.122.11  mongodb


    Python备份mongo


    Screenshot from 2018-08-13 15-29-20.png

    Screenshot from 2018-08-13 15-30-01.png


    代码:

    # -*- 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() 


    运行结果:

    Screenshot from 2018-08-13 15-32-31.png


    如下,已经备份到主机目录下;

    Screenshot from 2018-08-13 15-33-00.png


    Python导入mongodb数据


    Screenshot from 2018-08-13 15-35-08.png

    Screenshot from 2018-08-13 15-35-40.png


    代码:

    # -*- 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()


    运行结果:

    Screenshot from 2018-08-13 15-37-52.png


    没有运行代码这是一个全新的主机,mongodb中没有数据

    Screenshot from 2018-08-13 15-39-35.png

    导入数据后:

    Screenshot from 2018-08-13 15-40-53.png




关键字