'Listing users for certain DB with PyMongo
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!
Solution 1:[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'}]}
Solution 2:[2]
Here is an answer that works without elevation (even though it looks at a portion of the admin collection). A db user can always see their own information.
#/usr/bin/python
from pymongo import MongoClient
import pprint
username = "myDBReader"
uri = 'mongodb://myDBReader:D1fficultP%[email protected]:27017/'
client = MongoClient(uri)
db = client.admin
listing = db.command({"usersInfo": username }
print(username, "has roles:")
pprint.pprint(db.command({"usersInfo": username })['users'][0]['roles'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | phyatt |