MySQL8 – 'caching_sha2_password requires SSL' - mysql

I have changed to Mysql8 on my server.
I connect to the server through ssh.
With (e.g.) VScode Database explorer I can use the on the server, but from Python3 with MySQL connector, I don't.
On sever side, 'ssl_disabled=True,' solved the problem, but on my computer, I can not connect to the server's db.
import mysql.connector
from mysql.connector import Error
def create_connection():
connection = None
try:
connection = mysql.connector.connect(
host='host',
port='port',
user='user',
passwd='passwd',
database='db',
ssl_disabled=True,
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"Error in create_connection -->\n '{e}'")
return connection
create_connection()
I try to run this and get:
'caching_sha2_password requires SSL'

I solved it!
If I use port 3307 instead of 3306, it works from the local machine, too!

Related

SSL integration with Cloud SQL instance based MySQL

I enabled SSL in a MySQL Cloud SQL instance. In order to connect to the instance , I downloaded the necessary certficates and can connect fine using mysql command. The CloudSQL instance is running with Private IP on a sharedVPC network .
$ mysql -h 192.168.0.3 --ssl-ca=server-ca.pem --ssl-cert=client-cert.pem --ssl-key=client-key.pem -u testuser -p
Enter password:
Now to test connectivity from a code to connect to SQL instance I deployed the following in Cloud Functions
import pymysql
from sqlalchemy import create_engine
def sql_connect(request):
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True)
tab = engine.execute('show databases;')
return str([t[0] for t in tab])
It shows "Access Denied" error as shown below
Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Details:
(pymysql.err.OperationalError) (1045, "Access denied for testuser'#'192.168.60.4' (using password: YES)")
When I disable SSL it works fine as shown below
['information_schema', 'mysql', 'performance_schema', 'sys', 'testdb']
A) To enable SSL in code I did the following
ssl_args = {'sslrootcert':'server-ca.pem','sslcert':'client-cert.pem','sslkey':'client-key.pem'}
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True,connect_args=ssl_args)
but it is failing with below error
__init__() got an unexpected keyword argument 'sslrootcert'
B) Also tried disabling ssl=False in code but it is failing with below error
Invalid argument(s) 'ssl' sent to create_engine(), using configuration MySQLDialect_pymysql/QueuePool/Engine
UPDATE:
Changed the code for SSL as follows:
ssl_args = {'ssl': {'ca':'./server-ca.pem', 'cert':'./client-cert.pem', 'key':'./client-key.pem'}}
Uploaded the certs to cloud function source
Added 0.0.0.0/0 as authorized networks in CloudSQL to allow connecting from Cloud functions
Now seeing the following error
"Can't connect to MySQL server on 'X.X.X.181' ([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for 'X.X.X.181'. (_ssl.c:1091))") . However can connect using the same certificates using `mysql` command
Need help to resolve both A) fixing the error as observed so that the code is integrated with SSL and B) Modify code so that it does not uses SSL
Use ssl_ca for the root, ssl_cert for the cert and ssl_key for the key
ssl_args = {'ssl_ca':'server-ca.pem','ssl_cert':'client-cert.pem','ssl_key':'client-key.pem'}
engine = create_engine('mysql+pymysql://testuser:<password>#192.168.0.3/mysql',echo=True,connect_args=ssl_args)
Use SSL parameter in the form ssl = {"ssl":{"ca":"server-ca.pem"}} within the connect function
from pymysql import connect
from sqlalchemy import create_engine
import os
SQLALCHEMY_DATABASE_URI='mysql+pymysql://testuser:<password>#192.168.0.3/mysql?ssl_ca=server-ca.pem'
engine = create_engine(SQLALCHEMY_DATABASE_URI)
args, kwargs = engine.dialect.create_connect_args(engine.url)
# Create connection to the DB
db_conn = connect(kwargs["host"], kwargs["user"], kwargs["passwd"], kwargs["db"], ssl = {"ssl":{"ca":kwargs["ssl"]["ca"]}})
cursor = db_conn.cursor()
# Execute query
cursor.execute("show tables")
cursor.fetchall()

How to connect to a remote database server using Python?

I am trying to connect to a remote database server that is installed on CentOS 7 in VMware from windows using python, but I am unable to connect to it. I am using mysql.connector to access the database.Please help me solve the problem.
import mysql.connector
mydb = mysql.connector.connect(host="192.168.136.129", user="root", passwd="root", database="test", port=3306)
mycr = mydb.cursor()
mycr.execute("CREATE TABLE cat (name VARCHAR(25));")
Don't use root user there might be some permission issue.
Try creating a new user and access it.

(2059,“Authentication Plugin 'caching_sha2_password'”) when running server connected with MYSQL database on Django

I want to configure my django project in order to connect it with database in MYSQL I created with workbench 8.0,
and then I want to run the server by running
python manage.py runserver
from anaconda command prompt,
so that I can use the Django interface to visualize and alter data.
Please note that I don’t want to downgrade workbench 8.0.
These are the steps I have made:
From anaconda prompt:
pip install mysqlclient
In my project folder, in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'schema_meta',
'USER': 'root',
'PASSWORD': '<mypassword>',
'HOST': '127.0.0.1',
'PORT': '3306',
},
}
Inside the directory of mysql server, I open cnf.ini and insert a the [client] section:
[client]
database=schema_meta
host=127.0.0.1
user=root
password=<mypassword>
port=3306
default-character-set = utf8
Then from anaconda prompt I run
Python manage.py runserver
And I obtain error
django.db.utils.OperationalError: (2059, "Authentication plugin
'caching_sha2_password' cannot be loaded: Impossibile trovare il
modulo specificato.\r\n")
So I try to solve it by following this thread: django.db.utils.operationalError: (2059,"Authentication Plugin 'caching_sha2_password'")
I open mysql workbench and I run this query:
delete from mysql.user
where user='root'
and host = '127.0.0.1';
flush privileges;
CREATE USER 'root'#'127.0.0.1' IDENTIFIED WITH mysql_native_password BY '<mypassword>';
And then, in the my.ini file I change
default-authentication-plugin= caching_sha2_password
With
default-authentication-plugin=mysql_native_password
Finally from anaconda prompt:
python manage.py runserver
But again I get
django.db.utils.OperationalError: (2059, "Authentication plugin
'caching_sha2_password' cannot be loaded: Impossibile trovare il
modulo specificato.\r\n")
Now, what’s wrong? Why it did not get the changes into the authentication method?
In order to check that there are no other errors, from mysql workbench, from first “home” view, I right click on my database, I open “edit connection”, I click on “test connection”, and the software says that the connection is successfull.
mysql workbench saying connection successfully established
Moreover, I wanted to check if the problem was in my Django settings.
So from anaconda prompt I run
pip install pymysql
Then in the project folders I created a “connect_to_mysql.py” script, with the following code inside:
import pymysql.cursors
mydb = pymysql.connect(host='127.0.0.1',
user='root',
password='<mypassword>',
db='schema_meta',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
print(mydb)
and this seems to work fine, since when I run
connect_to_mysql.py
from anaconda, I get
pymysql.connections.Connection object at 0x000002013F2851D0
That I guess it means “connection successfully established”.
And just to be sure that the problem is into mysql (mysql connector I guess), I create a file “connect_to_mysql_2.py” with this code inside:
import mysql.connector
mydb = mysql.connector.connect(user='root', password='<mypassword>',
host='127.0.0.1', database='meta_schema')
print(mydb)
And when I run it from anaconda, again I get
"Authentication plugin '{0}' is not supported".format(plugin_name))
mysql.connector.errors.NotSupportedError: Authentication plugin
'caching_sha2_password' is not supported
That means that I fixed nothing by working on mysql workbench and in my.ini file.
How can I get my Django connected with my mysql database and my server running?
Is there a way to establish the server connector using pymysql connector instead that mysql connector?
This is probably not a problem in your python code, but in the python connector. The caching_sha2_password plugin is now the default auth plugin and clients have to support it in order to connect. So, the best solution is to update your python connector. An alternative way is to disable this plugin, but that's something I don't recommend as it lowers your server's security.
PyMySQL added support for caching_sha2_password in 0.9.0, though there was a Py2 error fixed in 0.9.1.
Also noted in the install instructions, for caching_sha2_password there is the additional requirement:
python3 -m pip install PyMySQL[rsa]
I think I solved it.
By following this thread
https://stackoverflow.com/a/21740692/7658051
In settings.py, at the DATABASES entry, I substituted
'ENGINE': 'django.db.backends.mysql'
with
'ENGINE': 'mysql.connector.django',
and again, as specified here,
https://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w003-utf8mb4
i added also
'OPTIONS': {
# Tell MySQLdb to connect with 'utf8mb4' character set
'charset': 'utf8mb4',
},
# Tell Django to build the test database with the 'utf8mb4' character set
'TEST': {
'CHARSET': 'utf8mb4',
'COLLATION': 'utf8mb4_unicode_ci',
}
and then if I run
python manage.py runserver
It seems to work, even if I cannot access http://127.0.0.1:8000/admin , because I am connected to a legacy database, so I still have to inspect db and stuff I still have to learn.
As second proof that the connection is now working, when I run
connect_to_mysql_2.py
(See (2059,“Authentication Plugin 'caching_sha2_password'”) when running server connected with MYSQL database on Django)
I finally get
mysql.connector.connection_cext.CMySQLConnection object at 0x000001DFB7521550
So I really think this time the connection is on.

Export Data From Raspberry Pi to mysql database on a PC via wifi

I am new to raspberry pi, and mysql servers, I am hoping I could get some insight on a problem which has occurred. This is a part of a project which is due in a few weeks, and was hoping to have a solution soon.
I am attempting to send data, via wifi, from my raspberry pi to a mysql database located on a PC. The raspberry pi and the mysql database are on the same local wifi network.
On the raspberry pi side, I have used the commands:
"sudo apt-get install python3-mysql.connector" and
"sudo apt-get install -f" to install the mysql connector.
my code is as follows:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", #localhost=ip address of PC
user="user",
passwd="1111",
database="location",
port="80"
)
mycursor = mydb.cursor()
sql = "INSERT INTO location (latitude, longitude) VALUES (%s, %s)"
val = ("26.111111", "-80.44444444")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
But the following error occurred:
self.sock.connect(sockaddr) ConnectionRefusedError:[Errno 111] Connection refused
I'd like to know, are there any other procedures that I am missing?
You are connecting to localhost instead of your PC, where I suspect your MySQL must be running.
I found the solution.
even though the httpd.conf file located on the PC says "Listen 0.0.0.0:80 Listen [::0]:80",
the port in the code should be 3306, instead of 80.

connecting Canopy to mysql

I am new to Python and using Enthought Canopy Express for learning purpose. As part of that I am looking for an option to connect Canopy to mysql. I did not find any materials. Please share if you know any method that I can use mysql in Canopy Express.
I am using Mac OS X version 10.9
Path for canopy is:
/Users/mz/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages
Mysql is version 5.6 with the following path:
mysql is /usr/local/mysql/bin/mysql
You can use the Canopy Package Manager to install pymysql:
Once installed, access pymysql according to the Python PEP249 DB API (create a connection, get a cursor, etc.):
In [1]: import pymysql
In [2]: connection = pymysql.connect?
Signature: pymysql.connect(*args, **kwargs)
Docstring:
Establish a connection to the MySQL database. Accepts several
arguments:
host: Host where the database server is located
user: Username to log in as
password: Password to use.
database: Database to use, None to not use a particular one.
port: MySQL port to use, default is usually OK.
...