When I use MongoChef to connect remote mongo database, I use next parameters:
Server
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)
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:
from ssh_pymongo import MongoSession
session = MongoSession('db.example.com')
db = session.connection['db-name']
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']
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']
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()