问题
I am connecting to a mongodb server on EC2. The mongo collections require authentication to connect.
I tried everything but I am getting the following error and can't seem to correct it.
from pymongo import MongoClient
mongo_username = "username"
mongo_password = "password"
ssh_user = "user"
ssh_address = "ec2-**********.amazonaws.com"
ssh_port = 22
private_key = "path/to/key/mykey.pem"
def connect_to_mongo():
try:
client = MongoClient("mongodb://"+mongo_username+":"+mongo_password+"@" + ssh_address, ssl = True, ssl_keyfile = private_key)
db = client.myDB
#Should 'admin' be there or 'myDB'? 'admin' at least get if(auth) passed, while 'myDB' doesn't
auth = client.admin.authenticate(mongo_username,mongo_password)
if(auth):
print "MongoDB connection successful"
col = db.myCollection.count()
else:
print "MongoDB authentication failure: Please check the username or password"
client.close()
except Exception as e:
print "MongoDB connection failure: Please check the connection details"
print e
if __name__ == "__main__":
connect_to_mongo()
Output :
MongoDB connection successful
MongoDB connection failure: Please check the connection details
SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590)
回答1:
EC2 will close 27017 port by default. Create the in-bound rule as described here and here.
回答2:
I tried all the options and finally this worked.
client = MongoClient("mongodb://" + ssh_address+":27017") # No private key passing
auth = client.myDB.authenticate(mongo_username,mongo_password) # Authenticate to myDB and not admin
db = client.myDB
So basically I don't need to pass a private key (which is required when doing ssh over to the EC2) since the port was already opened for all incoming IPs ( I guess this was an important fact that I should have known and posted in the question).
Also I was trying to authenticate via the admin DB
, which I shouldn't have done because I was given access to myDB
only.
来源:https://stackoverflow.com/questions/35206034/pymongo-unable-to-connect-to-mongodb-running-on-ec2