I have run into another problem now, with below given code i am unable to login, it still says Access is Denied, even though the username and password is correct .No errors on the console. Looks like i am missing something after the connection.
All i am trying to do here is modify the TODO section so that it runs the computed query against my Oracle database after connecting and a successful login, it should show the results from permissions table.
import cgi
import cx_Oracle
print("Content-type: text/html\n")
print("<title>Test</title>")
print("<body><center>")
try:
# get post data
form = cgi.FieldStorage()
name = form['name'].value if 'name' in form else ''
pwd = form['pwd'].value if 'pwd' in form else ''
permissions = []
# query to check password and get permissions
query = "SELECT PERMISSIONS FROM USERS WHERE NAME='{}' and PWD='{}'".format(name, pwd)
# TODO: connect to database and run query
host = '123.abc.com'
port = 1521
SID = 'orcl'
dsn_tns = cx_Oracle.makedsn(host, port, SID)
connection = cx_Oracle.connect('abuser', 'userpass', dsn_tns)
curs = connection.cursor()
result = curs.execute(query)
# TODO section ends
if len(permissions) > 0:
print("<H1>Access granted. You have the following permissions: {}.</H1>".format(permissions[0][0]))
else:
print("<H1>Access denied.</H1>")
connection.close()
except cx_Oracle.DatabaseError as e:
# for ease of debugging
print("Database Error: {}".format(e))
print("<br>Query: {}".format(query))
print("""
<form action="../login.html" method="GET">
<input type="submit" value="Back to Login">
</form>
""")
print('</center></body>')
Your indent is too great starting on line 36 (I guess you uploaded partial source code), where it starts host =
There is an extra indent in the line starting with host. Indents in Python usually follow the :. The below code should fix the indentation error that you are getting. More about this here - http://www.diveintopython.net/getting_to_know_python/indenting_code.html
import cgi
import cx_Oracle
print("Content-type: text/html\n")
print("<title>Test</title>")
print("<body><center>")
try:
# get post data
form = cgi.FieldStorage()
name = form['name'].value if 'name' in form else ''
pwd = form['pwd'].value if 'pwd' in form else ''
permissions = []
# query to check password and get permissions
query = "select permissions from users where name='{}' and pwd='{}'".format(name, pwd)
# Connect to database and run query
host = '123.abc.com'
port = 1521
SID = 'orcl'
dsn_tns = cx_Oracle.makedsn(host, port, SID)
connection = cx_Oracle.connect('abcuser', 'abcuserpassword', dsn_tns)
results = connection.execute(query)
# TODO section ends
if len(permissions) > 0:
print("<H1>Access granted. You have the following permissions: {}.</H1>".format(permissions[0][0]))
else:
print("<H1>Access denied.</H1>")
except cx_Oracle.DatabaseError as e:
# for ease of debugging
print("Database Error: {}".format(e))
print("<br>Query: {}".format(query))
Related
I am developing a web app using Angular 9 for frontend and Flask in python 3.8 for backend, everything was going well till i tried to connect the backend with the data base, where the code apparently its ok, flask start running succesfully but when i tried to use my endpoint for authentication, flask throws the error:
**local variable 'conn' referenced before assignment**
i have been checking some forums and so on but i dont understand what is going on. Thanks in advance for your help.
import pymysql
database_name = "dbx80"
database_user = "user_auth"
database_password = "Jan2019#"
def conection_database(db):
try:
conn = (pymysql.connect(
unix_socket="/cloudsql/servicisEX:us-central1:dbx43",
port = 3306,
user = database_user,
password = database_password,
database = database_name,
charset="utf8"
))
print(f"Connection {database_name} Succesful")
except Exception as e:
print(f"Error connecting to {database_name}")
return conn
Converting comment to an answer.
return conn is called no matter the result of the try except block.
If you put the return statement inside the try block, the error will not occur.
Example:
import pymysql
database_name = "dbx80"
database_user = "user_auth"
database_password = "Jan2019#"
def conection_database(db):
try:
conn = (pymysql.connect(
unix_socket="/cloudsql/servicisEX:us-central1:dbx43",
port = 3306,
user = database_user,
password = database_password,
database = database_name,
charset="utf8"
))
print(f"Connection {database_name} Succesful")
return conn
except Exception as e:
print(f"Error connecting to {database_name}")
os.eviron['username'] is sent from OpenVPN, but for debugging I changed it to "test" as user in the Database.
os.eviron['password'] is sent from OpenVPN, but for debugging I changed it to the working password "password", and everything worked as designed.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import mysql.connector as database
import sys
import hashlib
from config import DB_NAME, DB_ADMIN, DB_PASSWORD, DB_HOST, HASH_ALGORITHM, HASH_SALTY
connection = database.connect(
user=DB_ADMIN,
password=DB_PASSWORD,
host=DB_HOST,
database=DB_NAME
)
cursor = connection.cursor()
hash_func = getattr(hashlib, HASH_ALGORITHM)
salty = hash_func(HASH_SALTY.encode("utf-8")).hexdigest()
ovpnuser = (os.environ['username'])
ovpnuser = "SELECT * FROM users WHERE usernames = '" + ovpnuser + "';"
cursor.execute(ovpnuser)
result = cursor.fetchone()
if result is None:
sys.exit(1)
id, usernames, passwords = result
passw = (os.environ['password'] + salty) #Salt this mofo
if hash_func(passw.encode("utf-8")).hexdigest() != passwords:
sys.exit(1)
sys.exit(0)
Now that I use OpenVPN to call this plugin as you see it now, it returns sys.exit(1) Failed to authenticate. I've tried to debug it, but I can't get ovpn to print and errors from connections or calls to this plugin. I even added echo to write to a log file in the python code, and it didn't work.
Any thoughts?
I want to get the column names in redshift using python boto3
Creaed Redshift Cluster
Insert Data into it
Configured Secrets Manager
Configure SageMaker Notebook
Open the Jupyter Notebook wrote the below code
import boto3
import time
client = boto3.client('redshift-data')
response = client.execute_statement(ClusterIdentifier = "test", Database= "dev", SecretArn= "{SECRET-ARN}",Sql= "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='dev' AND `TABLE_NAME`='dojoredshift'")
I got the response but there is no table schema inside it
Below is the code i used to connect I am getting timed out
import psycopg2
HOST = 'xx.xx.xx.xx'
PORT = 5439
USER = 'aswuser'
PASSWORD = 'Password1!'
DATABASE = 'dev'
def db_connection():
conn = psycopg2.connect(host=HOST,port=PORT,user=USER,password=PASSWORD,database=DATABASE)
return conn
How to get the ip address go to https://ipinfo.info/html/ip_checker.php
pass your hostname of redshiftcluster xx.xx.us-east-1.redshift.amazonaws.com or you can see in cluster page itself
I got the error while running above code
OperationalError: could not connect to server: Connection timed out
Is the server running on host "x.xx.xx..xx" and accepting
TCP/IP connections on port 5439?
I fixed with the code, and add the above the rules
import boto3
import psycopg2
# Credentials can be set using different methodologies. For this test,
# I ran from my local machine which I used cli command "aws configure"
# to set my Access key and secret access key
client = boto3.client(service_name='redshift',
region_name='us-east-1')
#
#Using boto3 to get the Database password instead of hardcoding it in the code
#
cluster_creds = client.get_cluster_credentials(
DbUser='awsuser',
DbName='dev',
ClusterIdentifier='redshift-cluster-1',
AutoCreate=False)
try:
# Database connection below that uses the DbPassword that boto3 returned
conn = psycopg2.connect(
host = 'redshift-cluster-1.cvlywrhztirh.us-east-1.redshift.amazonaws.com',
port = '5439',
user = cluster_creds['DbUser'],
password = cluster_creds['DbPassword'],
database = 'dev'
)
# Verifies that the connection worked
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
ver = results[0]
if (ver is None):
print("Could not find version")
else:
print("The version is " + ver)
except:
logger.exception('Failed to open database connection.')
print("Failed")
I am trying to connect to a remote Oracle database using Python.
I am able to access the database directly using DBeaver and I have copied the parameters in the Python code below from the "Connection Configuration --> Connection settings --> General" tab (which can be opened by right-clicking on the database and selecting "Edit connection"):
import cx_Oracle
host_name = # content of "Host"
port_number = # content of "Port"
user_name = # content of "User name"
pwd = # content of "Password"
service_name = # content of "Database" (the "Service Name" option is selected)
dsn_tns = cx_Oracle.makedsn(host_name, port_number, service_name = service_name)
conn = cx_Oracle.connect(user = user_name, password = pwd, dsn = dsn_tns)
However, I get the following error:
DatabaseError: ORA-12541: TNS:no listener
Other answers I found related to this question suggested modifying some values inside the listener.ora file, but I have no such file on my computer nor do I know where it can be retrieved. Does anyone have any suggestions?
There would be two reason for that error.
The database was briefly unavailable at the time when you tried to access
The Oracle client application on your machine is not configured correctly
I think thi config is not correct.
See the link : https://oracle.github.io/python-cx_Oracle/
ip = '192.168.1.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect('username', 'password', dsn_tns)
I'm attempting to develop a web app using tornado/torndb and am running into some issues with my database interactions. I've written a "Database" class which wraps torndb in order to provide some common database functionality for my web app. When invoking any of the methods from the Database class I've written there seems to be a problem with the connection to the database:
"ERROR:root:Error connecting to MySQL on localhost"
My constructor opens the connection so I'm a bit confused as to why I see this message after the connection has been opened. I expect this is a scoping and/or GC issue that I am not understanding. The goal is to to create the Database object once and thus just have that
single connection persist throughout the life of the server, the db is stored
The following code snippet does work as expected which led me to the scoping or GC issue possibly:
#!/usr/bin/python
import torndb
class Database:
def __init__(self):
try:
self.__dbh = torndb.Connection(
'localhost',
'mydb',
user = 'myuser',
password = 'mypass')
except Exception as e:
print e
def user_add(self, user, email, passwd):
insert = "INSERT INTO users (username, email, passwd) VALUES " + \
"(%s, %s, %s)" % (user, email, passwd)
rowid = 0
try:
rowid = self.__dbh.execute(insert)
except Exception as e:
print e
if rowid is 0:
return (False, 'User exists');
return (True, None)
if __name__ == "__main__":
print 'Testing'
raw_input('Hit enter to connect to the DB')
d = Database();
users = []
raw_input('Hit enter to create some users')
for i in range(5):
users.append(str(i))
d.user_add(users[i], users[i], users[i])
<- snip ->
The issue is when I try to create a Database object from anywhere other than the main of the module that defines the Database class, for example:
import tornado.ioloop
import tornado.httpserver
import tornado.web
from register import Register
from logon import Logon
from db import Database
class Application(tornado.web.Application):
def __init__(self):
resources = [
(r"/logon", Logon),
(r"/register", Register)
]
self.db = Database()
tornado.web.Application.__init__(self, resources)
try:
self.db.user_add('testuser', 'testemail', 'password')
except Exception as e:
print e
if __name__ == "__main__":
app = Application()
# Start the server.
server = tornado.httpserver.HTTPServer(app)
server.listen(8080)
tornado.ioloop.IOLoop.instance().start()
The above when executed prints (due to the call to self.__dbh.execute()):
ERROR:root:Error connecting to MySQL on localhost
Some other bits of information:
I can connect to the db from the console without any issues.
I'm following this example https://github.com/facebook/tornado/blob/master/demos/blog/blog.py#L60
torndb version is 2.4.1, torndb version is LATEST (pulled using pip).
Questions:
Why is there a difference when I create my Database object in the main of the module that defines the class compared to creating the Database object anywhere else?
The problem was due to the string arguments passed to the query not being escaped, with the following change it works:
def user_add(self, user, email, passwd):
insert = "INSERT INTO users (username, email, passwd) VALUES " + \
"(\'%s\', \'%s\', \'%s\')" % (user, email, passwd)
rowid = 0
try:
rowid = self.__dbh.execute(insert)
except Exception as e:
print e
if rowid is 0:
return (False, 'User exists');
return (True, None)