如何通过pymongo验证mongodb身份验证的用户名密码?

时间:2015-04-08 07:10:22

标签: python mongodb authentication

我正在引用http://api.mongodb.org/python/current/examples/authentication.html站点的身份验证机制示例。我创建了一个用户管理员并使用其凭据为我的“报告”数据库创建了一个用户。现在我需要使用用户名和密码通过pymongo访问相同的内容。我在python shell中尝试了以下命令。这是正确的方式,因为我的身份验证失败了。

from pymongo import MongoClient

client = MongoClient('localhost')

client.reporting.authenticate('reportsUser', '123456', mechanism='MONGODB-CR')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/pymongo/database.py", line 746, in authenticate
    self.connection._cache_credentials(self.name, credentials)
  File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 441, in _cache_credentials
    auth.authenticate(credentials, sock_info, self.__simple_command)
  File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 214, in authenticate
    auth_func(credentials[1:], sock_info, cmd_func)
  File "/usr/lib/python2.7/dist-packages/pymongo/auth.py", line 194, in _authenticate_mongo_cr
    cmd_func(sock_info, source, query)
  File "/usr/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 607, in __simple_command
    helpers._check_command_response(response, None, msg)
  File "/usr/lib/python2.7/dist-packages/pymongo/helpers.py", line 147, in _check_command_response
    raise OperationFailure(msg % errmsg, code)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'reportsUser'), ('nonce', u'f8158a24f1c61650'), ('key', u'14cea216c54b93bae20acd2e076bb785')]) failed: auth failed

3 个答案:

答案 0 :(得分:11)

作为一个FYI,您也可以使用URI字符串格式。伪代码如下所示:

pymongo.MongoClient(&#39; mongodb的://用户:密码@服务器:端口/&#39)

这是一个带有auth:

的简单连接代码块
import pymongo
conn = pymongo.MongoClient('mongodb://root:pass@localhost:27017/')
db = conn['database']
coll = db['collection']

此处有更多查询字符串选项:http://docs.mongodb.org/manual/reference/connection-string/

希望帮助=看起来你已经拥有它了。快乐的编码!!

答案 1 :(得分:1)

对我有用。

在这里您可以使用身份验证用户名和密码将mongodb连接到python。

import pymongo

DATABASE_NAME = "your_database_name"
DATABASE_HOST = "localhost"

DATABASE_USERNAME = "database_username"
DATABASE_PASSWORD = "database_password"

try:
    myclient = pymongo.MongoClient( DATABASE_HOST )
    myclient.test.authenticate( DATABASE_USERNAME , DATABASE_PASSWORD )
    mydb = myclient[DATABASE_NAME]

    print("[+] Database connected!")
except Exception as e:
    print("[+] Database connection error!")
    raise e

默认情况下,Mongodb使用27017端口

答案 2 :(得分:0)

只需在提供的解决方案中添加更多内容即可。

我一直在使用URI连接字符串,并以f字符串提供凭据,这有助于减少行数。需要注意的一件事是密码中的特殊字符,我们使用urllib包进行转换,如下所示。

import urllib.parse
from pymongo import MongoClient

host = "localhost"
port = 27017

user_name = "myuser"
pass_word = "Pass@123"  

db_name = "mydb"  # database name to authenticate

# if you are password has '@' then you might need to escape hence we are using "urllib.parse.quote_plus()" 
client = MongoClient(f'mongodb://{user_name}:{urllib.parse.quote_plus(pass_word)}@{host}:{port}/{db_name}')