Mongolab refuses connections - python

I'm working on a Python program that submits data to Mongolab, and I'm running across a strange exception:
mongoengine.connection.ConnectionError: Cannot connect to database mongodb://<user>:
<password>#ds035617.mongolab.com:35617/<mydatabase>:
could not connect to localhost:27017: [Errno 10061] No connection could be made
because the target machine actively refused it
This is the offending code:
from mongoengine import *
connect('tablename', "mongodb://<user>:<password>#ds035617.mongolab.com:35617/<mydatabase>")
Anyone have any ideas as to what is wrong?

A few things I would check:
(1) Why does the error message say the system is trying to connect to localhost:27017...?
(2) Why does your mongodb URI have "user" and "password" where the real username and password should be?
My guess is the problem is (2) unless you are obscuring the username and password for the sake of this posting.
If you still have trouble email support#mongolab.com and we can dig deeper with you.
-will

I generally think it's poor form to answer one's own question, but I figured out the (rather simple) answer and wanted to document it to make sure others would have it as well.
The issue was not specifying host= as a keyword argument in the connect function. The correct function call would be:
from mongoengine import *
connect('tablename', host="mongodb://<user>:<password>#ds035617.mongolab.com:35617/<mydatabase>")

It looks like you're using a MongoDB URI to connect, but the driver is interpreting the string as the database name and trying to connect to the default localhost:27017. According to the mongoengine docs you want to pass that URI in as the host parameter:
Uri style connections are also supported as long as you include the database name - just supply the uri as the host to connect():
connect('project1', host='mongodb://localhost/database_name')

Related

Problems connecting to MariaDB using the Python mysql.connector

I am trying to use Python 3.7 to connect to various MySQL and MariaDB databases using ver 8.0.18 of the mysql.connector (installed via pip as the mysql-connector-python package).
In this particular instance, I am trying to connect to a MariaDB 5.5.52 instance, but seem to be having the same problem on other systems.
If I attempt to connect thus:
cnx = mysql.connector.connect(user=c['user'], password=c['password'], host=c['host'], database=c['database'])
I get
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user '<user name>'#'<ip address>' (using password: YES)
The mysterious thing is that I can use a client application (JetBrains DataGrip) to connect from the same PC to the databases in question without any problems, so I am confident that the credentials are valid and there aren't any network or similar problems preventing the connection (i.e. port 3306 is open).
The only common factor I can find seems to be the mysql.connector. I've checked the manual and it looks like the syntax is correct.
UPDATE Following #makozaki's advice to use a different connector (pymysql) the code works. So it would definitely appear to be the mysql.connector that's the problem. I might try rolling it back to a previous version to see if that fixes it (unless anyone out there knows of a workaround).
I was able to fix this same error message for mysql.connector by adding in the additional parameter 'tls_versions':
cnx = mysql.connector.connect(user=c['user'], password=c['password'], host=c['host'], database=c['database'], 'tls_versions'=['TLSv1.1', 'TLSv1.2'])
This works because, as of the update 8.0.18, you can now specify the TLS version if it doesn't match the version of your database.
So far as I can tell, this turned out to be something to do with character encoding. The password I was using had some strange characters in it, including a British pound sign and an accented foreign (European) character.
For reasons I don't yet understand, the DataGrip client passed these without any problem, yet the mysql.connector somehow nobbled them.I suspect that this is something to do with encoding, although everything is set (or defaults to) utf-8.
I've changed the password(s) to ones encoded in base64 and the problem appears to have been solved, although I am frustrated that I haven't got to the bottom of why it occurred in the first place.

connection times out when trying to connect to mongodb atlas with python

