Connecting Python to Oracle Databases with `cx_Oracle` and ldap.

Yes, I feel your pain. Here’s a solution.

Michael Dunn
2 min readMar 2, 2017

Have you had this experience?

  • The Oracle team at your organization is encouraging/requiring applications to start connecting to the databases via LDAP instead of other traditional methods.
  • You lookup the cx_Oracle documentation and find that there isn’t anything on LDAP based connection strings.
  • Wah-wah. :(

Thankfully, I have a DBA friend named Raj who taught me about `sqlnet.ora` and `ldap.ora`.

Super cool DBA Raj

I sat down with Raj (I wish I had a cool name like Raj) who taught me a number of things about Oracle and we were able to get LDAP connections working with cx_Oracle. Here are the steps you’ll need to follow:

  • In order to install cx_Oracle, you’ll already have had to go through the pain of installing the Oracle instant client. (Yes Oracle, it is a pain.)

When you do that, it will create a directory called something like /opt/oracle/instantclient_12_1 which will the various files needed to interact with Oracle databases.

  • You need to set the $ORACLE_HOME environment variable to point to this directory.
  • Then create a network/admin subdirectory. In here you will create two files: sqlnet.ora and ldap.ora. Start with these examples:
# sqlnet.ora
# Place this file in the network/admin subdirectory or your
# $ORACLE_HOME location.
NAMES.DIRECTORY_PATH = (LDAP)

This file basically tells Oracle to look in the `ldap` file for connection string information. Another common value that you will see in there is TNSNAMES, but we will leave it like this for now.

# ldap.ora
# Place this file in the network/admin subdirectory or your
# $ORACLE_HOME location.
DIRECTORY_SERVERS = (your-server.your-organization:389:636)
DEFAULT_ADMIN_CONTEXT = "ldap-ou-designation"
DIRECTORY_SERVER_TYPE = OID

Alright, now obviously, you are going to need to get the correct values for the variables in the example here. Your DBA will need to provide them for you. Basically they will be given you information about the LDAP server which they have setup which gives out connection strings to connect with your organizations databases.

Now in your Python code…

Once you have ldap.ora and sqlnet.ora files setup, you’ll be able to connect inside your Python programs like as follows:

# PSA: Don't hardcode your credentials in your source code.  
# `safe_location` is just an example
import cx_Oracle
from safe_location import username, password, database_alias
your_connection = cx_Oracle.connect(
"{}/{}@{}".format(username, password, database_alias))

That’s it. Go conquer your Oracle/LDAP connection problems!

Credits
Raj Tiwari: https://www.linkedin.com/in/rt123/

--

--

Michael Dunn
Michael Dunn

Written by Michael Dunn

We can only win as a nation when we stop believing it will require some of our neighbors to lose.

Responses (2)