Connecting to Atlas MongoDb using pymongo - ServerSelectionTimeoutError - python

I'm having trouble connecting to a db I set up in Atlas MongoDB.
I have already read multiple other questions but no answer made my connection work.
I want to point out that I am trying to access it behind a company's proxy (if that has anything to do with it).
My code is this and fails only on the last line where I try to count the documents:
from pymongo import MongoClient
client = MongoClient(
"mongodb+srv://name:pass#iliastrialcluster-1tl2y.azure.mongodb.net/test?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE"
)
db = client.get_database('sample_airbnb')
print(db)
listings_and_reviews = db.listingAndReviews
print(listings_and_reviews)
listings_and_reviews.count_documents({})
The error I get is:
Traceback (most recent call last):
File "C:~/mongo_connection1.py", line 11, in <module>
listings_and_reviews.count_documents({})
File "C:~\lib\site-packages\pymongo\collection.py", line 1721, in count_documents
_cmd, self._read_preference_for(session), session)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1454, in _retryable_read
read_pref, session, address=address)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1253, in _select_server
server = topology.select_server(server_selector)
File "C:~\lib\site-packages\pymongo\topology.py", line 235, in select_server
address))
File "C:~\lib\site-packages\pymongo\topology.py", line 193, in select_servers
selector, server_timeout, address)
File "C:~\lib\site-packages\pymongo\topology.py", line 209, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: iliastrialcluster-shard-00-00-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-02-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-01-1tl2y.azure.mongodb.net:27017: timed out

ServerSelectionTimeout error is the client's way of telling you you can't connect to the server. The primary cause of these errors when using MongoDB Atlas is the failure to enable access for the IP address of the node the client is running on.
To verify try connecting using the MongoDB shell mongo using the same connection string. if you get a connection failed then you know it's not a Python problem. Your client code looks OK BTW so I am pretty sure this is what it is.
The connection to the server is lazily evaluated so we don't try to initiate a connection until you make an actual request. In this case the count_documents call. This is why this is the call that generates the error.

#JoeDrumgoole Thanks for your answer. The problem was the proxy after all, after deactivating it the connection works fine. Good to know that the connection to the server is lazily evaluated.

Related

Trouble connecting to Cloud SQL in python

I am trying to connect to a database on Cloud SQL, but I keep getting the same error. Not sure what it is, and tried several approaches.
Input:
import pymysql
connection = pymysql.connect(host='127.0.0.1',
user='',
password='XXXX',
db='cmcsql')
output:
C:\Users\Ejer\anaconda3\envs\pythonProject\python.exe C:/Users/Ejer/PycharmProjects/pythonProject/CloudSQL_test.py
Traceback (most recent call last):
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 569, in connect
sock = socket.create_connection(
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\socket.py", line 808, in create_connection
raise err
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Der kunne ikke oprettes forbindelse, fordi destinationscomputeren aktivt nægtede det
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Ejer/PycharmProjects/pythonProject/CloudSQL_test.py", line 2, in <module>
connection = pymysql.connect(host='127.0.0.1',
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 327, in __init__
self.connect()
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 619, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] Der kunne ikke oprettes forbindelse, fordi destinationscomputeren aktivt nægtede det)")
Process finished with exit code 1
You should not be using 127.0.0.1 to connect to cloud sql instance.
127.0.0.1 is (in most cases) for localhost connection (when you run the db server locally on the same machine as where the client is). Instead you should be using the ip address given to your cloud sql instance. You can find it on the overview tab of the sql instance under Connect to this instance.
You should also create your user on the users tab and then use it in your code.
Don't forget about authentication, check out connections tab and read more about it here
Making sure that you have proper ip, user, existing db and connecting from authorized network should do the trick.
PyMysql connects to port 3306 by default, if your process is running on a different port it won't be able to connect.
Apart from the host, user, password parameters you also have to provide the port on which the sql process is running.

Python mysql connector change host link to ipaddress

I am coming across an issue with mysql connector.
I have an environment that i can't connect from my local machine.
I use simple command for connection:
from mysql.connector import connect
connection = mysql.connector.connect(user='dbuser', database='dbname',
host='amazon_link', password='dbpassword')
This works for all environment except one. And this also works in the server as well where the database lives.
I can access the database using my MySqlWorkbench from local machine. But when i try from my script, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 210, in _open_connection
self._ssl)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 144, in _do_auth
self._auth_switch_request(username, password)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 177, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'dbuser'#'10.0.1.72' (using password: YES)
And the ip address that i get for the host link is different from what mysql connector is showing here as well.
Is there a way to avoid mysql connector to change link to url here, as when i use the link instead of ip address in my Workbench i am able to connect. So i doubt it is an issue related to vpn or security groups. Otherwise i wouldn't be able to connect to database via work bench at all.
Any help would be appreciated. Thanks.
And sorry in case i missed something basic here.
Try to use the global IP address of your server instead of the domain name.
Refer the stackoverflow link for more details:
Remotely connect to MySQL with Python mysql.connector

How to connect to mongodb with python

I tried connecting my application to my cluster on mongodb Atlas like the examples but I'm still having trouble.
I used
import pymongo
client = pymongo.MongoClient('mongodb+srv://kay:myrealpassword#cluster0.mongodb.net/test')
I replaced myrealpassword with my password and cluster0 with my cluster's name .
This is the error i got :
Traceback (most recent call last): File "", line 1, in
File
"/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 468,
in init
res = uri_parser.parse_uri(entity, port, warn=True) File "/Library/Python/2.7/site-packages/pymongo/uri_parser.py", line 399,
in parse_uri
nodes = _get_dns_srv_hosts(fqdn) File "/Library/Python/2.7/site-packages/pymongo/uri_parser.py", line 289,
in _get_dns_srv_hosts
raise ConfigurationError(str(exc)) pymongo.errors.ConfigurationError: None of DNS query names exist:
_mongodb._tcp.saudimood.mongodb.net., _mongodb._tcp.saudimood.mongodb.net.Home.
I was having similar DNS error, I misspelled the DNS seed list :s
To avoid this and another errors try:
In the Clusters view, click Connect for the cluster to which you
want to connect.
Select Connect your application.
Select your driver and version.
Copy the connection string.
Replace <password> with the password for the <username> user. Replace myFirstDatabase with the name of the database that connections will use by default.
Try it
pymongo.MongoClient('mongodb://user:password#servername/dbname')

pymysql cannot connect with SSL

I am trying to connect to a MySQL database using python but I am getting a strange error. It is compounded by the fact that I can use the same connection values from the mysql console command and it connects with no problems.
Here is the exact code I am using:
import pymysql
from checks import AgentCheck
class DelayedJobCheck(AgentCheck):
def check(self, instance):
self.log.info("testing connection")
self.log.info(instance)
connection = pymysql.connect(**instance)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
self.gauge('hello.world', 1)
This is the error that I am getting:
Traceback (most recent call last):
File "/opt/datadog-agent/agent/checks/__init__.py", line 661, in run
self.check(copy.deepcopy(instance))
File "/opt/datadog-agent/agent/checks.d/delayed_job.py", line 10, in check
connection = pymysql.connect(**instance)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
OperationalError: (2003, u"Can't connect to MySQL server on '192.168.199.86' ([SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:590))")
I am running this code on a Ubuntu box and I though initially that it might be because the SSL CA is a self generated cert. So I followed the steps here But, it did not make any difference. Also I have verified that the process that is running this code has full access to the cert files
Any ideas what else might be causing this?
As the err info said dh key is too small, a larger one might help. Replace the default dh512.pem file with dh4096.pem
sudo wget "https://git.openssl.org/gitweb/?p=openssl.git;a=blob_plain;f=apps/dh4096.pem" -O dh4096.pem
Ref: http://www.alexrhino.net/jekyll/update/2015/07/14/dh-params-test-fail.html

Connect to old mysql installation using python-mysql,

I'm trying to connect to database built in into a physical device, and I don't want to change any configuration of this mysql server.
When I try to connect i get following error:
Traceback (most recent call last):
File "connect3031.py", line 3, in <module>
cnx = mysql.connector.connect(user='..', database='...', password='...', host='192.168.88.100')
File "/usr/lib/pymodules/python2.7/mysql/connector/__init__.py", line 45, in Connect
return MySQLConnection(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/mysql/connector/connection.py", line 366, in __init__
self.connect(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/mysql/connector/connection.py", line 411, in connect
ssl=(ssl_ca, ssl_cert, ssl_key))
File "/usr/lib/pymodules/python2.7/mysql/connector/connection.py", line 449, in _open_connection
self._charset)
File "/usr/lib/pymodules/python2.7/mysql/connector/protocol.py", line 350, in do_auth
"Authentication with old (insecure) passwords "\
mysql.connector.errors.NotSupportedError: Authentication with old (insecure) passwords is not supported: http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
Typical response for such problem is, for example, here mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication, however I don't want to touch this server (apart from selecting data), so updating user is out of question.
Is there any way I can configure client so it accepts these old insecure passwords. I really don't care for security, since it will be accessed via VPN, and all passwords are essentially common knowledge, as they are printed in the manual.
Server in question is (anyways that's what mysqldump tells me:
Server version 4.1.7-max
You probably need to use an other connector.
MySQL-python seems to support MySQL3.23+.
mysql-connector-python simply can't connect using old authentication.

Categories

Resources