如何连接远程mongodb与pymongo

时间:2017-03-10 12:34:40

标签: python mongodb python-3.x ssh pymongo

当我使用MongoChef连接远程mongo数据库时,我使用下一个参数:

服务器

  • 服务器: localhost
  • 端口: 27017

SSH隧道

  • SSH地址: 10.1.0.90

  • 端口: 25

  • SSH用户名:用户名

  • SSH密码:密码

当我与Pymongo联系时,我有下一个代码:

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)

但我有下一个错误:

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

拜托,你能帮帮我解决这个问题吗?我该怎么办?

3 个答案:

答案 0 :(得分:12)

适合我的解决方案。

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

答案 1 :(得分:1)

或者,您可以只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()

该包中的更多示例:

示例1-如果您的用户名相同,并且您已配置ssh密钥。

from ssh_pymongo import MongoSession

session = MongoSession('db.example.com')

db = session.connection['db-name']

示例2-如果您具有一些自定义的本地身份验证。

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']

示例3-如果要使用其他端口和键。

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']

答案 2 :(得分:-4)

这帮助我在python中连接pymongo和mLab数据库:

"Created by" == @me