简体   繁体   中英

Python script to Connect to remote mongoDB using ssh-tunnel and pymongo client is failing with errors

I am trying to connect to remote mongodb, here the ssh access has a different username and password, And the mongodb has a different username and password.

I tried passing the username and password of ssh in ssh tunnel server, and the mongodb credentials in the client, but getting an error stating:

pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused

Here the ssh connection is happening, whereas the mongodb is not getting connected

 def Collect_Pid_DB():

     MONGO_DB = "mydatabasename"

     server = SSHTunnelForwarder(
     (MONGO_HOST,22),
     ssh_username=username,
     ssh_password=password,
     remote_bind_address=('127.0.0.1', 27017)
 )
 server.start()
 #print (server)
 uri = "mongodb://admin:" + urllib.quote("p@ssW0$3") + "@127.0.0.1:27017"
 client = pymongo.MongoClient(uri,server.local_bind_port)
 db = client[MONGO_DB]
 print (db)
 print(json.dumps(db.collection_names(), indent=2))
 server.stop()

Actual results:

Database(MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True), u'MissingPatches')
 Traceback (most recent call last):
   File "duplicate.py", line 7, in <module>
class MyClass:
  File "duplicate.py", line 41, in MyClass
Collect_Pid_DB('192.142.123.142','root','password','mydatabasename')
   File "duplicate.py", line 35, in Collect_Pid_DB
print(json.dumps(db.collection_names(), indent=2))
   File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 787, in collection_names
nameOnly=True, **kws)]
   File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 722, in list_collections
read_pref) as (sock_info, slave_okay):
   File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
   File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 1135, in _socket_for_reads
server = topology.select_server(read_preference)
   File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 226, in select_server
address))
   File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 184, in select_servers
selector, server_timeout, address)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 200, in _select_servers_loop
self._error_message(selector))
  pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused

The following is the working code for the above question, In the above code the issue was that the local bind port along with the url was not parsed into a proper format, hence when authenticating the port couldnt be authenticated in order to connect. Hence in the above code mentioned in the question was not working.

The working code to connect to mongodb, when the ssh and mongo both have different credentials:

  def Collect_Pid_DB(hostname,user,password,accountid):
  server = SSHTunnelForwarder(
    (MONGO_HOST,22),
    ssh_username=MONGO_USER,
    ssh_password=MONGO_PASS,
    remote_bind_address=('127.0.0.1', 27017)
  )
  host_name="'primary_host_name': 'win-3auvcutkp34'"
  patch_name="'patch_name': '[\\& A-Za-z0-9+.,\\-]+'"

  server.start()
  client = pymongo.MongoClient(host='127.0.0.1',
      port=server.local_bind_port,
      username='admin',
      password='P@ssW0Rd')
  db = client[MONGO_DB]
  print (db)
  print(json.dumps(db.collection_names(), indent=2))

Hope the above answer would be helpful to someone, as i couldn't find one anywhere when i needed :P

Try to pip install ssh-pymongo and then:

from ssh_pymongo import MongoSession
session = MongoSession(MONGO_HOST)
db = session.connection['mydatabasename']

# perform your queries #

session.stop()

If you have more complex settings, check docs for cases, eg:

from ssh_pymongo import MongoSession

session = MongoSession(
    MONGO_HOST,
    port=22,
    user='ssh_username',
    password='ssh_password',
    uri='mongodb://admin:p@ssW0$3@127.0.0.1:27017')

db = session.connection['mydatabasename']

print(db.collection_names())

session.stop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM