pymongo auth failed in python script

Please try something like this:

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

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


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.