connecting to MongoDB with authentication using pymongo 2.7 - python

[![enter image description here][1]][1]Hi im trying to connect to mongoDB via a python code
client = MongoClient("mongodb://username:mypassword#localhost/mydatabase-1")
db = client['mydatabase-1']
and or
connection = MongoClient('localhost', 27017)
db = connection['mydatabase-1']
db.authenticate('username', 'mypassword')
uri = "mongodb://username:mypassword#localhost.com/mydatabase-1"
client = MongoClient(uri)
but i keep getting the same error without fail
ConfigurationError: command SON([('authenticate', 1), ('user', u'CEI'), ('nonce', u'950483ef6634f14'), ('key', u'76f0102585a7571d96dace50d7aca5a6')]) failed: auth failed
I am using pymongo 2.7 with python 2.7. I guess this means I'm working with mechanism='MONGODB-CR'
I am able to use these credentials to connect to the MongoDB database using MongoChef (a GUI) and it works perfectly.
I have tried to update the pymongo, and it is at version 2.7 i cant use a higher version because I have python 2.7. I cant find any more solutions online. From what i read on the mongoDB website it should work with mechanism='MONGODB-CR' but not for mechanism='SCRAM-SHA-1' due to being v2.7
have mongodb running using
E:\MongoDB\bin\mongod.exe --auth --port 27017 --dbpath E:\Data\db
and set up the user using
use admin
db.createUser(
{
user: "username",
pwd: "mypassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
UPDATE!!!!!!!!!!!!!!!!!!!!!!!!!!
managed to get pymongo 3.4 working using pip install. But still getting this message
runfile('C:/Users/mdb_emr_syn/untitled0.py', wdir='C:/Users/mdb_emr_syn')
Traceback (most recent call last):
File "<ipython-input-19-2ecc66a5cadd>", line 1, in <module>
runfile('C:/Users/mdb_emr_syn/untitled0.py', wdir='C:/Users/mdb_emr_syn')
File "C:\Program Files\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Program Files\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/mdb_emr_syn/untitled0.py", line 11, in <module>
connection.yo.authenticate("CEI","Syn12345.")
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\database.py", line 1048, in authenticate
connect=True)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\mongo_client.py", line 505, in _cache_credentials
sock_info.authenticate(credentials)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\pool.py", line 523, in authenticate
auth.authenticate(credentials, self)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\auth.py", line 470, in authenticate
auth_func(credentials, sock_info)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\auth.py", line 450, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\auth.py", line 201, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\pool.py", line 419, in command
collation=collation)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\network.py", line 116, in command
parse_write_concern_error=parse_write_concern_error)
File "C:\Program Files\Anaconda2\lib\site-packages\pymongo\helpers.py", line 210, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
OperationFailure: Authentication failed.
any ideas as to why????? thanks guys

I am totally new in MongoDB, and I've just been through this.
Hope this help for others like me.
# version info
mongodb : 3.4.7
python : 2.7
pymongo : 3.5.1
In my case, the reason I got Authentication failed is that I didn't have any user created in the db which I wanted to access.
I can check user with db.getUsers() in mongodb shell.
> use mydatabase-1
switched to db mydatabase-1
> db.getUsers()
[ ]
And it's empty.
So what I learned was :
After created a db and put some docs into collection, should also createUser() for that db, than pymongo can access.
In mongodb shell, continue with the example from original post.
db name: mydatabase-1
> use mydatabase-1
switched to db mydatabase-1
> db.createUser(
... {
... user: "username",
... pwd: "myPWD",
... roles: [ { role: "readWrite" } ]
... }
...)
Successfully added user: { "user" : "username", "roles" : [ "readWrite" ] }
And than, In python
To access your db, do this...
client = MongoClient("mongodb://username:myPWD#localhost:port/mydatabase-1")
db = client['mydatabase-1']
Or this
connection = MongoClient('localhost', port)
db = connection['mydatabase-1']
db.authenticate('username', 'myPWD')
And than, print doc from collection my_collection_name
cursor = db.my_collection_name.find()
for doc in cursor:
print doc
This should solved Authentication failed.

Upgrade PyMongo. Just because you're using Python 2.7 doesn't mean you have to use PyMongo 2.7. PyMongo 3.4.0 is the latest release, and it works with all versions of Python.

Related

pymongo.errors.ServerSelectionTimeoutError:localhost:27017:[WinError 10061] No connection could be made because the target machine actively refused it

I am following the Python tutorial from W3Schools. I just started the MongoDB chapter. I installed MongoDB and checked it with:
import pymongo
without getting an error.
But as soon as I enter the following code:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
print(x.inserted_id)
I get these messages and an error message at the bottom in cmd:
cd C:\Users\xxx\myname
python index.py
Output:
Traceback (most recent call last):
File "index.py", line 8, in <module>
x = mycol.insert_one(mydict)
File "C:\Users\path...\pymongo\collection.py", line 695, in insert_one
self._insert(document,
File "C:\Users\path...\pymongo\collection.py", line 610, in _insert
return self._insert_one(
File "C:\Users\path...\pymongo\collection.py", line 599, in _insert_one
self.__database.client._retryable_write(
File "C:\Users\path...\pymongo\mongo_client.py", line 1490, in _retryable_write
with self._tmp_session(session) as s:
File "C:\Program Files\WindowsApps\path...\lib\contextlib.py", line 113, in __enter__
return next(self.gen)
File "C:\Users\path...\pymongo\mongo_client.py", line 1823, in _tmp_session
s = self._ensure_session(session)
File "C:\Users\path...\pymongo\mongo_client.py", line 1810, in _ensure_session
return self.__start_session(True, causal_consistency=False)
File "C:\Users\path...\pymongo\mongo_client.py", line 1763, in __start_session
server_session = self._get_server_session()
File "C:\Users\path...\pymongo\mongo_client.py", line 1796, in _get_server_session
return self._topology.get_server_session()
File "C:\Users\path...\pymongo\topology.py", line 482, in get_server_session
self._select_servers_loop(
File "C:\Users\path...\pymongo\topology.py", line 208, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost: 27017: [WinError 10061] Could not connect because target computer actively refused connection
I also tried too disabling firewall temporarily, but the error kept coming up.
I used:
"python 3.8.2
, mongoDB 4.2.5.0
, pymongo 3.10.1
, windows 10 home"
What is going wrong?
There is nothing wrong with your code.
If you have disabled your firewall, the most likely reason is that the MongoDB service is not installed or running. On Windows, press the Windows key and type services to open the services application. Check the service MongoDB Server is listed and has a Running status.
You can test local connectivity by opening your favourite Windows terminal or PowerShell and typing mongo. If it is working you should see:
PS> mongo
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("1b5499b8-166a-4de6-a8c9-643499f04e66") }
MongoDB server version: 4.2.3
Try running this command in CLI:
mongod
If you see any error, then watch the
video How to Install MongoDB on Windows 10. This video was helpful.
I was trying to connect from Django. I am using Python 3.7 and earlier tried with the URI string provided for Python 3.6+, but it didn't work in PyCharm or Jupyter. But later I chose the URI string for Python version 3.4+ and it worked in Jupyter Notebook, but I got an issue connecting from the Django project.
So to solve this I installed MongoDB application from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.11-signed.msi which started MongoDB services on my machine. And without changing any previous code I am able to connect. Below is my code to connect to MongoDB from Django application:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': <DBname>,
'HOST': "mongodb://<username>:<password>#cluster0-shard-00-00.pifkd.mongodb.net:27017,cluster0-shard-00-01.pifkd.mongodb.net:27017,cluster0-shard-00-02.pifkd.mongodb.net:27017/<DBname>?ssl=true&replicaSet=atlas-79xyw7-shard-0&authSource=admin&retryWrites=true&w=majority",
'USER': <username>,
'PASSWORD': <password>,
}
}
In my case I put the wrong port in
client = pymongo.MongoClient('mongodb://localhost:27017/')
You can check which port MongoDB server is listening to (in Windows) via Task Manager → Performance → Open Resource Monitor → Network → Listening Ports
And search for mongod.exe.
Your device might have disabled the MongoDB services.
Search services in the search bar and find MongoDB services in the list. First right and then click on Properties and change from either Disable to Automatic or Manual to Automatic.
In case you want to keep it Manual, click on start after right-clicking the MongoDB services option in the list.

Authentication failed to connect to mongodb using pymongo

We have written a piece of code in python script using pymongo that connects to mongodb.
username = 'abc'
password = 'xxxxxx'
server = 'dns name of that server'
port = 27017
In program, the code looks like:
import pymongo
from pymongo import MongoClient
client = MongoClient(url, serverSelectionTimeoutMS=300)
database = client.database_name
data_insert = database.collection_name.insert_one({'id': 1, 'name': xyz})
When I tried to do these operations, it raises an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
self.__collation))
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
exhaust)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 99, in send_message_with_response
with self.get_socket(all_credentials, exhaust) as sock_info:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 168, in get_socket
with self.pool.get_socket(all_credentials, checkout) as sock_info:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 792, in get_socket
sock_info.check_auth(all_credentials)
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 512, in check_auth
auth.authenticate(credentials, self)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 470, in authenticate
auth_func(credentials, sock_info)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 450, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 201, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 419, in command
collation=collation)
File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 116, in command
parse_write_concern_error=parse_write_concern_error)
File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 210, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.
In MongoDB, while performing queries we are getting the responses normally, without raising any errors.
Because the other answers to your question didn't work for me, I'm going to copy and paste my answer from a similar question.
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
Well, I have been stuck with the same error for almost 3-4 hours. I came across solution with the following steps:
from your shell connect to MongoDB by typing: mongo
afterwards, create a database: use test_database
Now create a user with the following command with readWrite and dbAdmin privileges.
db.createUser(
{
user: "test_user",
pwd: "testing12345",
roles: [ "readWrite", "dbAdmin" ]
}
);
This will prompt Successfully added user: { "user" : "test_user", "roles" : [ "readWrite", "dbAdmin" ] }
you can check by typing: show users.
It will also show you DB name you created before in the json.
now you should be able to insert data to your database:
client = MongoClient("mongodb://test_user:myuser123#localhost:27017/test_database")
db = client.test_database
data = {"initial_test":"testing"}
db["my_collection"].insert_one(data).inserted_id
I ran into this error, and my problem was with the password.
I had what I believe to be a special character in the Master account. Changing the password to be only alphanumeric fixed it for me.
Code snippet
client = pymongo.MongoClient(
'mongodb://username:alphaNumericPassword#localhost:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'
)
# Specify the database to be used
db = client['prod-db']

Cannot connect to remote MongoDB server using flask-mongoengine

Trying to connect to a MongoDB cluster hosted on a remote server using flask-mongoengine but the following error is thrown:
File "test.py", line 9, in <module>
inserted = Something(some='whatever').save()
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/mongoengine/document.py", line 323, in save
object_id = collection.save(doc, **write_concern)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/collection.py", line 2186, in save
with self._socket_for_writes() as sock_info:
File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__
return next(self.gen)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/mongo_client.py", line 762, in _get_socket
server = self._get_topology().select_server(selector)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 210, in select_server
address))
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 186, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: admin:27017: [Errno -2] Name or service not known
Below is the code I am using:
# test.py
from my_app_module import app
from flask_mongoengine import MongoEngine
db = MongoEngine(app)
class Something(db.Document):
some = db.StringField()
inserted = Something(some='whatever').save()
print(inserted)
for obj in Something.objects:
print(obj)
My config.py file contains:
# config.py
MONGODB_SETTINGS = {
'db': 'testdb',
'host': 'mongodb://<my_username>:<my_password>#<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin',
}
But I can connect using pymongo using the following code.
from pymongo import MongoClient
uri = 'mongodb://<my_username>:<my_password>#<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin'
client = MongoClient(uri)
db = client['testdb']
db.test_collection.insert({'some_key': 'some_value'})
for col in db.test_collection.find():
print(col)
# Prints {'some_key': 'some_value', '_id': ObjectId('57ec35d9312f911329e54d5e')}
I tried to find a solution but nobody seems to have come across the problem before. I am using MongoDB's Atlas solution to host the MongoDB cluster.
I figured out that it's a bug in flask-mongoengine version 0.8 and has beed reported here.

