如何连接远程mongodb与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

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

解决方法:

适合我的解决方案.

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()
上一篇:python – pymongo中的快速或批量Upsert


下一篇:pymongo基础使用方法