Using python 3.10.10 on Windows 10 I am trying to connect to a mongo
database via ssh ideally. On the command line I just do
ssh [email protected]
mongo
and I can query the mongo DB. With the following python code
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
HOST = "111.222.333.444"
USER = "myuser"
class Mongo:
def __init__(self):
self.host = HOST
self.user = USER
self.uri = f"mongodb://{self.user}@{self.host}"
def connection(self):
try:
client = MongoClient(self.uri)
client.server_info()
print('Connection Established')
except ConnectionFailure as err:
raise(err)
return client
mongo = Mongo()
mongo.connection()
however I get an error
pymongo.errors.ConfigurationError: A password is required.
But as I am able to just login via ssh using my public key I do not require a password. How can this be solved in python?
I also tried to run a command on the command line using ssh
alone like
ssh [email protected] "mongo;use mydb; show collections"
but this does not work like that either.
2
Answers
Here is the solution that I found in the end, as simple as possible, and it can be run from within python, and without any special module to install, from a windows powershell:
You do two different things. In the first command you connect via ssh (using port 22) to the remote server. On the remote server you start the
mongo
shell. In the second command, you try to connect directly to the mongod server (default port 27017).In your case
myuser
is the user on remote server operating system, not the user on the MongoDB.You can (almost) always connect to a MongoDB without username/password, however when you provide a username then you also need a password. Try
It is not fully clear what you try to achieve. You can configure MongoDB to logon with x509 certificate instead of username/password, see Use x.509 Certificates to Authenticate Clients. These connections are also encrypted via TLS/SSL.
Or are you looking to configure a SSH-Tunnel? See https://serverfault.com/questions/597765/how-to-connect-to-mongodb-server-via-ssh-tunnel