Python will not connect to database - python

I'm trying to connect to a database via python. I keep getting this error when trying to run the code in python:
DatabaseError: ORA-12154: TNS:could not resolve the connect identifier specified
I know the tns settings are good because I can connect to the database via sql developer using the same computer. What's wrong with Python.
host = '205.218.7.153'
port = '1521'
sid= 'pdevl3'
username = 'uname'
password = 'pwd'
connect_str = username + '/' + password + '#' + host + ':' + port + '/' + sid
orcl = cx_Oracle.connect(connect_str)
curs = orcl.cursor()
curs.execute(query2)
rows = curs.fetchall()
curs.close()

Instead of building the string yourself, try using cx_Oracle to help build it for you:
import cx_Oracle
host = '205.218.7.153'
port = '1521'
sid= 'pdevl3'
username = r'uname' # make sure to use an r string if you have any special characters
password = r'pwd'
dsn_tns = cx_Oracle.makedsn(host, port, service_name=sid)
orcl = cx_Oracle.connect(user=username, password=password, dsn=dsn_tns)

Related

Connect to MongoDB Database using Python

I am new in using python and I want to try first connecting to mongodb database using python
This is my code but is has error
import pymongo
DATABASE_NAME = "testdb"
DATABASE_HOST = "mongodb://10.10.100.100:22222"
DATABASE_USERNAME = "testuserid"
DATABASE_PASSWORD = "testpass"
try:
myclient = pymongo.MongoClient(DATABASE_HOST)
myclient.test.authenticate( DATABASE_USERNAME , DATABASE_PASSWORD )
mydb = myclient[DATABASE_NAME]
print("[+] Database connected!")
except Exception as e:
print("[+] Database connection error!")
raise e
10.10.100.100 is just my sample address and also 22222 is sample port
DATABASE_URI = f"mongodb://{DATABASE_USERNAME}:{DATABASE_PASSWORD}#{DATABASE_HOST}"
myclient = pymongo.MongoClient(DATABASE_URI)

cx_Oracle: How do I connect to Oracle when you use a Wallet?

Here is the code in the file con = cx_Oracle.connect('/#database_name').
This is setup to use my oracle wallet but its not working for some reason (giving me login denied). How do I enter my user name and password in this line of code? con = cx_Oracle.connect('/#database_name')
You should take a look on
https://cx-oracle.readthedocs.io/en/latest/user_guide/connection_handling.html#establishing-database-connections
To use a wallet with cx_Oracle, you need first to configure the wallet, create the sqlnet.ora and tnsnames.ora files, and you need to use the dsn property
connection = cx_Oracle.connect(dsn="mynetalias", encoding="UTF-8")
Where mynetalias is the TNS entry in your tnsnames.ora
mynetalias =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = yourhost )(PORT = yourport))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = yourservicename)
)
)
Be sure to have the sqlnet.ora configured for using the wallet
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY = /your_wallet_path_directory)
)
)
SQLNET.WALLET_OVERRIDE = TRUE
You can use below,
import cx_Oracle
ip = '192.168.0.1'
port = 1521
service_name = 'my_service'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name)
db = cx_Oracle.connect('user', 'password', dsn)

Issues with connecting to Postgres DB via SSH in Python

I've been given a postgres DB in my uni project in which I have to SSH into the network from which I can then access the DB. I've set up the connection in DBeaver using the SSH tab and it works perfectly fine. However, using Python, I can connect to the SSH just fine, but cannot connect to the DB itself. I've checked with another DB that doesn't require SSH and that works just fine. Here is my code. Note: I've already tried using SSHTunnel, too, to no avail. Also, ignore my quick hack to anonymize my SSH login data, as I didn't find how to use a proper config file with paramiko late at night yesterday...
import os
from psycopg2 import connect, Error
from paramiko import SSHClient
from config import config
with open("ssh_config.txt", "r") as f:
lines = f.readlines()
hostname = lines[0].strip()
username = lines[1].strip()
password = lines[2].strip()
ssh = SSHClient()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.connect(hostname=hostname, username=username, password=password)
print("SSH connected.")
try:
params = config()
conn = connect(**params)
cursor = conn.cursor()
print("DB connected.")
# Print PostgreSQL connection properties.
print(conn.get_dsn_parameters(), "\n")
# Print PostgreSQL version.
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record, "\n")
except (Exception, Error) as error:
print("Error while connecting to PostgreSQL", error)
Any help would be appreciated. Thanks!
I've figured it out myself. Here is the updated code. Basically, I had to forward the remote address to localhost and then connect to localhost instead of the DB address.
from psycopg2 import connect, Error
from sshtunnel import SSHTunnelForwarder
from config import config
with open("ssh_config.txt", "r") as f:
lines = f.readlines()
hostname = lines[0].strip()
username = lines[1].strip()
password = lines[2].strip()
remote_bind_address = lines[3].strip()
try:
with SSHTunnelForwarder(
(hostname, 22),
ssh_username=username,
ssh_password=password,
remote_bind_address=(remote_bind_address, 5432),
local_bind_address=("localhost", 8080)) \
as tunnel:
tunnel.start()
print("SSH connected.")
params = config()
conn = connect(**params)
cursor = conn.cursor()
print("DB connected.")
# Print PostgreSQL connection properties.
print(conn.get_dsn_parameters(), "\n")
# Print PostgreSQL version.
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record, "\n")
cursor.close()
conn.close()
tunnel.close()
print("DB disconnected.")
except (Exception, Error) as error:
print("Error while connecting to DB", error)

