Hey everyone,
I have some troubles with connecting to one of our Mongo DB instances from my local machine via Python. While I seem to be able to connect, I cannot use the connection and all actions result in an authentication error.
- The exact same MongoDB URI string and SSH settings I am using in Python are working fine in MongoDB Compass.
- The remote is on Azure.
- The error I am getting is
Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}
- I am using a MongoDB URI in the form
"mongodb://{user}:{password}@127.0.0.1:27017/{collection}"
, I also tried making the authentication source explicit as explained here ("mongodb://{user}:{password}@127.0.0.1:27017/{collection}?authSource=admin"
) with no luck. - And yes, the mongo db user I am logging in with, has both access rights to the
/admin
and/{collection}
collections.
Any hints as to what I could be doing wrong?
Cheers,
Ferdinand
My code:
from sshtunnel import SSHTunnelForwarder
from pymongo import MongoClient
class MongoDatabaseSshConnection:
"""
"""
def __init__(self, server_url: str, server_port: int, server_user: str, server_password: str,
database_uri: str, binding: tuple[str, int] = ("127.0.0.1", 27017),
autoConnect: bool = True) -> None:
"""
"""
self.mongoClient: MongoClient | None = None
self.sshTunnel: SSHTunnelForwarder | None = None
self.server_user: str = server_user
self.server_password: str = server_password
self.server_port: int = server_port
self.server_url: str = server_url
self.database_uri: str = database_uri
self.binding: tuple[str, int] = binding
if autoConnect:
self.Connect()
def Connect(self) -> None:
"""
"""
self.tunnel = SSHTunnelForwarder(
(self.server_url, self.server_port),
ssh_username=self.server_user,
ssh_password=self.server_password,
remote_bind_address=self.binding
)
self.tunnel.start()
self.client = MongoClient(self.database_uri)
def __del__(self) -> None:
"""
"""
if self.client is not None:
self.client.close()
if self.tunnel is not None:
self.tunnel.stop()
def TestRemoteConnection(self) -> None:
"""
"""
try:
self.client.admin.command('ping')
print("Ping successful")
except Exception as e:
print(f"Ping failed: {e}")
def main() -> None:
"""
"""
serverUrl: str
serverPort: int
userName: str
userPassword: str
databaseUri: str
binding: tuple[str, int] = ("127.0.0.1", 27017)
connection: MongoDatabaseSshConnection = MongoDatabaseSshConnection(
serverUrl, serverPort, userName, userPassword, databaseUri, binding)
connection.TestRemoteConnection()