2016-02-04 70 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