尝试使用 python 连接到远程 MongoDB 集群,通过堡垒进行保护

Trying to connect with python to a remote MongoDB cluster, protected via a bastion

提问人:Baptiste Bortot 提问时间:6/22/2023 最后编辑:Baptiste Bortot 更新时间:6/22/2023 访问量:110

问:

我正在尝试使用以下架构连接到远程mongodb,并使用python查询数据库。

----------------------------------------------------------------------

                            |
-------------+              |    +----------+               +---------
    LOCAL    |              |    |  REMOTE  |               | PRIVATE
    CLIENT   | <== SSH w/ pkey==>|  SERVER  | <==distant==> | NETWORK
             |              |    |(BASTION) |               | MongoDB 
             |              |    |          |               | cluster
-------------+              |    +----------+               +---------
                            |
                         FIREWALL 
                  (only port 22 is open)

----------------------------------------------------------------------

该连接适用于 MongoDB Compass,开启 TLS、SSH 身份文件和密码以及以下连接字符串:

mongodb+srv://:@/admin?replicaSet=replicaset&tls=true

但是当我尝试以下python代码时:


from sshtunnel import SSHTunnelForwarder
import pymongo
connection_str=r'mongodb://127.0.0.1:27018'
pkey= r'\private_key_adress.pem',
pp_pkey= r'passphrase'
pp_mongouser=r'passphrase_mongo'
username='user_name' #same for bastion connection and mongodb connection
bastion_adress='bastion_adress'

server = SSHTunnelForwarder(
    ssh_address_or_host =(bastion_adress,22),
    ssh_username=username,
    ssh_pkey=r'\private_key_adress.pem',
    ssh_password=r'passphrase',
    remote_bind_address=('mongo_db_server_adress', 27017),
    local_bind_address=('127.0.0.1', 27018)
)

server.start()

print(server.local_bind_port) 
db = pymongo.MongoClient(connection_str,username=username, password=pp_mongouser,tls=True)["db_name"] 
print(db.list_collection_names())
server.stop()

我收到以下错误:

ServerSelectionTimeoutError

我该如何解决这个问题?

python mongodb pymongo 堡垒主机

评论


答: 暂无答案