Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect remote mongodb with pymongo

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


Server

  • Server: localhost
  • Port: 27017

SSH Tunnel

  • SSH address: 10.1.0.90

  • Port: 25

  • SSH Username: username

  • SSH Password: password


When I connect with Pymongo, I have the next code:

import pymongo

MONGO_HOST = "10.1.0.90"
MONGO_PORT = 25
MONGO_DB = "db_name"
MONGO_USER = "username"
MONGO_PASS = "password"

con = pymongo.MongoClient(MONGO_HOST, MONGO_PORT)
db = con[MONGO_DB]
db.authenticate(MONGO_USER, MONGO_PASS)

print(db)

But I have the next error:

pymongo.errors.ServerSelectionTimeoutError: 10.1.2.84:27017: [Errno 111] Connection refused

Please, could you help me with this problem? What did I do wrong?

like image 295
Volodymyr Nazarenko Avatar asked Mar 10 '17 12:03

Volodymyr Nazarenko


People also ask

How does Python connect to MongoDB remote?

a) First, ssh into your MongoDB server through PuTTY by entering MongoDB server IP address and the port as 22. b) Enter the command mongo to enter into the MongoDB shell. Since there is no authentication set up yet, it will allow you directly without any authnz checks.

Is PyMongo a MongoDB client?

Python PyMongo MongoClient allows Developers to build scalable and flexible applications using MongoDB NoSQL Database to maintain flexible schema. Python PyMongo MongoClient is suited for JSON object data that is used in modern applications and supported by MongoDB.


1 Answers

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()
like image 175
Volodymyr Nazarenko Avatar answered Sep 18 '22 17:09

Volodymyr Nazarenko