Listing users for certain DB with PyMongo

Deadly 提交于 2019-12-12 16:33:22

问题


What I'm trying to acheive

I'm trying to fetch users for a certain database.

What I did so far

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.

Current code

#/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.

EDIT

Working solution

#/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']

Thank you all and @salmanwahed specifically!


回答1:


You can execute the usersInfo command to fetch the users data. Like:

db.command('usersInfo')

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'}]}


来源:https://stackoverflow.com/questions/38562042/listing-users-for-certain-db-with-pymongo

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