I have installed mongodb and enabled auth. and its working find. I can connect it from remote notebook using robomongo application:
JavaScript
x
7
1
Host: SERVER_IP
2
PORT: 27017
3
DATEBASE: prod-db
4
USERNAME: user_name
5
PASS: user_password
6
Auth Mechanism: MONGODB-CR
7
and We can connect from server shell locally using:
JavaScript
1
2
1
$ mongo prod-db -u user_name -p user_password
2
Everything works fine, but when we try it using pymongo api. authentications failed. below is the python code:
JavaScript
1
10
10
1
from pymongo import MongoClient
2
3
client = MongoClient()
4
client.prod_db.authenticate('user_name', 'user_password', mechanism='MONGODB-CR')
5
db = client.prod_db
6
result = db.users.find()
7
8
for document in result:
9
print(document)
10
Tools used:
JavaScript
1
8
1
python 2.7
2
pymongo versiob 3.3.1
3
MongoDB shell version: 2.6.10
4
$ mongod --version
5
db version v2.6.10
6
2016-10-31T16:34:59.868+0000 git version: nogitversion
7
2016-10-31T16:34:59.868+0000 OpenSSL version: OpenSSL 1.0.2g 1 Mar 2016
8
Error trace:
JavaScript
1
19
19
1
Traceback (most recent call last):
2
File "<stdin>", line 1, in <module>
3
File "/usr/local/lib/python2.7/dist-packages/pymongo/database.py", line 1018, in authenticate
4
connect=True)
5
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 444, in _cache_credentials
6
sock_info.authenticate(credentials)
7
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 343, in authenticate
8
auth.authenticate(credentials, self)
9
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 464, in authenticate
10
auth_func(credentials, sock_info)
11
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 439, in _authenticate_mongo_cr
12
sock_info.command(source, query)
13
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 239, in command
14
read_concern)
15
File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 102, in command
16
helpers._check_command_response(response_doc, None, allowable_errors)
17
File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 205, in _check_command_response
18
raise OperationFailure(msg % errmsg, code, response)
19
Solution: problem was with database name, following code works fine:
JavaScript
1
9
1
from pymongo import MongoClient
2
3
client = MongoClient('mongodb://user_name:user_password@localhost:27017/prod-db')
4
db = client['prod-db']
5
6
result = db.users.find()
7
for document in result:
8
print document
9
Advertisement
Answer
Please try something like this:
JavaScript
1
3
1
client = MongoClient("mongodb://user_name:user_password@SERVER_IP/prod-db")
2
db = client['prod-db']
3