I'm trying to connect to my mongodb atlas cluster but i keep getting timed out as soon as i try to do something with my db.
The db i use was created in mongoshell and also the collection i checked their existence in mongodb compass
ERROR
pymongo.errors.ServerSelectionTimeoutError: projekt-shard-00-01-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-00-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-02-rk7ft.mongodb.net:27017: timed out
CODE
client = MongoClient("""mongodb://user:password#projekt-shard-00-00-rk7ft.mongodb.net:27017,projekt-shard-00-01-rk7ft.mongodb.net:27017,projekt-shard-00-02-rk7ft.mongodb.net:27017/projekt?ssl=true&replicaSet=projekt-shard-0&authSource=admin""")
client.projekt.category.insert_one({type : "pants"}).inserted_id
SO the problem is with your IP Address,
GO to the Network Access panel in MongoDB Atlas
In the IP Access List section, you will find all your IP addresses
Click on edit tab for the current IP address you are using
There change the setting to ALLOW ACCESS FROM ANYWHERE
That's it, it will work!
I was having this issue for hours. It's odd that it seems to be a connection issue, but it's not throwing a bad auth or anything, just this timeout. The client object seems to be actually created (I could print its properties). I kept playing around and this somehow worked:
In the MongoDB GUI, navigate to Database Access
Add a test user with the same read/write permissions to everything as the initial user created upon setup
Change the connection string in Python to the new user's username + password
Run the code
For me it finally connected and inserted successfully. After this, the original user's connection string now worked, so I deleted the test user.
I can't identify the root cause of this issue, but it seems like the Database Users table just needed some kind of action performed on it to refresh and begin accepting user connections.
Anybody looking for a solution, if you are trying to access Atlas instance from out in the wild, check the "Network Access" tab, as i think you have to whitelist either all, or specific IP addresses

Is there a way to set secure_auth to false in MySQLdb.connect in Python 2.7.5?

I am attempting to run a script written in Python 2.7.5 (not using Django). When it tries to connect to a remote mysql server with the MySQLdb.connect() method it throws the following error:
_mysql_exceptions.OperationalError: (2049, "Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled)")
I have done reading about this issue:
Django/MySQL-python - Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled)
mysql error 2049 connection using old (pre-4-1-1) authentication from mac
Is there a way to set a parameter in the MySQLdb.connect() method to set secure_auth to false? Without having to change any passwords or running the command from the cmd line. I have looked at the official docs and there does not appear to be anything in there.
I have tried adding secure_auth=False to the parameters but throws an error (shown in the code below).
Python:
def get_cursor():
global _cursor
if _cursor is None:
try:
db = MySQLdb.connect(user=_usr, passwd=_pw, host='external.website.com', port=3306, db=_usr, charset="utf8")
# tried this but it doesnt work (as expect but tried anyway) which throws this error
# TypeError: 'secure_auth' is an invalid keyword argument for this function
# db = MySQLdb.connect(user=_usr, passwd=_pw, host='external.website.com', port=3306, db=_usr, charset="utf8", secure_auth=false)
_cursor = db.cursor()
except MySQLdb.OperationalError:
print "error connecting"
raise
return _cursor
I spent an inordinate amount of time working through the MySQLdb source code and determined that this simply cannot be done without patching the MySQLdb's C wrapping code. Theoretically, you should be able to pass the SECURE_CONNECTION flag to specify that do not want to use the insecure old passwords:
MySQLdb.connect(..., client_flags=MySQLdb.constant.CLIENT.SECURE_CONNECTION)
But the MySQLdb code never actually checks that flag, and never configures the secure_connection option when calling the MySQL connection code, so it always defaults to requiring new-style passwords.
Possible fixes include:
Patch the MySQLdb code
Use an old version of the MySQL client libraries
Update the passwords on the MySQL server
Create a single new user with a new-style password
Sorry I don't have a better answer. I just ran into this problem myself!
I know Moses answer as been validated but I wanted to offer my work around based on what he suggested.
I had previously installed mysql_python for my python and had the brew version of mysql installed.
I deteleted all of that.
I look for a way to install MySQLdb by looking for it last stable version with the source.
I compiled them (followed the isntructions here), installed them and then I looked for a stable version of MySQL client (MySQL website is the best place for that) and install the 5.5 version which was perfectly fitting my requirements.
I made mysql to launch itself automatically and then restarted my computer (but you can just restart apache) and check that all path were correct and the right includes are in the right places (you can check that against the link above).
And now it all works fine!
Hope it helps.
SSL is a separate paramter that you can set in the connection paramter...Here is a note from the source code...Try checking mysql_ssl_set() documentation.
ssl
dictionary or mapping, contains SSL connection parameters;
see the MySQL documentation for more details
(mysql_ssl_set()). If this is set, and the client does not
support SSL, NotSupportedError will be raised.
This document talks about all the secure parameters - http://dev.mysql.com/doc/refman/5.0/en/mysql-ssl-set.html...
I don't see anything to disable secure auth in glance..

