pymongo auth failed in python script

后端 未结 4 2052
不知归路
不知归路 2020-12-31 00:44

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: 270         


        
相关标签:
4条回答
  • 2020-12-31 00:51

    This worked for me ....

    import pymongo
    
    client = 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.

    0 讨论(0)
  • 2020-12-31 00:52

    Please try something like this:

    client = MongoClient("mongodb://user_name:user_password@SERVER_IP/prod-db")
    db = client['prod-db']
    
    0 讨论(0)
  • 2020-12-31 00:56

    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.

    0 讨论(0)
  • 2020-12-31 01:11

    If you've tried the above answers 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)
    

    Similar fix for command line is adding --authenticationDatabase admin

    0 讨论(0)
提交回复
热议问题