add user to mongodb via python

流过昼夜 提交于 2019-12-22 04:39:22

问题


I want to be able to add users to MongoDB so that we can automate MongoDB installs with authentication already baked in. I can successfully add users using pymongo that are read only or are dbOwner by doing this:

from pymongo import MongoClient

client = MongoClient('localhost:27017')   
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', True)

but when I do this following code block to specify roles, it fails:

from pymongo import MongoClient

client = MongoClient('localhost:27017')
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', False, 'readWrite')

with the error:

line 10, in <module>
    client.admin.add_user('newTestUser', 'Test123', False, 'readWrite')
TypeError: add_user() takes at most 4 arguments (5 given)

In the docs it implies that you are able to have optional fields for the user document such as other roles. Has anyone been able to set these correctly? Namely, I want to have readWrite service accounts that can add data to collections but don't have full dbOwner privileges.


回答1:


Here is the workaround:

client.testdb.add_user('newTestUser', 'Test123', roles=[{'role':'readWrite','db':'testdb'}])

Note: as you're going to set "roles", should leave the 3rd argument (read_only) empty.



来源:https://stackoverflow.com/questions/24686749/add-user-to-mongodb-via-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!