def _query(urlpath, req={}, conn=None, headers={}): """Low-level query handling. Arguments: urlpath -- API URL path sans host (string, no default) req -- additional API request parameters (default: {}) conn -- kraken.Connection object (default: None) headers -- HTTPS headers (default: {}) """ url = API_HOST + urlpath if conn is None: conn = connection.Connection() ret = conn._request(url, req, headers) print "111", ret return json.loads(ret)
def __init__(self, client_id, username=None, password=None, host_ip=None, qos=0): self.__username = username self.__client_id = client_id self.__password = password self.__host_ip = host_ip self.__topic_publish = "" self.__message_publish = "" self.__topics = [] self.__unsubscribe_topics = [] self.__connection = conn.Connection() self.__is_connected = False self.__struct = packet_struct() self.__qos = qos
def main(): arg = parser.parsArg() if (arg.debug): logging.basicConfig(stream=sys.stdout, format='%(asctime)s - %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) else: logging.basicConfig(stream=sys.stdout, format='%(asctime)s - %(message)s', datefmt='%H:%M:%S', level=logging.INFO) logging.info('Slow Loris Attack Started') target_info = Target(arg.addr, arg.port, arg.sockets) connection = con.Connection(target_info) connection.retrieve_ws() connection.start_attack()
def _create_connection(self, sock): # socket, dict, directors queue, sending queue send_queue = queue.Queue() message = {'msg': 'REQUEST_PARTS_LIST'} send_queue.put(message) # Using deep copy to ensure there are no race conditions on orch dict con = connection.Connection(sock, copy.deepcopy(self.orch_dict), send_queue, self.director_queue) con.start() # Add to up the dictionaries ip, _ = sock.getpeername() self.connections_ip_dict[con] = ip # self.ip_connections_dict[ip] = con self.connections_parts_dict[con] = 0 self.connections_queue_dict[con] = send_queue
def _query(self, urlpath, req={}, headers={}): """Low-level query handling. Arguments: urlpath -- API URL path sans host (string, no default) req -- additional API request parameters (default: {}) conn -- kraken.Connection object (default: None) headers -- HTTPS headers (default: {}) """ url = self.uri + urlpath if self.conn is None: self.conn = connection.Connection(self.api) ret = self.conn._request(url, req, headers) return json.loads(ret)
def __create_pg_connection(self, address, context): redirect_config = self.instance_config.redirect pg_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) pg_sock.connect((redirect_config.host, redirect_config.port)) pg_sock.setblocking(False) events = selectors.EVENT_READ | selectors.EVENT_WRITE pg_conn = connection.Connection(pg_sock, name = redirect_config.name + '_' + str(self.num_clients), address = address, events = events, context = context) logging.info("initiated client connection to %s:%s called %s", redirect_config.host, redirect_config.port, redirect_config.name) return pg_conn
def connection_init(self, dest_addr): port = random.randint(4000, 65535) nodes = random.sample(self.tor_network.node_list, 3) self.log_write("console", "nodes: {}".format("\t".join([str(i) for i in nodes]))) new_connection = connection.Connection(nodes[0].ip_address, port, None, dest_addr) new_connection.nodes = nodes # generate symmetric keys and initialization vectors for _ in range(3): new_connection.symmetric_keys.append(os.urandom(16)) new_connection.init_vectors.append(os.urandom(16)) self.connection_list.append(new_connection) # initialize connection with first node data = self.splitter.join([ nodes[1].ip_address.encode(), new_connection.symmetric_keys[0], new_connection.init_vectors[0] ]) data = rsa_encrypt(nodes[0].public_key, data) self.form_and_send_packet(nodes[0].ip_address, port, data) # initialize connection with second node data = self.splitter.join([ nodes[2].ip_address.encode(), new_connection.symmetric_keys[1], new_connection.init_vectors[1] ]) data = rsa_encrypt(nodes[1].public_key, data) data = device.aes_encrypt(new_connection.symmetric_keys[0], new_connection.init_vectors[0], data) self.form_and_send_packet(nodes[0].ip_address, port, data) # initialize connection with third node data = self.splitter.join([ dest_addr.encode(), new_connection.symmetric_keys[2], new_connection.init_vectors[2], b"" ]) data = rsa_encrypt(nodes[2].public_key, data) data = device.aes_encrypt(new_connection.symmetric_keys[1], new_connection.init_vectors[1], data) data = device.aes_encrypt(new_connection.symmetric_keys[0], new_connection.init_vectors[0], data) self.form_and_send_packet(nodes[0].ip_address, port, data)
def serve(self): """ Loop principal del servidor. Se acepta una conexión a la vez y se espera a que concluya antes de seguir. """ # Set up the poller p = select.poll() p.register(self.srsocket, select.POLLIN) clients = {} while True: events = p.poll() print events for fileno, event in events: if fileno == self.srsocket.fileno(): if event & select.POLLIN: c_socket, c_adress = self.srsocket.accept() c_socket.setblocking(0) p.register(c_socket, select.POLLIN) c_fileno = c_socket.fileno() clients[c_fileno] = connection.Connection( c_socket, self.directory) print('New client: ' + str(c_adress)) else: if event & select.POLLIN: conn = clients[fileno] conn.handle_input() if conn.remove: p.unregister(fileno) del clients[fileno] conn.socket.close() else: p.modify(fileno, select.POLLIN | select.POLLOUT) print(fileno, select.POLLIN | select.POLLOUT) elif event & select.POLLOUT: conn = clients[fileno] conn.handle_output() if conn.remove: p.unregister(fileno) del clients[fileno] conn.socket.close() else: p.modify(fileno, select.POLLIN) print p
def __init__(self, maxPlayers, myPort): """ maxPlayers is the maximum number of players we'll allow. myPort is the socket port# """ # Call the base-class constructor #threading.Thread.__init__(self) # Server attributes self.maxPlayers = maxPlayers self.serverPort = myPort # "Tweak" values the control operations on the server self.heartbeatTimer = 0.0 self.heartbeatCounter = 0 self.heartbeatFreq = 0.5 self.logLevel = 3 # 0 = Server startup/shutdown messages # 1 = Connection made/lost/new-account/login # messages and below # 2 = changes to dbase buffer/file # 3 = Updates to/from clients and below # 4 = Heartbeats and below # 5 = Pings and below # 6 = Debug info and below # A list of ID-msg pairs. We'll process this in our 'main' loop self.pendingMessages = [] self.pendingMessagesSemaphore = threading.Semaphore(1) self.connectionSemaphore = threading.Semaphore(1) # The database -- when a client joins / leaves this will be synced self.dbase = {} self.dbase_fname = "dbase.dat" # Information on connected clients self.clientNextID = 0 self.clients = {} # All game data we want to represent on the server goes here... self.players = {} # The player objects # The thread responsible for listening for data self.connection = connection.Connection() self.connection.setListener(self) self.connection.createSocket(self.serverPort) print("Starting connection")
def route_packet(self, data, address): # make sure that no one change the connections list self.mutex.acquire() for conn in self.connections: # if the packet is from this client if conn.is_remote_address(address): result = conn.handle_outgoing_packet(data) self.mutex.release() if result == None: self.end_connection(conn) return # if no connection exists, create a new one if len(self.connections) < self.config.config.MAX_CLIENTS: conn = connection.Connection(self, address, self.config.config) conn.handle_outgoing_packet(data) self.connections.append(conn) # release the mutex self.mutex.release() conn.handshake()
def receive_item(self, project_name, req_id, receive_vm_num, receive_network_num, info): receive_time = format_time(time.time()) get_id_sql = ("select id from task where project = '%s';") % ( project_name) conn = None task_id = None try: conn = connection.Connection(conf_dict=self.db_conf) conn.execute(get_id_sql) ret = conn.fetchone() task_id = ret[0] except MySQLdb.Error, e: conn.close() DBLOG.error( "database.receive_item - project-%s req-%s receive item fail, " "can't get task id:%s" % (project_name, req_id, str(e))) return False, str(e)
def test_default_administrator_read_current_user(self): conn = connection.Connection() # First log in success = conn.login("http://127.0.0.1:5000/api", "administrator", {"password": "******"}) self.assertTrue(success) # And then read the current user success = conn.call_get_method("/usermanagement/user") self.assertTrue(success) user = json.loads(conn.last_response_message.text) self.assertIsNotNone(user) self.assertEqual(user["id"], self.__admin_user_id) self.assertEqual(user["user_name"], "administrator") self.assertEqual(user["display_name"], "Administrator") self.assertEqual(user["email"], "") self.assertEqual(user["active"], True)
def __init__(self, getdevicesonwake=True, makeonlydevicecurrent=True): # The connection that will be used to communicate with the Roku devices # on the network. # Unless "False" is passed, this will automatically find and hold a list # of Roku device IP addresses. To get the addresses, call # self.connection.get_devices() -- returns a list self.connection = connection.Connection(getdevicesonwake) self.current_device = None if getdevicesonwake: self.gather_roku_devices(makeonlydevicecurrent) if makeonlydevicecurrent: if len(self.devices) > 0: self.current_device = self.devices[0] else: self.devices = [] # The keyboard parser self.keyboard = keyboard_parser.KBoard()
def serve(self): """ Loop principal del servidor. Se acepta una conexión a la vez y se crea un hilo para atenderla. """ while True: try: conn_sock, client_addr = self.listener_sock.accept() conn = connection.Connection(conn_sock, self.directory) conn_thread = Thread(target=conn.handle, daemon=True) conn_thread.start() print("[%i] Connection from %s\n" % (active_count() - 1, client_addr[0])) except KeyboardInterrupt: print("\nServer stopped\n") break self.listener_sock.close()
def connect(self, host, port): """ Called by client code - socket and connection threads should not touch! blocks while attempting to establish a connection with specified server Return: a Connection instance (if successful) or an error Errors: if socket closed, throw exception """ self.connectionsLock.acquire() newConn = connection.Connection(self.sock.getsockname()[1], port, self.maxWindowSize, connection.STATE.SYN_SENT, host, self) self.connections[(host, port)] = newConn self.connectionsLock.release() newConn.establishConnection() debugLog("new connection created with: " + host + " on port " + str(port)) return newConn
def wait_for_auth(self): """ Method to check and perform auth The method returns imeediately if session ids missmatch or the stop event is set """ #check whether we have a conflict in session ids, if so we can return immediately and connect again if self.session_id != api.session.cookies.get( 'SessionID') or self.is_stop or self.univ.stop_event.is_set(): return #try to set auth status, if another thread has done it already we dont have to do anything #else we reset the post event and reauthenticate if api.session.auth_status(api.AuthStatus.UNAUTHORIZED): api.session.set_events(post_event=False) connection.Connection().reconnect() #reauthenticate if self.univ.post_event.is_set() == False: _log.debug('%s waiting for post event' % self.name) self.univ.post_event.wait()
def playUnknown(self, videoInput, movie): optExp3D = False setting = settings.StereoscopicSettings() if setting.switcherExp == 'true': xbmcPlayer = xbmc.Player() optExp3D = True Player = xbmc3Dplayer.StereoscopicPlayer() conn = connection.Connection() #check = Player.checkFile(self.settings.mediainfoLocation, movie) check = Player.checkFile(setting.mediainfoLocation, movie) pathMovie = conn.connection(movie) #Player.playStereoUnknown(self.settings.playerLocation, pathMovie, videoInput, self.settings.outputVideo, self.settings.audioLang. self.settings.subtitleLang, self.settings.subtitleSize, self.settings.subtitleCoding, self.settings.subtitleColor) Player.playStereoUnknown(setting.playerLocation, pathMovie, videoInput, setting.outputVideo, setting.audioLang, setting.subtitleLang, setting.subtitleSize, setting.subtitleCoding, setting.subtitleColor, setting.subtitleParallax, optExp3D) if setting.switcherExp == 'true': xbmcPlayer.play(pathMovie) conn.exit(movie)
def start_task(self, project_name, req_id, start_time, network_info, vm_info, network_num, vm_num): # start_time = format_time(time.time()) update_sql = ( "update task set status = 'START', start_time = '%s'," "network_info = '%s', vm_info = '%s', vm_num = %d, network_num = %d " "where project = '%s';") % (start_time, network_info, vm_info, vm_num, network_num, project_name) #print update_sql conn = None try: conn = connection.Connection(conf_dict=self.db_conf) conn.execute(update_sql) conn.commit() conn.close() except MySQLdb.Error, e: conn.close() DBLOG.error( "database.start_task - project-%s req-%s start task fail:%s" % (project_name, req_id, str(e))) return False, str(e)
def serve(self): """ Loop principal del servidor. Se aceptan multiples conexiones y se atienden en simultaneo. """ # Poll object p = select.poll() p.register(self.server_socket, select.POLLIN) while True: for connec in self.connections.values(): client_socket = connec.get_socket() if connec.to_remove(): print("Disconnecting client: " + str(connec.address)) self.connections.pop(client_socket.fileno()) p.unregister(client_socket) client_socket.close() else: p.modify(client_socket, connec.events()) events = p.poll() for fileno, event in events: if fileno == self.server_socket.fileno(): if event & select.POLLIN: (client_socket, client_address) = self.server_socket.accept() client_socket.setblocking(0) p.register(client_socket, select.POLLIN) connec = connection.Connection(client_socket, self.directory, client_address) self.connections[client_socket.fileno()] = connec print('New client: ' + str(client_address)) else: if event & select.POLLIN: self.connections[fileno].handle_input() if event & select.POLLOUT: self.connections[fileno].handle_output()
def init(self): self._client = connection.Connection() self._online = self.is_online() self._private = self.is_private() if self._error: logging.debug('[Model.init] ' + self._id + ' does not exist on site') return status_string = '' if DEBUGGING: status_string = '\t[Model.init]\t' status_string = status_string + "online:" + str( self._online) + " | private:" + str( self._private) + " -> model initialized" if self._online and not self._private: self.write_log( status_string + " and starting recording | gender: " + self._gender, REC_START) self._start_recording()
def get_top_three_articles(): # create a connection conn = connection.Connection() # get the cursor db_cursor = conn.get_connection() path_folder = "/article/" # query to be run query = "SELECT title, count(*) as count FROM articles " \ "INNER JOIN log ON articles.slug = substring(log.path,LENGTH ('{0}')+1) " \ "GROUP BY title " \ "order by count desc " \ "LIMIT 3;".format(path_folder) # execute the query db_cursor.execute(query) # result will hold the results of the query result = db_cursor.fetchall() # close the connection del db_cursor return result
def call_session(self, py_dict): """ Wrapper method for startsession, stopsession, getsession result @param py_dict containing all keywords controller the tool behavior @return result obj or schema object """ pylogger.debug( "Called DiskIO session with operation {0:s}".format(py_dict)) operation = py_dict['operation'] cli_client = self.create_cli_client() if (operation.lower() == "startsession"): ssh_connection = connection.Connection(self.test_disk.controlip, self.test_disk.username, self.test_disk.password, "None", "ssh") pylogger.debug("Created new ssh_connection %s" % ssh_connection) cli_client.set_connection(ssh_connection.anchor) return self.start_session(cli_client) if (operation.lower() == "stopsession"): return self.stop_session(cli_client) if (operation.lower() == "getsessionresult"): return self.get_session_result(cli_client)
def __init__(self, strXMLname, strFallbackPath, strDefaultName, forceFallback=0): addon = xbmcaddon.Addon(__scriptID__) self.player = xbmc3Dplayer.StereoscopicPlayer() self.conn = connection.Connection() TAB_PREFS['prog'] = addon.getSetting('player_location') TAB_PREFS['mediainfo'] = addon.getSetting('mediainfo_location') TAB_PREFS['file1'] = '"' + xbmc.getInfoLabel( "ListItem.FileNameAndPath") + '"' TAB_PREFS['output'] = self.player.getOutputFormat( addon.getSetting('output_video')) TAB_PREFS['audio'] = self.getLang() TAB_PREFS['subtitle'] = self.getLang() TAB_PREFS['subsize'] = addon.getSetting('subtitle_size') TAB_PREFS['subenc'] = addon.getSetting('subtitle_coding') TAB_PREFS['subcolor'] = addon.getSetting('subtitle_color') TAB_PREFS['subparallax'] = addon.getSetting('subtitle_parallax') TAB_PREFS['switcher'] = addon.getSetting('chooser') TAB_PREFS['switcherexp'] = addon.getSetting('chooser_exp')
def create_connection(self, packet): raw_data = packet[3] try: data = rsa_decrypt(self.private_key, raw_data).split(self.splitter) except ValueError: return next_port = random.randint(4000, 65535) next_addr = data[0].decode() new_connection = connection.Connection(packet[0], packet[2], next_port, next_addr) new_connection.symmetric_keys.append(data[1]) new_connection.init_vectors.append(data[2]) try: new_connection.is_end_node = True if data[3] == b"" else False except IndexError: pass self.connection_list.append(new_connection) self.log_write( "console", "{}:\trcv/new/con from: {}\tto: {}\tlength: {}\tdata: {}".format( self, new_connection.source_addr, new_connection.dest_addr, len(self.splitter.join(data)), self.splitter.join(data)))
def get_result(self, project_name, req_id): ret, status = self.get_status(project_name, req_id) if ret == False: DBLOG.error( "databtase.get_result - project-%s req-%s get result fail:%s" % (project_name, req_id, status)) return ret, status if status != "END" and status != "EXPIRED": DBLOG.error( "databtase.get_result - project-%s req-%s get result fail:task not end(%s)" % (project_name, req_id, status)) return False, "task not end:" + status conn = None try: conn = connection.Connection(conf_dict=self.db_conf) except MySQLdb.Error, e: DBLOG.error( "databtase.get_result - project-%s req-%s get status fail: %s" % (project_name, req_id, str(e))) return False, str(e)
def load_bots(config_filename): """Load the bots defined in the config file """ # Find all the bots in the scripts folder script_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scripts') for script_file in os.listdir(script_dir): if not script_file.endswith('.py'): continue script_name = os.path.splitext(script_file)[0] module_name = 'pyrobot.bot.scripts.' + script_name module = my_import(module_name) #Find the scripts in this module for name in module.__dict__.keys(): object = module.__dict__[name] if isinstance(object, type(Script)) and object != Script: log.info('Loading script: %s', name) scripts[name] = object #initialize the bots config = ConfigParser() config.read(config_filename) runbots = config.get('pyrobot', 'run').split(',') for botname in runbots: usescripts = config.get(botname, 'scripts').split(',') script_instances = [] for name in usescripts: scriptmodule = scripts[name] script_instances.append(scriptmodule(config.items(botname))) username = config.get(botname, 'username') password = config.get(botname, 'password') slot = int(config.get(botname, 'slot')) bots[botname] = connection.Connection(cel, username, password, slot, script_instances) #bots[botname].connect() event.EventProcessor().start()
def serve(self): """ Loop principal del servidor. Se acepta una conexión a la vez y se espera a que concluya antes de seguir. """ # FALTA: Aceptar una conexión al server, crear una # Connection para la conexión y atenderla hasta que termine. while True: # Aceptamos conexion, abriendo una conexion entre el # Cliente y servidor try: # El metodo accept() nos da una tupla addr_client, la cual es # una tupla con IP del cliente, y su port. socket_client, addr_client = self.socket.accept() print "Connected by: %s" % (addr_client, ) # creamos una conexion con el socket cliente, este objeto es # del archivo connection.py conexion = connection.Connection(socket_client, self.dir) # llamamos al handle() para que atiende los pedidos del cliente conexion.handle() except: print("Servidor caido") return 0
def get_top_authors(): # create a connection conn = connection.Connection() # get the cursor db_cursor = conn.get_connection() path_folder = "/article/" # query to be run query = "SELECT name,count(*) " \ "FROM articles " \ "INNER JOIN log ON articles.slug = substring(log.path,length('/article/')+1) " \ "INNER JOIN authors on author = authors.id " \ "GROUP BY name " \ "ORDER BY count DESC;".format(path_folder) # execute the query db_cursor.execute(query) # result will hold the results of the query result = db_cursor.fetchall() # close the connection del db_cursor return result
def create_task(self, project_name, req_id): receive_time = format_time(time.time()) update_sql = ( "update task set req_id = '%s', status = 'RECEIVED', receive_time = '%s'," "start_time = NULL, stop_time = NULL, network_info = NULL, vm_info = NULL, vm_num = NULL," "receive_vm_num = 0, network_num = NULL, receive_network_num = 0, result = NULL" " where project = '%s';") % (req_id, receive_time, project_name) insert_sql = ( "insert into task set project = '%s', req_id = '%s', status = 'RECEIVED'," "receive_time= '%s', start_time = NULL, stop_time = NULL, network_info = NULL," "vm_info = NULL, vm_num = NULL, receive_vm_num = 0, network_num = NULL, receive_network_num = 0," "result = NULL;") % (project_name, req_id, receive_time) conn = None try: conn = connection.Connection(conf_dict=self.db_conf) except MySQLdb.Error, e: DBLOG.error( "database.create_task - project-%s req-%s task_start fail:%s" % (project_name, req_id, str(e))) return False, str(e)
def accept(self, block=True, timeout=None): """ called by client code - Socket and connection threads should not touch! blocks until a new connection is received and a Connection object has been created. Return: a Connection instance Errors: if socket closed, throw exception """ unknownPacket = self.unknownPackets.get(block, timeout) debugLog("got unknown packet for accept call") self.connectionsLock.acquire() newConn = connection.Connection(self.sock.getsockname()[1], unknownPacket[1][1], self.maxWindowSize, connection.STATE.SYN_RECV, unknownPacket[1][0], self) self.connections[(unknownPacket[1][0], unknownPacket[1][1])] = newConn self.connectionsLock.release() newConn.establishConnection() return newConn