2016-02-04 67 views
1

我正在连接到EC2上的mongodb服务器。 mongo集合需要认证才能连接。pymongo - 无法连接到在EC2上运行的mongodb

我尝试了一切,但我得到以下错误,似乎无法纠正它。

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() 

输出:

MongoDB connection successful 
MongoDB connection failure: Please check the connection details 
SSL handshake failed: EOF occurred in violation of protocol (_ssl.c:590) 

回答

1

我试过所有的选项,最后这个工作。

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 

所以基本上我并不需要通过一个私有密钥(这是做的SSH到EC2时需要),因为该端口已打开所有传入的IP地址(我想这是一个重要的事实:我应该知道并在问题中发布)。

另外我试图通过admin DB进行身份验证,我不应该这样做,因为我只能访问myDB

2

EC2将默认关闭端口27017。如herehere所述创建入境规则。

+0

我的合作开发者之一是通过Java接口访问mongodb,他能够做到这一点。 你还认为这可能是原因吗? – Shivendra

+0

这个Java实例是否在同一个VPC下运行?你是否从EC2的VPC之外访问? – user3

+0

我不知道第一个问题的答案,但我从家庭网络访问EC2。 – Shivendra