How can I access a clearquest oracle database from python?

At work we have to use ClearQuest. Recently I have had the necessity of making some "complicated" queries and I have found that to be very difficult with the CQ query editor.
I have think about using python to connect directly to the database and make my own queries so I can run the script automagically, but I am unable to connect to the database.
I have follow the tip of this answer https://stackoverflow.com/a/1870849/156459
But without any success.
I have compared the cx_Oracle.makedsn return value with the one sent by the CQ client for windows and both are equal.
The error I get is "ORA-01017: Invalid username/password; logon denied" . I have double checked the user and password and are correct.
I have captured the TSN packets between the oracle server and my computer while running my script and I have seen something rare to me: My computer ask for a connection and the server answer with Accept ...
Any help would be ( very ) welcomed.
Thanks for your time!
Check whether your password contains any characters that require escaping.

Connect to SQL Server instance using pymssql

I'm attempting to connect to a SQL Server instance from a Windows box using pymssql (version 2.0.0b1-dev-20111019 with Python 2.7.1). I've tried the most basic approach from the console:
import pymssql
c = pymssql.connect(host = r'servername\instance',
user = 'username',
password = 'userpassword')
In response to this, I get the very helpful error: InterfaceError: Connection to the database failed for an unknown reason.
I am reasonably confident that the connection information is correct, as it works when I use adodbapi, with the following commands:
import adodbapi
c = adodbapi.connect(r'Provider=sqloledb;Data Source=servername\instance;User ID=username;password=userpassword;'
c.close
I've tried adding the port number to the host parameter, with the same result. Does anyone have a suggestion on how to go about resolving this issue?
Incidentally, I've read the responses at "Unable to connect to SQL Server via pymssql". The OP eventually resolved his issue by correctly configuring FreeTDS, which, from what I can tell, is not used by pymssql on Windows.
Based on #cha0site's recommendation, I have tried using just the hostname, rather than the hostname and instance. This resulted in the same error, but it seemed to take longer to generate the error (though the traceback still indicates the same line). The reason I have been specifying the instance is that I was not able to connect using SSMS unless I specified the instance, so I assumed that it would be necessary for other connections.
I've now also tried pymssql.connect(host='servername', user='username', password='userpassword', database='instance') with the same result (based on #Sid's comment). Based on the pymssql documentation, I believe the database parameter is used to specify the initial database that the user is to be connected to, rather than the instance.
Just to clarify, "instance" is the name provided during installation of SQL Server, not a database within that installation. It occurs to me that it's possible that pymssql does not support this notation, so I will look into re-configuring the SQL Server instance so that it is not required.
I've now re-installed SQL Server as a default instance, rather than a named instance, which allows me to connect without specifying the instance name. adodbapi still works (without /instance), but pymssql still returns the same error. I've also removed and re-installed pymssql from a freshly downloaded archive (still the same version).
Check your freetds.conf file and see if you have set the port 1219., then check again the connexion:
DB = pymssql.connect(host='DB',user='youruser',password='yourpwd',database='yourDBname')
Edit: example of my freetds.conf file Python:
host = 'IP'
port = 1219
To specify host=servername\instance or server=servername\instance, the SQL Server Browser service must be on the SQL Server machine.

Categories