Skip to content Skip to sidebar Skip to footer

Pymongo Auth Failed In Python Script

I have installed mongodb and enabled auth. and its working find. I can connect it from remote notebook using robomongo application: Host: SERVER_IP PORT: 27017 DATEBASE: prod-db US

Solution 1:

Please try something like this:

client = MongoClient("mongodb://user_name:user_password@SERVER_IP/prod-db")
db = client['prod-db']

Solution 2:

If you've tried the above answers (from milos.ai) and you're still getting an error:

pymongo.errors.OperationFailure: Authentication failed.

There's a good chance you need to add ?authSource=admin to the end of your uri.

Here's a working solution that I'm using with MongoDB server version 4.2.6 and MongoDB shell version v3.6.9.

from pymongo import MongoClient

# Replace these with your server details
MONGO_HOST = "XX.XXX.XXX.XXX" 
MONGO_PORT = "27017"
MONGO_DB = "database"
MONGO_USER = "admin"
MONGO_PASS = "pass"

uri = "mongodb://{}:{}@{}:{}/{}?authSource=admin".format(MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB)
client = MongoClient(uri)

And if you're using command line, you'll get the same fix by adding the argument --authenticationDatabase admin

Solution 3:

For pymongo,

Try below for MongoDB 4:

Add authSource : This is the name of the database that has the collection with the user credentials.

Ex:

client = MongoClient(host=<<hostname>>,
                     port=<<port>>, 
                     username=<<user_name>>, 
                     password=<<password>>,
                    authSource="admin")
db_obj = client[db_name]

Edit 1: I have tried this on Mongo 3.x version as well. Working for that too.

Solution 4:

This worked for me ....

importpymongoclient= pymongo.MongoClient("mongodb://username:12%40password@ip:27017/sample_db",authSource="admin") 
db = client['sample_db']

Remember if you have special characters in your password (e.g. #,@) you will need to encode them (see %40) in the password. If you do not do authSource="admin" you will receive authentication errors. username - your mongodb username, ip - ip address as this assumes database is hosted on a remote server. sample_db is the database that you would like to access.

Post a Comment for "Pymongo Auth Failed In Python Script"