def Open(self, p_autocommit=True):
try:
self.v_con = psycopg2.connect(
self.GetConnectionString(),
cursor_factory=psycopg2.extras.DictCursor
)
self.v_con.autocommit = p_autocommit
self.v_cur = self.v_con.cursor()
self.v_start = True
# PostgreSQL types
self.v_cur.execute('select oid, typname from pg_type')
self.v_types = dict([(r['oid'], r['typname']) for r in self.v_cur.fetchall()])
if not p_autocommit:
self.v_con.commit()
self.v_con.notices = DataList()
except Spartacus.Database.Exception as exc:
raise exc
except psycopg2.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
python类connect()的实例源码
def oraclesql():
ipaddress='10.65.1.120'
username='sys'
password='ase_sys_n'
port='1521'
tnsname='dctest'
try:
db = cx_Oracle.connect(username+'/'+password+'@'+ipaddress+':'+port+'/'+tnsname ,mode=cx_Oracle.SYSDBA)
except Exception as e:
content= (tnsname+' is Unreachable,The reason is '+ str(e)).strip()
print (content)
else:
cursor = db.cursor()
data=oraclesql(cursor)
cursor.close()
db.close()
cursor.execute('select max(count(*)) from v$open_cursor group by sid')
data=cursor.fetchone()
return data
def get_conn(self):
"""
Returns a oracle connection object
Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora)
The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file)
or is a string like the one returned from makedsn().
:param dsn: the host address for the Oracle server
:param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS)
You can set these parameters in the extra fields of your connection
as in ``{ "dsn":"some.host.address" , "service_name":"some.service.name" }``
"""
conn = self.get_connection(self.oracle_conn_id)
dsn = conn.extra_dejson.get('dsn', None)
sid = conn.extra_dejson.get('sid', None)
mod = conn.extra_dejson.get('module', None)
service_name = conn.extra_dejson.get('service_name', None)
if dsn and sid and not service_name:
dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
elif dsn and service_name and not sid:
dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
else:
conn = cx_Oracle.connect(conn.login, conn.password, conn.host)
if mod is not None:
conn.module = mod
return conn
def connect(self):
self.initConnection()
self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
self.__dsn = utf8encode(self.__dsn)
self.user = utf8encode(self.user)
self.password = utf8encode(self.password)
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
logger.info("successfully connected as SYSDBA")
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
raise SqlmapConnectionException(msg)
self.initCursor()
self.printConnected()
def __init__(self, ip = IP, port = PORT, db = DB, user_name = USER_NAME, user_pass = USER_PASS):
super(OracleDB, self).__init__()
if STOP_ORCL:
return
if not hasattr(self,'conn'):
try:
self.conn = cx_Oracle.connect(user_name, user_pass, '%s:%d/%s'%(ip, port, db))#, threaded=True,events = True)
self.cursor = self.conn.cursor()
except Exception as e:
raise
else:
log.debug('?????? %s'%db)
def get_connect(self):
db = cx_Oracle.connect(self.username, self.password, self.host_string)
# print db.version
# versioning = db.version.split('.')
# if versioning[0] == '10':
# print "Running 10g"
# elif versioning[0] == '9':
# print "Running 9i"
# print db.dsn
# sql = 'SELECT * FROM' + self.table_name
# # cursor.execute('SELECT * FROM %s',str)
# cursor.execute(sql)
# # pprint(cursor.fetchall())
#
# # for row in cursor: ## notice that this is plain English!
# # print row
#
# column_data_types = cursor.execute('SELECT * FROM ADP_D_HOST')
#
# print column_data_types
#
# pprint(cursor.description)
return db.cursor()
def connect(self):
self.initConnection()
self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
self.__dsn = utf8encode(self.__dsn)
self.user = utf8encode(self.user)
self.password = utf8encode(self.password)
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
logger.info("successfully connected as SYSDBA")
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
raise SqlmapConnectionException(msg)
self.initCursor()
self.printConnected()
def connect(self):
self.initConnection()
self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
self.__dsn = utf8encode(self.__dsn)
self.user = utf8encode(self.user)
self.password = utf8encode(self.password)
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
logger.info("successfully connected as SYSDBA")
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
raise SqlmapConnectionException(msg)
self.initCursor()
self.printConnected()
def connect(self):
self.initConnection()
self.__dsn = cx_Oracle.makedsn(self.hostname, self.port, self.db)
self.__dsn = utf8encode(self.__dsn)
self.user = utf8encode(self.user)
self.password = utf8encode(self.password)
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password, mode=cx_Oracle.SYSDBA)
logger.info("successfully connected as SYSDBA")
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError):
try:
self.connector = cx_Oracle.connect(dsn=self.__dsn, user=self.user, password=self.password)
except (cx_Oracle.OperationalError, cx_Oracle.DatabaseError, cx_Oracle.InterfaceError), msg:
raise SqlmapConnectionException(msg)
self.initCursor()
self.printConnected()
def get_conn(self):
"""
Returns a oracle connection object
Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora)
The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file)
or is a string like the one returned from makedsn().
:param dsn: the host address for the Oracle server
:param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS)
You can set these parameters in the extra fields of your connection
as in ``{ "dsn":"some.host.address" , "service_name":"some.service.name" }``
"""
conn = self.get_connection(self.oracle_conn_id)
dsn = conn.extra_dejson.get('dsn', None)
sid = conn.extra_dejson.get('sid', None)
service_name = conn.extra_dejson.get('service_name', None)
if dsn and sid and not service_name:
dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
elif dsn and service_name and not sid:
dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
else:
conn = cx_Oracle.connect(conn.login, conn.password, conn.host)
return conn
def oracle_connect(self, mobile):
# ??????
t = time.strftime('%Y%m%d', time.localtime(time.time()))
# ??oracle????????
conn = cx_Oracle.connect('???/??')
cursor = conn.cursor()
# ?????SQL???????
sql = r"select * from (select sms_inf from gwadm.SMSTSMmO where mbl_no = " + "'" + mobile + "'" + " and tx_dt = " + t + " order by OPR_TM desc)where rownum <= 1"
cursor.execute(sql)
row = cursor.fetchone()
cursor.close()
conn.close()
code = []
# ??????????
for i in row[0]:
if i.isdigit():
code.append(i)
return ''.join(code)
def connect(username='stock', password='123456', host='localhost', port=1521, sid='orcl'):
# tns = cx_Oracle.makedsn(host, port, sid)
# con = cx_Oracle.connect(username, password, tns) # ?????
# cursor = conn.cursor() # ??cursor
# return cursor
cf = configparser.ConfigParser()
cf.read("..\\config\\config.conf")
oracleHost = str(cf.get("oracle", "ip"))
oraclePort = int(cf.get("oracle", "port"))
oracleUser = str(cf.get("oracle", "username"))
oraclePassword = str(cf.get("oracle", "password"))
oracleDatabaseName = str(cf.get("oracle", "databasename"))
oracleConn = oracleUser + '/' + oraclePassword + '@' + oracleHost + '/' + oracleDatabaseName
conn = cxo.connect(oracleConn)
return conn
# ????????
def add_ver_info(separate_files, connect_string, username):
"""add version information"""
f = None
if separate_files:
ver_file = os.path.join(SCHEMA_DIR, 'version.txt')
f = open_file_write(ver_file)
title = 'info'
print_start_info(title)
output_line('date: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), f)
output_line('connect string: %s' % (connect_string), f)
output_line('user: %s' % (username), f)
script_ver = __version__[5:-2]
output_line('created by: %s' % (script_ver), f)
print_stop_info(title)
show_qry('DB version', DB_VERSION_SQL, fout=f)
show_qry('DB name', 'SELECT ora_database_name FROM dual', fout=f)
sel_info_option = '--ver-info-sql'
for s in sys.argv[1:]:
if s.startswith(sel_info_option):
sel = s[len(sel_info_option):].strip('=')
try:
show_qry(sel, sel, fout=f)
except:
ex_info = traceback.format_exc()
serr = '\nSQL: %s\nException: %s\n' % (sel, ex_info)
print_err(serr)
break
show_qry('DB features used', FEATURE_USAGE_SQL, fout=f)
if f:
f.close()
def fuzzData(data, index):
global connection
for x in funnydata:
try:
if type(x) is int:
print "Data is number",x
else:
print "Data is " + str(x)[0:30] + " of length " + str(len(str(x)))
varList = []
for var in range(index):
varList.append(x)
cur = connection.cursor()
cur.execute(data, varList)
except:
error = str(sys.exc_info()[1])
if error.upper().find("ORA-00933") > -1 or error.upper().find("ORA-01756:") > -1 or error.upper().find("ORA-00923:") > -1:
print "*** POSSIBLE SQL INJECTION FOUND ***"
elif error.upper().find("ORA-03113") > -1:
if len(str(x)) > 50:
print "*** POSSIBLE BUFFER OVERFLOW ***"
else:
print "*** INSTANCE CRASHED ***"
print "Reconnecting ... "
connect()
elif error.upper().find("ORA-00600") > -1:
print "*** INTERNAL ERROR ***"
elif error.upper().find("PLS-00306:") > -1:
print "Currently unfuzzable :("
continue
elif error.upper().find("ORA-03114") > -1:
print "We are not connected :?"
connect()
print error
def get_new_connection(self, conn_params):
conn_string = convert_unicode(self._connect_string())
return Database.connect(conn_string, **conn_params)
def findTotal(patronID):
# function to get the total amount of fines owed for a patron, not just the weekly fines
# Does lookup based on patron id
sum = 0.0;
# make connection to the database
dsn = cx_Oracle.makedsn("localhost","1521","VGER")
con = cx_Oracle.connect(user="READ-ONLY-DBA-USER",password="READ-ONLY-DBA-PASS",dsn=dsn)
cur = con.cursor()
# run the query
query = """
SELECT sum(fine_fee_balance)
FROM fine_fee
WHERE patron_id='{pID}'
"""
cur.execute(query.format(pID=patronID));
try:
sum = cur.fetchone()[0]
except:
sum = 0.0
return sum
def findSSAN(patronID):
# function to get a users SSAN (bannerID) based on patronID
# returns String NONE if value is None (alumni users, etc)
# added to allow for banner id to go in summary, as per TKT-193
ssan = "NONE";
# make connection to the database
dsn = cx_Oracle.makedsn(db_host,db_port,db_SID)
con = cx_Oracle.connect(user=db_user,password=db_password,dsn=dsn)
cur = con.cursor()
# run the query
query = """
SELECT
pt.ssan
FROM
patron pt
WHERE
pt.patron_id IN ({pID})
"""
cur.execute(query.format(pID=patronID));
try:
ssan = cur.fetchone()[0]
except:
ssan = "NONE"
if ssan == None:
ssan = "NONE"
else:
ssan = "@" + ssan[1:]
return ssan;
def findItemType(barCode):
# function to get the type of an item, based on itemId.
# checks for temporary item ID being set, if so, returns that type instead
# Note: dicts field itemId isn't really itemId, it's item barcode
# dict's barcode field is PATRON barcode
itemType = "NONE";
# make connection to the database
dsn = cx_Oracle.makedsn(db_host,db_port,db_SID)
con = cx_Oracle.connect(user=db_user,password=db_password,dsn=dsn)
cur = con.cursor()
# run the query
query = """
SELECT
itt.item_type_name
FROM
item it,
item_type itt,
item_barcode ib
WHERE
ib.item_barcode IN ('{itemNumber}') AND
ib.item_id = it.item_id AND
itt.item_type_id = CASE WHEN (it.temp_item_type_id = '0') THEN it.item_type_id ELSE it.temp_item_type_id END
"""
cur.execute(query.format(itemNumber=barCode));
try:
itemType = cur.fetchone()[0]
except:
itemType = "NONE"
if itemType == None:
itemType = "NONE"
return itemType;
##########Utility Functions
def Open(self, p_autocommit=True):
try:
self.v_con = sqlite3.connect(self.v_service, self.v_timeout)
#self.v_con.row_factory = sqlite3.Row
self.v_cur = self.v_con.cursor()
if self.v_foreignkeys:
self.v_cur.execute('PRAGMA foreign_keys = ON')
self.v_start = True
except sqlite3.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
self.v_con = sqlite3.connect(self.v_service, self.v_timeout)
#self.v_con.row_factory = sqlite3.Row
self.v_cur = self.v_con.cursor()
if self.v_foreignkeys:
self.v_cur.execute('PRAGMA foreign_keys = ON')
self.v_start = True
except sqlite3.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
self.v_con = pymysql.connect(
host=self.v_host,
port=int(self.v_port),
db=self.v_service,
user=self.v_user,
password=self.v_password,
cursorclass=pymysql.cursors.DictCursor)
self.v_cur = self.v_con.cursor()
self.v_start = True
except pymysql.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
self.v_con = pymysql.connect(
host=self.v_host,
port=int(self.v_port),
db=self.v_service,
user=self.v_user,
password=self.v_password,
cursorclass=pymysql.cursors.DictCursor)
self.v_cur = self.v_con.cursor()
self.v_start = True
except pymysql.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
self.v_con = cx_Oracle.connect('{0}/{1}@{2}:{3}/{4}'.format(
self.v_user,
self.v_password,
self.v_host,
self.v_port,
self.v_service
))
self.v_cur = self.v_con.cursor()
self.v_start = True
except cx_Oracle.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
self.v_con = pymssql.connect(
host=self.v_host,
port=int(self.v_port),
database=self.v_service,
user=self.v_user,
password=self.v_password
)
self.v_cur = self.v_con.cursor()
self.v_start = True
except pymssql.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Open(self, p_autocommit=True):
try:
c = ibm_db.connect(self.GetConnectionString(), '', '')
self.v_con = ibm_db_dbi.Connection(c)
self.v_cur = self.v_con.cursor()
self.v_start = True
except ibm_db.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except ibm_db_dbi.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def get_new_connection(self, conn_params):
conn_string = convert_unicode(self._connect_string())
return Database.connect(conn_string, **conn_params)
def get_new_connection(self, conn_params):
conn_string = convert_unicode(self._connect_string())
return Database.connect(conn_string, **conn_params)
def get_new_connection(self, conn_params):
conn_string = convert_unicode(self._connect_string())
return Database.connect(conn_string, **conn_params)
def __init__(self, _resource=None, _connect = True):
"""
:param _resource: A resource object to read settings from
:param _connect: Also connect to the database (default:True)
"""
self.on_connect = None
if _resource is not None:
self.resource = _resource
self.read_resource_settings(_resource)
if _connect:
self.connect_to_db()
def get_connect(self):
db = cx_Oracle.connect(self.username, self.password, self.host_string)
return db.cursor()