1

尝试从 python 脚本启动 mongodb 副本集,并遇到身份验证错误。

from pymongo import MongoClient

ip = 'zzz.zz.zzz.zz'
port = 27017
replica_set = 'yomama'

config = {
  '_id': replica_set,
  'members': [
    {'host': 'xxx.xx.xxx.xx',
     '_id': 0,
     'arbiterOnly': False},
    {'host': 'yyy.yy.yyy.yy',
     '_id': 1,
     'arbiterOnly': False},
    {'host': 'zzz.zz.zzz.zz',
     '_id': 2,
     'arbiterOnly': False},
  ],
}

connection = MongoClient(ip, port)
connection.admin.command('replSetInitiate', config)

运行此脚本会导致:

pymongo.errors.OperationFailure: command SON([('replSetInitiate', {'_id': 'yomama', 'members': [{'host': 'xxx.xx.xxx.xx', '_id': 0, 'arbiterOnly': False}, {'host': 'yyy.yy.yyy.yy', '_id': 1, 'arbiterOnly': False}, {'host': 'zzz.zz.zzz.zz', '_id': 2, 'arbiterOnly': False}]})])
failed: unauthorized

数据库上没有设置身份验证,并且从 mongo shell 运行相同的东西可以正常工作:

db.runCommand({replSetInitiate:{'_id': 'yomama', 'members': [{'host': 'xxx.xx.xxx.xx', '_id': 0, 'arbiterOnly': false}, {'host': 'yyy.yy.yyy.yy', '_id': 1, 'arbiterOnly': false}, {'host': 'zzz.zz.zzz.zz', '_id': 2, 'arbiterOnly': false}]}})
{
    "info" : "Config now saved locally.  Should come online in about a minute.",
    "ok" : 1
}

在用 pymongo 做同样的事情时为什么会出现这个错误?

4

1 回答 1

1

弄清楚了。发生这种情况是因为通过在初始化 MongoClient( connection = MongoClient(ip, port)) 时指定 ip 和端口,客户端没有使用localhost 异常绕过身份验证。使用 localhost 进行初始化可以解决问题,例如connection = MongoClient().

于 2013-10-21T23:24:01.313 回答