Connect to Oracle Cloud Database with python oracledb - python

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 !

Related

can't remotely connect to mysql database in cpanel with python

I tried to connect remotely to my database in cpanel in all ways but it won't let me, does anyone know why it doesn't give me access?
HOST = "xxxxxxxxx"
DATABASE = "xxxxxxxxx"
USER = "xxxxxxxxxxx"
PASSWORD = "xxxxxxx"
db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
print("Connected to:", db_connection.get_server_info())
#####################################################################################
python3 sqlConect.py
Traceback (most recent call last):
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/network.py", line 509, 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 "/home/miguel/Desktop/python/sqlConect.py", line 61, in <module>
db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 206, in _open_connection
self._socket.open_connection()
File "/home/miguel/.local/lib/python3.10/site-packages/mysql/connector/network.py", line 511, in open_connection
raise errors.InterfaceError(
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'industriasbjt.com:3306' (111 Connection refused)
In cpanel when you try to connect remotely and access is denied by port 3306, you have to contact the cpanel provider and check the plans that give remote access, because if port 3306 is blocked the remote connection plan may is limited, it's just a matter of talking to the provider that provides the cpanel

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

Cannot Connect To RDS Instance Using Python pymysql Library

I am attempting to connect to an RDS instance using Python's pymysql library. Unfortunately I'm getting an exception back.
Here is my Python code:
import pymysql
#Connect
connection = pymysql.connect(host='jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname',
port='3306',
user='username',
password='pass',
database='dbname')
Upon executing it, I receive the following exception:
Traceback (most recent call last):
File "/path/to/file/test.py", line 8, in <module>
database='treemigodb')
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname' ([Errno 8] nodename nor servname provided, or not known)")
Here is what I've tried:
I've opened up the security group on the AWS side to traffic. I had previously performed this connection in Java, with success. AWS is configured as it should be.
I've seen in other examples that the host format tends to vary. Therefore, I've tried:
jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/dbname
jdbc:mysql://url.us-east-1.rds.amazonaws.com/dbname
jdbc:mysql://dbname.url.us-east-1.rds.amazonaws.com/
jdbc:mysql://url.us-east-1.rds.amazonaws.com/
dbname.url.us-east-1.rds.amazonaws.com/dbname
url.us-east-1.rds.amazonaws.com/dbname
dbname.url.us-east-1.rds.amazonaws.com/
Is there some potential setup that I could be missing? I've double-checked that every other parameter matches.

mysql.connector.errors.interfaceerror 2003

My summer project is to put data into SQL for processing. Unfortunately I can not establish a connection to the SQL with mysql connector.
The python file I am testing with are two lines:
import mysql.connector
db1 = mysql.connector.connect(host="localhost", database="thename", user="user",password="passw")
The error message is:
C:\Projekt\Python efforts...>test.py Traceback (most recent call
last): File
"C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\network.py",
line 472, in open_connection
self.sock.connect(sockaddr) ConnectionRefusedError: [WinError 10061] Det gick inte att göra en anslutning eftersom måldatorn aktivt
nekade det
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Projekt\Python
efforts...\test.py", line 4, in
db1 = mysql.connector.connect(host="localhost", database="thename", user="user",password="passw") File
"C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector__init__.py",
line 179, in connect
return MySQLConnection(*args, **kwargs) File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\connection.py",
line 95, in init
self.connect(**kwargs) File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\abstracts.py",
line 719, in connect
self._open_connection() File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\connection.py",
line 206, in _open_connection
self._socket.open_connection() File "C:\Users\Niklas\AppData\Local\Programs\Python\Python35\lib\site-packages\mysql\connector\network.py",
line 475, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err))) mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL
server on 'localhost:3306' (10061 Det gick inte att göra en anslutning
eftersom måldatorn aktivt nekade det)
C:\Projekt\Python efforts...>
I have tried restarting and enabling services and computer several times. The user and password I use grants me access in SQL Server Management Studio. I have created a firewall rule to allow communication on port 3306, though it is not listed as one of the active ports when I look. I have also tried disabling the firewall on my computer (though not on the router as it should not be needed for a localhost query?). Using wireshark I don't seem to get any traffic at all on port 3306(!?). I cannot telnet to localhost though tracert has no problems. I have tried with different IPs and domain name that are valid. I have enabled TCP/IP settings for a bunch of the different IP versions under TCP/IP protocol in the SQL Server Configuration manager (though I'm not sure how I did that as it is write protected so I can't do the rest of them).
Everything listed here yields the same result so I assume that there is something very fundamentally (basic and easy?) wrong with what i am doing. Please pitch in with any and all troubleshooting tips you can find for resolving this connection issue as I am on my third day of getting absolutely nowhere.
Once again it has been proven that it is easy to get blinded when digging. I was trying to use mysql connector to connect to a ms sql. I have now switched to pypyodbc to handle the communication with the SQL.

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