Skip to content

Instantly share code, notes, and snippets.

@m-mohsin-ali
Created December 26, 2021 17:59
Show Gist options
  • Save m-mohsin-ali/8be51a32560ef4de85b9555e8af53096 to your computer and use it in GitHub Desktop.
Save m-mohsin-ali/8be51a32560ef4de85b9555e8af53096 to your computer and use it in GitHub Desktop.
Accessing Mongodb Localhost Behind SSH
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