Python Oracle Connection using cx_Oracle and Kerberos Auth - python

Is there a way to use the oracle python driver package cx_Oracle and specify Kerberos authentication?
I've seen this done using oracle jdbc drivers, but not with cx_Oracle specifically. Below is my current connection code:
dsn = cx_Oracle.makedsn(host="some host", port="some port", service_name="some service")
con = cx_Oracle.connect("user", "password", dsn, threaded=True)

Maybe these will help:
Similar setup?
Connect to Database using oracle client and kerberos with Python
CX-Oracle or Python OracleDB with External Auth:
https://github.com/oracle/python-cx_Oracle/issues/61#issuecomment-320121457

Related

How can I use Python 3.10 to connect to a MariaDB database on a NAS from a Linux machine?

Good day,
I have a Synology NAS DS120J hosting a MariaDB 10 (10.3.32-1040) database, on the same local network, I have a Linux machine running Ubuntu 22.04.
I am trying to connect the Linux machine to the MariaDB database using Python 3.10 and the MariaDB connector. However, it seems that I am missing a step.
When I access this database using the command line, I SSH from the Linux machine to the NAS, mentioning the port where the database is located on the NAS.
Then I populate my credentials to login to the database, this works fine.
But when using Python 3.10 and the MariaDB connector, I only provide with my credentials to login to the database, so I feel like I am missing the SSH step to the NAS, at least this is my assumption.
How could I achieve that ? Can someone please help ?
Here is my script in Python:
import mariadb
import json
import sys
with open('config.json') as config_file:
config = json.load(config_file)['mariadb']
try:
conn = mariadb.connect(
user=config['raspi-svr']['user'],
password=config['raspi-svr']['password'],
host=config['raspi-svr']['host'],
port=config['raspi-svr']['port'],
database="test_db"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
cur = conn.cursor()
Here is the error message I am getting when running my script:
Error connecting to MariaDB Platform: Lost connection to server at 'handshake: reading initial communication packet', system error: 0
I tried running the MariaDB connector for Python.

Connect to IBM DB2 on Cloud using python api ibm_db

Can you please let me know how to connect to DB2 on IBM Cloud using python?
I have tried the below steps.
installed ibm_db using pip install ibm_db
Created a free tier Db2 service on IBM cloud
Generated Service credentials key
Trying to establish a connection with the database with the credential details (Database, host, port, user id, and password) extracted from the Service credentials key
import ibm_db
print("Creating connection.......")
conn_string = "DATABASE=bludb;HOSTNAME=54a2f15b-5c0f-46df-8954-7e38e612c2bd.c1ogj3sd0tgtu0lqde00.databases.appdomain.cloud;PORT=32733;PROTOCOL=TCPIP;UID=<userId>;PWD=<password>;"
conn = ibm_db.connect(conn_string,"","")
if conn:
print("Connection ...... [SUCCESS]")
else:
print("Connection ...... [FAILURE]")
I am getting below error message:
SQLCODE=-30082n: [IBM][CLI Driver] SQL30082N Security processing failed with reason "17" ("UNSUPPORTED FUNCTION"). SQLSTATE=08001
It seems like you are on the new Db2 on Cloud lite plan with non-standard ports and SSL enforced. When you connect to Db2 using the Python driver and use SSL, you have to add the SECURITY=SSL property, e.g.:
conn_string = "DATABASE=bludb;HOSTNAME=yourhostname;PORT=<port>;PROTOCOL=TCPIP;UID=<userId>;PWD=<password>;SECURITY=SSL"
I think the easy way to do this is with SQL Magic. This way, you can just type a SQL statement just by adding %sql before your query
First install the packages
!pip install sqlalchemy==1.3.9
!pip install ibm_db_sa
Then,
%load_ext sql
Finally, run the following code by replacing your username, password, hostname and SSL. You can find these in your IBM DB2 under credentials.
%sql ibm_db_sa://my-username:my-password#hostname:port/BLUDB?security=SSL
Now you can run any SQL by using %sql before or %%sql if the whole cell is going to be SQL. Example:
%sql SELECT * FROM TABLENAME;
or
%%sql
SELECT *
FROM TABLENAME;
There's a python package called ibm_db, does this link or (cited in the first one) this one help?

sqlalchemy with db2 and kerberos

How can I connect to my db2 database with sqlalchemy when the authentication is using kerberos?
When using pyodbc the connection string contains AuthenticationMethod=4, which lets kerberos handle the authentication and I don't need to provide username and password.
Is there a way to either pass a pyodbc.connect object directly into sqlalchemy or can I alternatively tell sqlalchemy to use kerberos?
My odbc connection string looks like this:
connstr = 'ApplicationUsingThreads=0;' \
...: 'FloatingPointParameters=0;' \
...: 'DoubleToStringPrecision=16;DB=NYRMPDI1;' \
...: 'AuthenticationMethod=4;' \
...: f'IpAddress={ip_address};' \
...: f'TcpPort={port};' \
...: f'DRIVER={driver_location}'
I can't find any way to pass this into sqlalchemy create_engine.
ibm_db_sa with an IBM Db2 driver supports kerberos connections with pyodbc, both DSN-LESS and DSN connection-strings, and it works with all three types of IBM Db2-driver (fat client, run-time-client, and ODBC and CLI driver). Different configurations are necessary for the fat-client+runtime-client, versus the ODBC and CLI client.
By default, unless you tell it otherwise, the installation of ibm_db_sa or ibm_db modules will install the IBM 'ODBC and CLI client'.
Your odbcinst.ini needs to define a driver-name (in my example I call it DB2CLI but you give it any name you prefer), and specify the library to load (example libdb2.so) from the correct path.
Here is an example of a DSN-LESS connection string, which you must urlencode before passing to create_engine():
CONNECTION_STRING=("DRIVER={DB2CLI};HOSTNAME=192.168.1.178;PORT=60000;KRBPLUGIN=IBMkrb5;AUTHENTICATION=KERBEROS;DATABASE=SAMPLE;")
quoted_connection_string=urllib.parse.quote_plus(CONNECTION_STRING)
engine = create_engine('ibm_db_sa+pyodbc:///?odbc_connect={}'.format(quoted_connection_string))
If you prefer a DSN connection, you must define all the details in the db2dsdriver.cfg and have a stanza for the dsn in the active odbc.ini that references the driver you configured in your odbcinst.ini, and you must specify only the DSN in the connection-string like this:
CONNECTION_STRING=("DSN=SAMPLE;")
engine = create_engine('ibm_db_sa+pyodbc:///?odbc_connect={}'.format(CONNECTION_STRING))
For DSN connections, it helps if you first get the kerberos connection working with isql defore you get it working with sqlalchemy because the troubleshooting seems easier.
I tested with these component versions:
ubuntu 16.04 LTS x64
python 3.6.8 in a virtualenv
ibm_db 3.0.1
ibm_db_sa 0.3.5
unixODBC 2.3.4
pyodbc 4.0.30
IBM Db2 data server driver 11.1.4.4a (optional)
IBM Db2 ODBC and CLI driver (default)
local and remote Db2-LUW servers whose Db2-instances are kerberized already.
Steps to try:
For DSN connections, configure your active db2dsdriver.cfg with dsn and database with parameter Authentication, parameter value Kerberos.
For the fat-client and runtime-client, configure your IBM Data Server Client CLNT_KRB_PLUGIN parameter to IBMkrb5 via db2 update dbm cfg using CLNT_KRB_PLUGIN IBMkrb5. (You don't need this step when using the ODBC and CLI driver).
Configure your active odbcinst.ini for Db2 to use the correct libdb2.so library as supplied by your Db2 client, and reference this driver-name either in your DSN-LESS python code, or in your odbc.ini for DSN-connections.
For DSN connections only, configure your active odbc.ini to use the Db2 driver specified in odbcinst.ini and mention Authentication = kerberos in your DSN stanza in odbc.ini.
For DSN connections, Omit any userid/password from the active odbc.ini file. For DSN-LESS connectiond you don't need any reference to the database in the odbc.ini or db2dsdriver.cfg.
For DSN connections only, Verify db2cli validate -dsn $YOURDSN -connect for a remote database completes successfully without a userid or password. This proves that the CLI layer is using kerberos.
(Optional) For Db2 fat client, or runtime client, verify you can connect to a catalogued remote database at the shell command line db2 connect to $YOUR_REMOTE_DATABASE (without needing to enter a userid/password). This proves that regular shell scripts can connect to the database with kerberos authentication.
If you are using either the Db2 fat client, or the Db2 runtime client then you need to dot in / source the correct db2profile before running either isql or your python script.

Connect to SQLServer with Pyodbc using Trusted Connection on OSX

Is it possible connect using local Domain credentials that I use to log into my OSX System to connect to a SQLServer DB with python, pyodbc, unixodbc, and FreeTDS like I would when connecting from a Windows system?
Windows Connection String that works:
pyodbc.connect('Trusted_Connection=yes', driver='FreeTDS', TDS_Version = 7.0, server='<SERVER>', port=<PORT>, database='<DATABASE>')
When I attempt this from a Mac I get the following error:
pyodbc.Error: ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)')
I am attempting to avoid hard coding usernames and passwords.
The Trusted_Connection setting indicates whether to use Windows Authentication Mode for login validation or not. Given that you're using a Mac, I suspect that Windows Authentication Mode will not be possible and so it will be necessary to pass the username and password to the connection string.

SQLAlchemy connects to SQLServer using Windows Authenticaton with pymssql driver

I can use pymssql to connect to SQLServer using Windows Authentication:
conn = pymssql.connect(host='..', database='..', trusted=True)
But how could I use SQLAlchemy to connect to SQLServer using Windows Authenticaton with pymssql driver?
The example given by SQLAlchemy is:
mssql+pymssql://<username>:<password>#<freetds_name>
Since I use Windows Authentication, I cannot manually set the username and password.
I do not have pymssql to check, but try the version below:
mssql+pymssql://<freetds_name>?trusted=True

Categories