Search code examples
pythonmongodbsshopensslpymongo

pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: localhost:27017: [WinError 10054]


I'm trying to connect to mongoclient via ssh tunnel. Here is the code

import pymongo
from sshtunnel import SSHTunnelForwarder

with open("config.json") as f:
    config = json.load(f)

config_params = config["dev_db"]

# SSH server credentials
SSH_HOST = config_params['host_name']
SSH_PORT = 22
SSH_USER = config_params['host_username']
SSH_KEY = config_params['private_key']

# MongoDB server credentials
MONGO_HOST = config_params["db_uri"]
MONGO_PORT = 27017
params = config_params['params']

# Create an SSH tunnel
with SSHTunnelForwarder(
    (SSH_HOST, SSH_PORT),
    ssh_username=SSH_USER,
    ssh_pkey=SSH_KEY,
    remote_bind_address=(MONGO_HOST, MONGO_PORT),
    local_bind_address=('localhost', MONGO_PORT),
) as server:

    # Connect to MongoDB
    client = pymongo.MongoClient(
        'localhost',
        server.local_bind_port,
        username = params['username'],
        password=params['password'],
        tlsAllowInvalidCertificates=True,
        tls=True,
        tlsCAFile=params['tlsCAFile'],
        retryWrites=False
    )
    print(client)
    print(client.list_database_names())

Credentials are 100% valid. I can connect with them via mongo Atlas and everything works. I also checked if pems are available from code and they really are.

Python 3.7 but I also tried 3.11. Pymongo 4.3.3 and sshtunnel 0.4. Sorry I spend on it may be 12 hours with the help of ChatGPT and we are both have no ideas :/


Solution

  • After two days and some random sh*t I commented

    with SSHTunnelForwarder(
       (SSH_HOST, SSH_PORT),
       ssh_username=SSH_USER,
       ssh_pkey=SSH_KEY,
       remote_bind_address=(MONGO_HOST, MONGO_PORT),
       #local_bind_address=('localhost', MONGO_PORT),
    ) as server:
    

    this line and it's worked out ! I assume that it faced with some conficts during binding the port. Thanks everybody!