0

I'm trying to add a user to the mongodb, I have a shell script, but I'm trying to do this using python.

I have the code :

addadmusr="""{ createUser 'admin', pwd 'lint1234', roles ['userAdminAnyDatabase'] }"""

call('/opt/mongodb/bin/mongo -port primport --eval """db.getSiblingDB("""admin""").runCommand(addadmusr)"""',shell = True)

I'm trying to use subprocess calls to get this done, and I have a primport extracted by using the code:

primport = subprocess.check_output('/opt/mongodb/bin/mongo localhost27017 --eval "printjson(rs.isMaster())" | grep "primary"| cut -f1 -d, | cut -f3 -d : | grep -Eo """[0-9]{1,}"""' , shell = True)

when I'm trying to add the user, it says invalid port number "primport" and returns connection failed. My guess is the primport value that Im extracting is not parsing into the call statement that I'm using. I need to use the value extracted (primport) and add the user -admin to the db. Any python alternative also helps.

1 Answer 1

1

What is about pymongo for example?

You can try to use something like that:

from pymongo import MongoClient

client = MongoClient('localhost:27017')
client.testdb.add_user('newUserName', 'TestPassword', roles=[{'role':'readWrite','db':'testdb'}])
Sign up to request clarification or add additional context in comments.

4 Comments

I had that in my mind, but I cannot specify the localhost:27017 as it may differ each time the primary user changes. Hence, it has to extract the portnumber using the primport function call that I wrote.
I need something that uses the extracted port number by using the primport command, and then adds the admin user to the db on the primport - port.
If 'primport' after your command contains the correct value of port you can just create MongoClient using it. client = MongoClient('localhost:' + str(primport))
doesn't work. It still says port must be an integer, hence its not reading the value of primport @Bashalex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.