How to connect remote mongodb with pymongo

前端 未结 3 1910
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 00:28

When I use MongoChef to connect remote mongo database, I use next parameters:


Server

  • Server: localhost
  • Por
相关标签:
3条回答
  • 2020-12-06 01:07

    This helped me to connect pymongo with mLab database in python :

    from pymongo import MongoClient
    
    MONGO_HOST = "ds123456.mlab.com"
    MONGO_PORT = 23456
    MONGO_DB = "db name"
    MONGO_USER = "Username"
    MONGO_PASS = "password"
    connection = MongoClient(MONGO_HOST, MONGO_PORT)
    db = connection[MONGO_DB]
    db.authenticate(MONGO_USER, MONGO_PASS)
    
    0 讨论(0)
  • 2020-12-06 01:16

    Or, you could just pip install ssh-pymongo:

    from ssh_pymongo import MongoSession
    
    session = MongoSession('10.1.0.90',
        port=25,
        user='USERNAME',
        password='PASSWORD',
        uri='mongodb://127.0.0.1:27017'
    )
    
    db = session.connection['DATABASE_NAME']
    
    print(db)
    
    session.stop()
    

    More examples from the package:

    Example 1 -- If your username is same, and you've configured ssh keys.

    from ssh_pymongo import MongoSession
    
    session = MongoSession('db.example.com')
    
    db = session.connection['db-name']
    

    Example 2 -- If you have some custom local authentication.

    from ssh_pymongo import MongoSession
    
    session = MongoSession('db.example.com',
        uri='mongodb://user:password@127.0.0.1/?authSource=admin&authMechanism=SCRAM-SHA-256')
    
    db = session.connection['db-name']
    

    Example 3 -- If you want to use different ports and keys.

    from ssh_pymongo import MongoSession
    
    session = MongoSession(
        host='db.example.com',
        port=21,
        user='myuser',
        key='/home/myplace/.ssh/id_rsa2'
    )
    
    db = session.connection['db-name']
    
    0 讨论(0)
  • 2020-12-06 01:30

    The solution which works for me.

    from sshtunnel import SSHTunnelForwarder
    import pymongo
    import pprint
    
    MONGO_HOST = "REMOTE_IP_ADDRESS"
    MONGO_DB = "DATABASE_NAME"
    MONGO_USER = "LOGIN"
    MONGO_PASS = "PASSWORD"
    
    server = SSHTunnelForwarder(
        MONGO_HOST,
        ssh_username=MONGO_USER,
        ssh_password=MONGO_PASS,
        remote_bind_address=('127.0.0.1', 27017)
    )
    
    server.start()
    
    client = pymongo.MongoClient('127.0.0.1', server.local_bind_port) # server.local_bind_port is assigned local port
    db = client[MONGO_DB]
    pprint.pprint(db.collection_names())
    
    server.stop()
    
    0 讨论(0)
提交回复
热议问题