Unable to connect Python to Oracle

I want to connect Python to local Oracle with cx_Oracle. I know that in order to make the connection, I should know the local IP, port and SID. So I get these information through the following steps:
local IP:
import socket
#get local IP:
localhost = socket.gethostbyname(socket.gethostname())
port:
This is from my listener.ora so I use port 1521.
# listener.ora Network Configuration File: C:\app\413022472\product\12.2.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = C:\app\413022472\product\12.2.0\dbhome_1)
(PROGRAM = extproc)
(ENVS = "EXTPROC_DLLS=ONLY:C:\app\413022472\product\12.2.0\dbhome_1\bin\oraclr12.dll")
)
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = DESKTOP-2RE9AJU.local)(PORT = 1521))
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
)
DEFAULT_SERVICE_LISTENER = (orcl)
sid:This bothers me a lot. I tried a lot but still can't get the correct sid. This is from my tnsnames.ora:
# tnsnames.ora Network Configuration File: C:\app\413022472\product\12.2.0\dbhome_1\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = DESKTOP-2RE9AJU.local)(PORT = 1521))
ORACLR_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
)
(CONNECT_DATA =
(SID = CLRExtProc)
(PRESENTATION = RO)
)
)
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
This is what I got when running select instance_name from v$instance; in sqlplus:
INSTANCE_NAME
--------------------------------
orcl
I tried the following:
import cx_Oracle
import socket
#get local IP:
localhost = socket.gethostbyname(socket.gethostname())
#generate dsn:
dsn = cx_Oracle.makedsn(localhost, '1521', service_name = 'orcl')
#make connection:
conn = cx_Oracle.connect("c##scott", "tiger", dsn)
Which gives me:DatabaseError:ORA-12514, TNS:listener does not currently know of service requested in connect descriptor
I also tried dsn = cx_Oracle.makedsn(localhost, '1521', sid = 'orcl')
Which gives me:ORA-12505: TNS:listener does not currently know of SID given in connect descriptorD
I should tell that I changed the text in listener.ora and tnsnames.ora but I can't remember the details. Could anyone help me make the connection success?
In listeners, there are many things that effect in creating a connection.
Below is the content of "listener.ora" file as per my system.
Before that verify your hostname is valid or not by using "hostname" in command prompt. Before replacing the content of listener file takes a copy of your existing listener.ora file. Once you modified the listener.ora file then restarts the listener and Oracle service as well.
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = DESKTOP-2RE9AJU.local)(PORT = 1521))
)
)
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = CLRExtProc)
(ORACLE_HOME = C:\app\413022472\product\12.2.0\dbhome_1)
(PROGRAM = extproc)
(ENVS = "EXTPROC_DLLS=ONLY:C:\app\413022472\product\12.2.0\dbhome_1\bin\oraclr12.dll")
)
(SID_DESC =
(GLOBAL_DBNAME = orcl.com)
(ORACLE_HOME =C:\app\413022472\product\12.2.0\dbhome_1)
(SID_NAME = orcl)
)
)
DEFAULT_SERVICE_LISTENER = (orcl)
I would use a snippet from this Oracle tutorial (remember to change user/pass accordingly).
import cx_Oracle
con = cx_Oracle.connect('pythonhol/welcome#127.0.0.1/orcl')
print con.version
con.close()
Here's the link to the official cx_Oracle Documentation.
As a last thing, at this GitHub URL you can find several updated examples that could be of help in speeding up your work.
From my experience this can be a really frustrating error to debug. You probably solved the error but l'll add my solution here for anyone who struggles with a similar error connecting to Oracle through cx_Oracle.
Important points to note here:
Although this is a database error, it would not be solved by killing and restarting the database listened service, it is to do with our connection through cx_
Make sure the Oracle client and Python have the same architectures, either both are 32 bit or both are 64 bit. Here's how you can check your Python architecture:
import platform platform.architecture()
Make sure the environment path variable has the complete path of the Oracle client till the bin folder.
Make sure to set the TNS_ADMIN variable to where the TNS file exists.
Connection:
import cx_Oracle conn = cx_Oracle.connect('<username>','<password>','<service name variable in your TNS file>')
This method uses the connection details provided in the TNS file and cx_Oracle accesses the host and port details from the file itself.

Python ldap connection test

I want to be able to test that a connection to a host and port is valid.
I'm using the current line:
ldapObject = ldap.open(host="host", port=389)
This seems to return an instance. I need to determine if it can find the host or not?
Any suggestions?
open is deprecated.
This is a working example. See if this helps.
def ldap_initialize(remote, port, user, password, use_ssl=False, timeout=None):
prefix = 'ldap'
if use_ssl is True:
prefix = 'ldaps'
# ask ldap to ignore certificate errors
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
if timeout:
ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, timeout)
ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
server = prefix + '://' + remote + ':' + '%s' % port
conn = ldap.initialize(server)
conn.simple_bind_s(user, password)
return conn
Found a solution:
import ldap
try:
ldapObject = ldap.open(host="host", port=389)
ldapObject .simple_bind_s()
except ldap.SERVER_DOWN:
print("Failed")

Categories