How do I configure PyMySQL connect for SSL? - python

I'm trying to connect my database using SSL with PyMySQL, but I can't find good documentation on what the syntax is.
These credentials work in Workbench and with the CLI, but I get this error when using PyMySQL.
Can't connect to MySQL server on 'server.domain.com' ([WinError 10061] No connection could be made because the target machine actively refused it)")
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl={'ssl':{'ca': 'C:/SSL_CERTS/ca-cert.pem',
'key' : 'C:/SSL_CERTS/client-key.pem',
'cert' : 'C:/SSL_CERTS/client-cert.pem'
}
}
)
If I shut SSL off and drop the SSL parameter, I can connect unsecured just fine. What am I doing wrong with the SSL parameter?
Edit: PyMySQL now wants ssl parameters listed like this instead of in a dict.
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)

Thanks for the help everyone. The syntax listed in the question is right, but the server I was attempting a connection to was using a non-standard port. I needed to add
port = db_creds['port']
Thanks, MannyKary, for the clue.

I had the same problem connecting pyMysql using client-side cert and key for users that REQUIRE X509, the TiDB (mySQL 5.7 compatible) server complained that no cert was supplied!!!
[2021/05/18 16:31:23.881 +00:00] [INFO] [privileges.go:258] ["ssl check failure, require x509 but no verified cert"] [user=mindline_root] [host=%]
Looking through the sourcecode of PyMysql 1.0.2, it appears that the ssl parameter is now a boolean instead of a ssl_dict, so you should put all your ssl parameters into individual arguements, e.g.,
db_conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['user'],
passwd=db_creds['passwd'],
db=db_creds['db'],
charset=db_creds['charset'],
ssl_ca='C:/SSL_CERTS/ca-cert.pem',
ssl_key='C:/SSL_CERTS/client-key.pem',
ssl_cert='C:/SSL_CERTS/client-cert.pem'
)

Related

How do I connect my python code to a mysql database hosted on the internet?

I have made a free account on https://www.freemysqlhosting.net which provides a free mysql database hosting facilities. I have created a database there, but I don't know how to connect to it from my python code on VSCode.
As of now, I am using a database that is on my computer.
This is the code in a config.py file that establishes connection to the MySQL server.
import mysql.connector as mysql
mysqlobj = mysql.connect(host='localhost', user='root',password='Mypass', database='timetable')
cursorobj = mysqlobj.cursor()
cursorobj.execute('USE timetable')
So how do I connect to a remote database on the said website with a piece of code that can be executed, because that way the connection can be established from any computer if they have the code to do so, without installing extensions(unless it's necessary).
If you require more details, please do ask in the comment section.
You should use remote address of server on which MySQL server is hosted and provide the IP address or Domain name exposed as connection properties to you in host,
import mysql.connector
config = {
'user': 'test',
'password': 'password',
'host': 'Remote IP or Domain Name',
'database': 'employees',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cnx.close()
This looks like a dup of Connecting to remote database located on web (freemysqlhosting.net‏) via visual studio c#. I've never used that service(looks pretty sketchy). They should provide you a connection string or at least the connection parts which consists of:
IP
port
username
password
database
NOTE: it's generally a bad idea to have a mysql server bound to ports exposed to the public internet, even with a username password.
I think you should be using pyodbc instead of mysql connector. That's what I remember using.
To install pyodbc it is a simple pip install pyodbc command
You may find more useful information here
If you're unable to connect to your hostedDB, try to whitelist your local IP address in your hosting server.
This might work.

Problems with MySQL in Python

I'm currently building a python flask web app. When I run it I get several ERRORS about lost connection to the MySQL server. Can someone help me, please?
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
mysql.connector.errors.OperationalError: MySQL Connection not available.
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'eu-cdbr-west-01.cleardb.com:3306', system error: 1 [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2570)
I get those errors when I upload it to Heroku and also on my local computer. It's also weird that it's sometimes working and sometimes not.
Are you using a library? My previous experience with flask <-> sql has been through pymysql.
here's the connection and return function i used the last time i set it up, this, may however be out of date since the new version of pymysql was added.
def connect_to_db():
'''this function connects the database to the website'''
return pymysql.connect( host = db_host(),
user = db_username,
password = my_secrets.hunter2,
db = 'some_db',
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor,
)
def return_db():
'''Opens a new database connection per request.'''
if not hasattr(g, 'db'):
g.db = connect_to_db()
return g.db
Notice here that the return function requires importing the flask g object
It also looks like SSL is one of the problems you're running into. SSL can be a big pain when changing versions especially on OSX.

How to setup ssh tunnel dynamically in python?

I am trying to build a tunnel to then connect to an Oracle DB, but tunnel cannot be opened. Error is the following:
ERROR | Problem setting SSH Forwarder up: Couldn't open tunnel localhost:1521 <> XXXXXXXXX:1521 might be in use or destination not reachable.
sshtunnel.HandlerSSHTunnelForwarderError: An error occurred while opening tunnels.
My code is set as:
self.tunnel = sshtunnel.SSHTunnelForwarder((conn_data['gateway'], int(conn_data['gateway_port'])),
ssh_username=conn_data['username'],
ssh_password=password,
remote_bind_address=(conn_data['remote_bind'],
int(conn_data['remote_port'])),
local_bind_address=(conn_data['local_bind'],
int(conn_data['local_port'])))
The code works fine if I am inside the network of the company I work for. But if I am connected through VPN, I get the above error. My guess is that the VPN is built over the same tunnel.
I tried changing the local_port and removing the local bind, but if I do that, I get the error:
cx_Oracle.DatabaseError: ORA-12541: TNS:no listener
So, how can I dynamically set the port of SSHTunnelForwarder so it can access my DB through my already set VPN?
Note: changing the VPN's configuration or not using it is not an option.
Problem solved. The issue was that my VPN was using the same port as me (which caused the first error), and my Oracle connection was pointing to this port also (what caused error ORA-12541).
To solve it, I had to change conn_data['local_port'] to another port and set the port of my oracle connection to this same port:
self.tunnel = sshtunnel.SSHTunnelForwarder((conn_data['gateway'],
int(conn_data['gateway_port'])),
ssh_username=conn_data['username'],
ssh_password=password,
remote_bind_address=(conn_data['remote_bind'], int(conn_data['remote_port'])),
local_bind_address=(conn_data['local_bind'], 1234))
self.connection.connect(conn_data['host'],
port=1234,
username=conn_data['username'],
password=password,
look_for_keys=False)

Database connection failed for local MSSQL server with pymssql

I had been working with pyodbcfor database connection in windows envirnment and it is working fine but now I want to switch to pymssql so that it is easier to be deployed to Linux machine as well. But I am getting this error:
(20009, b'DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is unavailable or does not exist (localhost:1433)\nNet-Lib error during Unknown error (10060)\n')
My connection code for using both pyodbc and pymssql is:
import pyodbc
import pymssql
def connectODSDB_1():
conn_str = (
r"Driver={SQL Server};"
r"Server=(local);"
r"Database=populatedSandbox;"
r"Trusted_Connection=yes;"
)
return pyodbc.connect(conn_str)
def connectODSDB_2():
server = '(local)'
database = 'populatedSandbox'
conn = pymssql.connect(server=server, database=database)
return conn
What could be the problem? And solution?
Well after browsing internet for a while, it seems pymssql needs TCP/IP be enabled for communication.
Open Sql Server Configuration Manager
Expand SQL Server Network Configuration
Click on Protocols for instance_name
Enable TCP/IP
I have faced the same issue while using RDS(AWS database instance). We should configured the inbound outbound rules.
Do following steps to configure.
Services->RDS->DB Instances -> Select DB-> Connectivity&Security
Under Security Section
VPC security groups -> click on security group
Change the inbound rules.
Check the source IP and change into anywhere or specific IP

Cannot connect to Oracle using python 3.4

I just started to learn python and try to connect to oracle 11g, but I always get following error
cx_Oracle.InternalError: No Oracle error?
Here is my simple script to connect to oracle
import cx_Oracle as oracle
con = oracle.connect('user/password#ip:port/service')
Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.
One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:
import cx_Oracle
ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)
This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.

Categories