Python mysql connector access denied error

I've read everything possible and I just can't connect to my mysql server. Here is my code. very simple. (I used xxx to hide all the private info. everything else is the way i got it.
import mysql.connector
conn = mysql.connector.connect(user='xxxx',password='xxxxx',host='xxxx',db='xxx',port=3306)
The login info is definitely correct. I tried it in a mysql client and it connected just fine. The MySQL server is hosted on dreamhost. I set the allowable IPs for the db user to wildcard %.%.%.% so anyone could connect.I don't know what else could possibly be wrong. When I try to connect in python i get:
C:\Python33\python.exe D:/Dropbox/python/v2/test.py
Traceback (most recent call last):
File "D:/Dropbox/python/v2/test.py", line 3, in <module>
conn = mysql.connector.connect(user='xxx',password='xxx',host='xxx',db='xxx',port=3306)
File "C:\Python33\lib\site-packages\mysql\connector\__init__.py", line 101, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 117, in __init__
self.connect(**kwargs)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 383, in connect
self._open_connection()
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 350, in _open_connection
self._ssl)
File "C:\Python33\lib\site-packages\mysql\connector\connection.py", line 176, in _do_auth
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1044 (42000): Access denied for user 'xxx'#'%.%.%.%' to database 'xxx'
Any help would be greatly appreciated.
You will have to GRANT permissions to the user.
Something like:
GRANT ALL PRIVILEGES ON *.* TO 'user2'#'localhost' IDENTIFIED BY PASSWORD 'xxxxx'

issues with OpenERP installation

I am installing openerp at my local server, I have installed it and its dependences but after finishing its installation when i run server 'openerp-server' and acces it using 0.0.0.0:8069/. I got the following error
OpenERP Server Error
Client Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/http.py", line 195, in dispatch
response["result"] = method(self, **self.params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/controllers/main.py", line 709, in get_list
return db_list(req)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/controllers/main.py", line 88, in db_list
dbs = proxy.list()
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 31, in proxy_method
result = self.session.send(self.service_name, method, *args)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 104, in send
raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)
Server Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 90, in send
return openerp.netsvc.dispatch_rpc(service_name, method, args)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/netsvc.py", line 295, in dispatch_rpc
result = ExportService.getService(service_name).dispatch(method, params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/service/web_services.py", line 122, in dispatch
return fn(*params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/service/web_services.py", line 351, in exp_list
cr = db.cursor()
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 477, in cursor
return Cursor(self._pool, self.dbname, serialized=serialized)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 183, in __init__
self._cnx = pool.borrow(dsn(dbname))
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 378, in _locked
return fun(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 433, in borrow
result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
OperationalError: FATAL: role "ghrix" does not exist
I haven't recognize this error.
One more thing , I haven't edit OpenERP server configuration file . And if I have to edit this file then what are those changes.
Thanks.
This error indicates that OpenERP is trying to connect to the PostgreSQL database server using the "ghrix" user, which does not exist. This is probably the user under which you are starting the server.
If you have created a special database user for OpenERP you need to specify it on the command-line using --db_user=DB_USER (and in that case you probably also need --db_host=localhost and --db-password=YOUR_PASSWORD).
If you haven't created any database user yet, the easiest solution is probably to create one named ghrix, e.g.:
$ sudo su - postgres
$ createuser -s ghrix # -s to make a super-user that can create DBs
Note: Use ./openerp-server --help to see all possible startup parameters for the OpenERP server. You can also put the command-line options in a config file: just execute
$ ./openerp-server -s
and then edit the sample config file that is created in $HOME/.openerp_serverrc
Even though the question has been answered, the following is a concise tutorial on installing a production grade OpenERP Server, that also explains how to set up the database, manage access rights and configure your OpenERP installation:
http://www.theopensourcerer.com/2012/02/how-to-install-openerp-6-1-on-ubuntu-10-04-lts/
you should check two case
First case:
$ sudo su - postgres $ createuser -s ghrix
second case
fill the db user and db password in
/odoo/debian/odoo.conf
run odoo with this parameter
./odoo-bin -c /opt/odoo/debian/odoo.conf
If not resolved comment below i try to resolve it

Categories

Resources