Created
December 26, 2021 17:59
-
-
Save m-mohsin-ali/8be51a32560ef4de85b9555e8af53096 to your computer and use it in GitHub Desktop.
Accessing Mongodb Localhost Behind SSH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo import MongoClient | |
from pprint import pprint | |
from sshtunnel import SSHTunnelForwarder | |
#Creating a SSH Tunnel to bind a the local port onto our system | |
server = SSHTunnelForwarder( | |
('IP_ADDRESS', 22),#IP Address to server | |
ssh_username = 'USERNAME', #Your ssh conection username | |
ssh_password = 'PASSWORD', #Your ssh conection password | |
remote_bind_address = ('localhost', 27017) #the port on the server you want to bind to i.e mongodb default port is 27017 | |
) | |
server.start() | |
#DB Config change as you find best | |
db_config = { | |
"CON_STRING": f"mongodb://localhost:{server.local_bind_port}/?readPreference=primary&appname=jupyter&ssl=false", | |
"DB_NAME": "inventory", | |
"COLLECTION_NAME": "users", | |
} | |
#List the data in an specific collection | |
data_list=[] | |
with MongoClient(db_config['CON_STRING']) as client: | |
db = client[db_config['DB_NAME']] | |
collections = db[db_config['COLLECTION_NAME']] | |
for post in collections.find(): | |
data_list.append(post) | |
pprint(data_list) | |
server.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment