Python3 MySQL SSL Error - mysql.connector - python

I have spent all day on this and cant figure it out. I have no problems connecting to the remote server using python and the mysql.connector but when i try using SSL I get the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/network.py", line 384, in switch_to_ssl
self.sock.do_handshake()
File "/usr/lib/python3.4/ssl.py", line 804, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:600)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./mysql_test.py", line 25, in <module>
con = mysql.connector.connect(**config);
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 210, in _open_connection
self._ssl)
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 134, in _do_auth
self._socket.switch_to_ssl(**ssl_options)
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/network.py", line 390, in switch_to_ssl
errno=2055, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2055: Lost connection to MySQL server at '192.168.1.10:3306', system error: 1 [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:600)
system spec both servers:
Debian 8.2
OpenSSL 1.0.1k 8 Jan 2015
mysql 5.7.X.
python3
pip3
mysql.connector = Connector/Python 2.1.3
I know the ssl connection works with php and cli mysql connections but i can't figure out how to get ssl to work properly. I have also tried to change the ssl protocol in the mysql.connector network.py source. I have also tried with and without use_pure flag. Any help is greatly appreciated.
the python source:
import mysql.connector
config = {
'user' : 'uname',
'password' :'passwd',
'host' : '192.168.1.10',
'database' : 'python',
'ssl_ca' : '/etc/mysql/ssl/client/ca-cert.pem',
'ssl_cert' : '/etc/mysql/ssl/client/client-cert.pem',
'ssl_key' : '/etc/mysql/ssl/client/client-key.pem',
'use_pure' : 'False'
}
con = mysql.connector.connect(**config);
con.close();

I figured it out. Needed to remove the ssl_key and ssl_cert connection arguments, and only supply the ssl_ca and it works like a charm.

Related

Unable to establish connection to MySQL server 'Authentication plugin is not supported'

I'm trying to establish a connection to MySQL server from IDLE and I can't figure out why I'm getting an error.
>>> dbconfig = {'host': '127.0.0.1',
'user': 'vsearch',
'password': 'vsearchpasswd',
'database': 'vsearchlogDB'}
>>> import mysql.connector
>>> conn = mysql.connector.connect(**dbconfig)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
conn = mysql.connector.connect(**dbconfig)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 208, in _open_connection
self._do_auth(self._user, self._password,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/connection.py", line 137, in _do_auth
packet = self._protocol.make_auth(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/protocol.py", line 99, in make_auth
packet += self._auth_response(client_flags, username, password,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/protocol.py", line 58, in _auth_response
auth = get_auth_plugin(auth_plugin)(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/mysql/connector/authentication.py", line 190, in get_auth_plugin
raise errors.NotSupportedError(
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
I've tried these suggestions I found on stackoverflow :
shutting down mysql.server, installing mysql-connector-python and restarting mysql.server
passing an auth_plugin argument to the connect() method (as seen below)
auth_plugin='mysql_native_password'
made sure MySQL in listening to port 3306 (answer below)
localhost:mysql (LISTEN)
Versions:
mysql Ver 8.0.32 for macos12.6 on x86_64 (Homebrew)
Python 3.9.1
MacOS 12
Managed to fix issue by uninstalling MySQL connector and reinstalling it. Had issues with permissions so make sure you have permissions to read and write in connector directories.
This tutorial might help if your trying to connect to MySQL with MySQL-connector-python :
https://pynative.com/python-mysql-database-connection/

Quickstart.py - failed to connect to all addresses

I installed the Python libraries on my local PC, I also added my GA-4 Property ID. When I attempt to run the script I get the following error, note that the error actually makes sense because the IP Address failing doesn't have a valid SSL certificate:
Traceback (most recent call last):
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 72, in error_remapped_callable
return callable_(*args, **kwargs)
File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED"
debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED {grpc_status:14, created_time:"2022-11-28T18:41:22.060505311+00:00"}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 51, in <module>
sample_run_report("")
File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 43, in sample_run_report
response = client.run_report(request)
File "\\usalbodd01\bod_Share\BODS_Tools\google\analytics\data_v1beta\services\beta_analytics_data\client.py", line 511, in run_report
response = rpc(
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\gapic_v1\method.py", line 154, in __call__
return wrapped_func(*args, **kwargs)
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 74, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
Have any of you run into this when attempting to run the quickstart.py script locally?
Regards,
Greg
I attempted to run the script after following the "TODOS". I installed the Google certificates locally. I then tested the IP Address the script is failing on, the address is not secured.
Your connection isn't private
Attackers might be trying to steal your information from 142.250.190.10 (for example, passwords, messages, or credit cards).
NET::ERR_CERT_AUTHORITY_INVALID

Connect to Oracle Cloud Database with python oracledb

I'm trying to connect to a newly created database in Oracle Cloud (https://cloud.oracle.com/db/adb/)
I've copied the connection string from DB Connection > Connection Strings > (One of the three listed.)
Which looks a little like this:
(description= (retry_count=20)(retry_delay=3)(address=(protocol=tcps)(port=1522)(host=adb.uk-london-1.oraclecloud.com))(connect_data=(service_name=abc123xyzredacted.adb.oraclecloud.com))(security=(ssl_server_cert_dn="CN=adwc.eucom-central-1.oraclecloud.com, OU=Oracle BMCS FRANKFURT, O=Oracle Corporation, L=Redwood City, ST=California, C=US")))
I'm authenticating using the "ADMIN" account that was created at DB creation along with its password.
Running the test.py script found here: https://python-oracledb.readthedocs.io/en/latest/user_guide/installation.html#quickstart
import oracledb
import os
un = os.environ.get('PYTHON_USERNAME')
pw = os.environ.get('PYTHON_PASSWORD')
cs = os.environ.get('PYTHON_CONNECTSTRING')
with oracledb.connect(user=un, password=pw, dsn=cs) as connection:
with connection.cursor() as cursor:
sql = """select sysdate from dual"""
for r in cursor.execute(sql):
print(r)
I get
% python test.py
Traceback (most recent call last):
File "src/oracledb/impl/thin/connection.pyx", line 227, in oracledb.thin_impl.ThinConnImpl._connect_with_address
File "src/oracledb/impl/thin/crypto.pyx", line 125, in oracledb.thin_impl.get_ssl_socket
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1040, in _create
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1129)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/test.py", line 15, in <module>
with oracledb.connect(user=un, password=pw, dsn=cs) as connection:
File ".venv/lib/python3.9/site-packages/oracledb/connection.py", line 1000, in connect
return conn_class(dsn=dsn, pool=pool, params=params, **kwargs)
File ".venv/lib/python3.9/site-packages/oracledb/connection.py", line 128, in __init__
impl.connect(params_impl)
File "src/oracledb/impl/thin/connection.pyx", line 345, in oracledb.thin_impl.ThinConnImpl.connect
File "src/oracledb/impl/thin/connection.pyx", line 163, in oracledb.thin_impl.ThinConnImpl._connect_with_params
File "src/oracledb/impl/thin/connection.pyx", line 129, in oracledb.thin_impl.ThinConnImpl._connect_with_description
File "src/oracledb/impl/thin/connection.pyx", line 247, in oracledb.thin_impl.ThinConnImpl._connect_with_address
File ".venv/lib/python3.9/site-packages/oracledb/errors.py", line 103, in _raise_err
raise exc_type(_Error(message)) from cause
oracledb.exceptions.OperationalError: DPY-6005: cannot connect to database. Connection failed with "[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1129)"
Am I using the wrong connection string? Should I create another user?
Additional:
I've just found this: https://blogs.oracle.com/opal/post/easy-way-to-connect-python-applications-to-oracle-autonomous-databases
So I now have "Network" showing:
Access Type: Allow secure access from specified IPs and VCNs
Access Control List: Enabled Mutual TLS (mTLS)
Authentication: Not Required
Where my IP address is entered in Access Control List.
You have:
Access Control List: Enabled Mutual TLS (mTLS)
which seems incorrect.
This is what my cloud console shows when I have 1-way (aka walletless) authentication enabled:
Network
Access Type: Allow secure access from specified IPs and VCNs
Access Control List: Enabled
Mutual TLS (mTLS) Authentication: Not Required
When you copy the connection string from the cloud console, make sure to select the correct TLS (not mTLS) value in the dropdown box just above, because the connection string changes.
Check your current IP address is in the ACL list, because IPs addresses are often not static !

Python myqsl.connector connection error on pyton.org

I have a mysql server on my computer. I did port fowarding on my modem. I checked port is open or not with signal sites and return success answer. When i try connect on my pc with host = "localhost" i returned success answer. But when i try connect mysql server with python.org's shell, i returned connection error same like this:
Traceback (most recent call last):
File “/usr/lib/python3.8/site-packages/mysql/connector/network.py”, line 529, in open_connection
self.sock.connect(sockaddr)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “”, line 1, in
File “/usr/lib/python3.8/site-packages/mysql/connector/init.py”, line 177, in connect
return MySQLConnection(*args, **kwargs)
File “/usr/lib/python3.8/site-packages/mysql/connector/connection.py”, line 104, in init
self.connect(**kwargs)
File “/usr/lib/python3.8/site-packages/mysql/connector/abstracts.py”, line 781, in connect
self._open_connection()
File “/usr/lib/python3.8/site-packages/mysql/connector/connection.py”, line 284, in _open_connection
self._socket.open_connection()
File “/usr/lib/python3.8/site-packages/mysql/connector/network.py”, line 531, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can’t connect to MySQL server on ‘myipadress:3306’ (111 Con
nection refused)
How can i connect my mysql server ?
In order to encounter this error first do the following:
Make sure the host is in the format 127.0.0.1 and there are no / or \ in the host name
Check if you have specified all the correct info about the server like passwords, user, root, etc
Make sure the server is active and there is no fire wall blocking your access
Remove all the unwanted users from the server

Connection to remote MySQL db from Python 3.4

I'm trying to connect to two MySQL databases (one local, one remote) at the same time using Python 3.4 but I'm really struggling. Splitting the problem into three:
Step 1: connect to the local DB. This is working fine
using PyMySQL. (MySQLdb isn't compatible with Python 3.4, of
course.)
Step 2: connect to the remote DB (which needs to
use SSH). I can get it to work from the Linux command prompt but not
from Python... see below.
Step 3: connect to both at the
same time. I think I'm supposed to use a different port for the
remote database so that I can have both connections at the same time
but I'm out of my depth here! If it's relevant then the two DBs will
have different names. And if this question isn't directly related,
please tell me and I'll post it separately.
Unfortunately I'm not really starting in the right place for a newbie... once I can get this working I can happily go back to basic Python and SQL but hopefully someone will take pity on me and give me a hand to get started!
For Step 2, my code is below. It seems to be quite close to the sshtunnel example which answers this question Python - SSH Tunnel Setup and MySQL DB Access - though that uses MySQLdb. For the moment I'm embedding the connection parameters – I'll move them to the config file once it's working properly.
import dropbox, pymysql, shlex, shutil, subprocess
from sshtunnel import SSHTunnelForwarder
import iot_config as cfg
def CloseLocalDB():
localcur.close()
localdb.close()
def CloseRemoteDB():
# Disconnect from the database
# remotecur.close()
# remotedb.close()
# Close the SSH tunnel
# ssh.close()
print("end of CloseRemoteDB function")
def OpenLocalDB():
global localcur, localdb
localdb = pymysql.connect(host=cfg.localdbconn['host'], user=cfg.localdbconn['user'], passwd=cfg.localdbconn['passwd'], db=cfg.localdbconn['db'])
localcur = localdb.cursor()
def OpenRemoteDB():
global remotecur, remotedb
with SSHTunnelForwarder(
('my_remote_site', 22),
ssh_username = "my_ssh_username",
ssh_private_key = "/etc/ssh/my_private_key.ppk",
ssh_private_key_password = "my_private_key_password",
remote_bind_address = ('127.0.0.1', 3308)) as server:
remotedb = None
#Following line gives an error if uncommented
# remotedb = pymysql.connect(host='127.0.0.1', user='remote_db_user', passwd='remote_db_password', db='remote_db_name', port=server.local_bind_port)
#remotecur = remotedb.cursor()
# Main program starts here
OpenLocalDB()
CloseLocalDB()
OpenRemoteDB()
CloseRemoteDB()
This is the error I'm getting:
2016-04-21 19:13:33,487 | ERROR | Secsh channel 0 open FAILED: Connection refused: Connect failed
2016-04-21 19:13:33,553 | ERROR | In #1 <-- ('127.0.0.1', 60591) to ('127.0.0.1', 3308) failed: ChannelException(2, 'Connect failed')
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60591)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/sshtunnel.py", line 286, in handle
src_address)
File "/usr/local/lib/python3.4/dist-packages/paramiko/transport.py", line 834, in open_channel
raise e
paramiko.ssh_exception.ChannelException: (2, 'Connect failed')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.4/socketserver.py", line 613, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python3.4/socketserver.py", line 344, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.4/socketserver.py", line 669, in __init__
self.handle()
File "/usr/local/lib/python3.4/dist-packages/sshtunnel.py", line 296, in handle
raise HandlerSSHTunnelForwarderError(msg)
sshtunnel.HandlerSSHTunnelForwarderError: In #1 <-- ('127.0.0.1', 60591) to ('127.0.0.1', 3308) failed: ChannelException(2, 'Connect failed')
----------------------------------------
Traceback (most recent call last):
File "/home/pi/Documents/iot_pm2/iot_ssh_example_for_help.py", line 38, in <module>
OpenRemoteDB()
File "/home/pi/Documents/iot_pm2/iot_ssh_example_for_help.py", line 32, in OpenRemoteDB
remotedb = pymysql.connect(host='127.0.0.1', user='remote_db_user', passwd='remote_db_password', db='remote_db_name', port=server.local_bind_port)
File "/usr/local/lib/python3.4/dist-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 678, in __init__
self.connect()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 889, in connect
self._get_server_information()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 1190, in _get_server_information
packet = self._read_packet()
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 945, in _read_packet
packet_header = self._read_bytes(4)
File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 981, in _read_bytes
2013, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
Thanks in advance.
Answering my own question because, with a lot of help from J.M. Fernández on Github, I have a solution: the example that I copied at the beginning uses port 3308 but port 3306 is the standard. Once I'd changed this it started working.

Categories