I am using django with mysql database to develop apis. Now I got a new requirement to connect mongodb database with django. I have used following solution
from sshtunnel import SSHTunnelForwarder
import pymongo
import pprint
MONGO_HOST = "REMOTE_IP_ADDRESS"
MONGO_DB = "DATABASE_NAME"
MONGO_USER = "LOGIN"
MONGO_PASS = "PASSWORD"
server = SSHTunnelForwarder(
MONGO_HOST,
ssh_username=MONGO_USER,
ssh_password=MONGO_PASS,
remote_bind_address=('127.0.0.1', 27017)
)
server.start()
client = pymongo.MongoClient('127.0.0.1', server.local_bind_port) #
server.local_bind_port is assigned local port
db = client[MONGO_DB]
And now I am getting following
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
Is it good way to connect mongodb in django poject?
I don't think is related to the way you connect to it. That message means something in your SSH configuration is not correct.
The SSHTunnelForwarder
should be instantiated with the SSH host, port, user, and password as you first need to access the host (where sshd is running) from which you can connect to the Mongo host. I also don't see where you're passing your key for authentication. Make sure you define <your-key-instance-here>
accordingly to the type of key you have (for example for an RSA-type key using paramiko
: paramiko.RSAKey.from_private_key_file('/path/to/your/ssh/key/file')
). After that, in the client you need to specify Mongo User and Password:
@contextmanager
def _tunnel():
with SSHTunnelForwarder((ssh_host, 22),
ssh_username=SSH_USER,
ssh_pkey=<your-key-instance-here>,
remote_bind_address=(MONGO_HOST, MONGO_PORT)
) as tunneled_conn:
yield pymongo.MongoClient('mongodb://%s:%[email protected]' % (MONGO_USR, MONGO_PWD),
port=tunneled_conn.local_bind_port
)
Then in your code use it as
with _tunnel() as mongo_client:
...
I received this issue as my SSH key was not open ssh format. Stepped through the SSHTunnelForwarder code, the failing section relates to the SSH key loading using the paramiko library which loads the SSH key of the following types:
I wrote a helper to Test this directly (see below). Another catch is that the SSH key may not be found in the path.
To solve the key issue. Using PuttyGen: PuttyGen -> Load Private Key -> Conversions -> Export Open SSH.
if not (path.exists(SSH_file_full_path)):
raise Exception("SSH file not found!")
import paramiko
try:
k = paramiko.RSAKey.from_private_key_file(SSH_file_full_path,key_file_password)
except paramiko.ssh_exception.PasswordRequiredException as e:
print(sys.exc_info()[0])
raise Exception("Problem with SSH key. Probably the password is wrong.")
except paramiko.ssh_exception.SSHException:
print(sys.exc_info()[0])
raise Exception("Problem with SSH key. Most probably not open SSH format.")
except Exception as e:
print(sys.exc_info()[0])
raise Exception("Unknown SSH key load problem.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With