使用PyMongo列出某些数据库的用户 [英] Listing users for certain DB with PyMongo
问题描述
我正在尝试为某个数据库获取用户.
I'm trying to fetch users for a certain database.
我能够找到列出数据库或创建用户的功能,但没有找到列出用户的功能,我考虑过调用任意命令(例如show users
),但是我找到了实现它的任何方法.
I was able to find function to list the databases or create users but none for listing the users, I thought about invoking an arbitrary command such as show users
but I could find any way to do it.
#/usr/bin/python
from pymongo import MongoClient
client = MongoClient("localhost",27017)
db = client.this_mongo
试错
我可以看到数据库名称并打印它们,但没有其他内容:
Trial and error
I can see the DB names and print them but nothing further:
db_names = client.database_names()
#users = db.command("show users")
for document in db_names:
print(document)
#cursor = db.add_user('TestUser','Test123',roles={'role':'read'})
如果只有一个可以获取用户光标的函数,以便我可以对其进行迭代,那么它会很棒.
If there was only a function that could fetch the users cursor so I can iterate over it it would be great.
#/usr/bin/python
from pymongo import MongoClient
client = MongoClient("localhost",27017)
db = client.this_mongo
# This is the line I added with the help of @salmanwahed
listing = db.command('usersInfo')
for document in listing['users']:
print document['user'] +" "+ document['roles'][0]['role']
谢谢大家,特别感谢@salmanwahed!
Thank you all and @salmanwahed specifically!
推荐答案
您可以执行 usersInfo
命令来获取用户数据.喜欢:
You can execute the usersInfo
command to fetch the users data. Like:
db.command('usersInfo')
它将返回如下结果:(我已经创建了testingdb
用于测试)
It will return you a result like this: (I had created the testingdb
for testing)
{u'ok': 1.0,
u'users': [{u'_id': u'testingdb.TestUser',
u'db': u'testingdb',
u'roles': [{u'db': u'testingdb', u'role': u'read'}],
u'user': u'TestUser'}]}
这篇关于使用PyMongo列出某些数据库的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!