0

I am trying to connect to a remote mongodb, with the following architecture, with python to query the database.

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

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

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

The connection works fine with MongoDB Compass with TLS on, SSH Identity file and passphrase and the following connection string :

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

But when I try the following python code :


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

I get the following error :

ServerSelectionTimeoutError

How can i fix that ?

0 Answers0