def listen_push_port(self, port): port.sockets = [] for port_url in port.port_urls: socket = self.context.socket(zmq.PUSH) socket.setsockopt(zmq.HWM, self.queue_size) socket.connect(port_url) port.sockets.append(socket)
def main(): host = '' port = 80 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: socket.connect(host, port) except Exception as e: print ("Couldn't acquire port :", port,"\n") try: port = 8080 socket.connect(host, port) except Exception as e: print ("Couldn't connect to port 80 ad 8080") print ("Success: client connected to host: ", host, "and port: ", port) while True: sys.stdout.write("Client ready to send request:") cmd = str(sys.argv) print ("Sending command to server: %s" % cmd) print ("Host name: %s" % str(sys.argv[1])) print ("Port: %s" % str(sys.argv[2])) print ("Filename: %s" % str(sys.argv[2])) socket.send(cmd) response = socket.recv(1024) if response: sys.stdout.write(response) socket.close()
def get_replay(name, query, config, context=None): endpoint = config.get('replay_endpoints', {}).get(name, None) if not endpoint: raise IOError("No appropriate replay endpoint " "found for {0}".format(name)) if not context: context = zmq.Context(config['io_threads']) # A replay endpoint isn't PUB/SUB but REQ/REP, as it allows # for bidirectional communication socket = context.socket(zmq.REQ) try: socket.connect(endpoint) except zmq.ZMQError as e: raise IOError("Error when connecting to the " "replay endpoint: '{0}'".format(str(e))) # REQ/REP dance socket.send(fedmsg.encoding.dumps(query)) msgs = socket.recv_multipart() socket.close() for m in msgs: try: yield fedmsg.encoding.loads(m) except ValueError: # We assume that if it isn't JSON then it's an error message raise ValueError(m)
def send(self, message_type=None, message_type_args={}, request_id=None): if(not request_id): request_id = uuid.uuid4() context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://{0}:{1}".format(self._ip, self._port)) socket.poll(timeout=1) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) lib.debug.info("Sending request {0} …".format(request_id)) timestarted = time.time() hostdetails = simplejson.dumps({'hostname':lib.hostname_ip.hostname, 'ip':lib.hostname_ip.ip}) send_msg = simplejson.dumps(self.process(message_type, message_type_args,hostdetails)) socket.send_multipart([bytes(unicode(request_id)), bytes(unicode(hostdetails)), bytes(unicode(message_type)), bytes(unicode(send_msg))]) while(True): sockets = dict(poller.poll(10000)) if(sockets): for s in sockets.keys(): if(sockets[s] == zmq.POLLIN): try: (recv_id, recv_hostdetails, recv_msg_type, recved_msg) = s.recv_multipart() recv_message = self.process(recv_msg_type, recved_msg,recv_hostdetails) lib.debug.info("Received reply %s : %s [ %s ]" % (recv_id, recv_message, time.time() - timestarted)) except: lib.debug.info (sys.exc_info()) break break lib.debug.info ("Reciever Timeout error : Check if the server is running") socket.close() context.term()
def orca_producer(host, port=44666): """ Pushes CMOS and base current records to a ZMQ Push/Pull socket to be parsed by other workers. CMOS rates and base currents are pushed to ports 5557 and 5558 respectively. See `zeromq.org <http://zeromq.org>`_ for more information. """ socket = Socket() socket.connect(host, port) cmos_context = zmq.Context() cmos = cmos_context.socket(zmq.PUSH) cmos.bind('tcp://127.0.0.1:5557') base_context = zmq.Context() base = base_context.socket(zmq.PUSH) base.bind('tcp://127.0.0.1:5558') while True: id, rec = socket.recv_record() if id == CMOS_ID: cmos.send_pyobj((id,rec)) if id == BASE_ID: base.send_pyobj((id,rec))
def getFile(filename): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:1337") socket.send(filename) response = socket.recv_json() return response
def _socketRequest(self, scheme, host, port, payload): socket = self._getSocketForScheme(scheme) socket.connect((host, port)) socket.sendall(payload) data = socket.recv(1024) socket.close() return data
def send(self, service_name, method, *args): socket = NetRPC() socket.connect(self.hostname, self.port) socket.mysend((service_name, method, )+args) result = socket.myreceive() socket.disconnect() return result
def localization_client(ip,port): context = zmq.Context() # Socket to talk to server print "Connecting to localization server ... " socket = context.socket(zmq.REQ) socket.connect(("tcp://localhost:%d" % port)) # Do 10 requests, waiting each time for a response while True: # print("Sending request %s ... " % request) socket.send(b"pose") # Get the reply. result = json.loads(socket.recv(1024)); # printing the result # print(result) # In order to access position : (result["pos"]["x"],result["pos"]["y"],result["pos"]["z"]) # In order to access orientation : (result["orient"]["w"],result["orient"]["x"],result["orient"]["y"],result["orient"]["z"]) print "Position : " , (float(result["pos"]["x"]),float(result["pos"]["y"]),float(result["pos"]["z"])) print "Orientation : " , (float(result["orient"]["w"]),float(result["orient"]["x"]),float(result["orient"]["y"]),float(result["orient"]["z"])) # wait for a while time.sleep(0.050)
def main(network, nick, chan, port): socket.connect((network, port)) irc = ssl.wrap_socket(socket) irc.send(bytes("NICK %s\r\n" % nick, "UTF-8")) print(irc.recv(4096)) irc.send(bytes("USER %s %s %s :My bot\r\n" % (nick, nick, nick), "UTF-8")) print(irc.recv(4096)) irc.send(bytes("JOIN #%s\r\n" % chan, "UTF-8")) print(irc.recv(4096)) while True: data = irc.recv(4096) print(data) user_in = input(":") if user_in.find("!s") != -1: user_in = user_in[3:] searchterm = user_in try: print_search(searchterm) except KeyError: print("No Result Found") print(user_in) data = data.decode("UTF-8") if data.find("PING") != -1: irc.send(bytes("PONG " + data.split()[1] + "\r\n", "UTF-8")) if user_in.find("!q") != -1: irc.send(bytes("QUIT\r\n", "UTF-8")) exit() if user_in.find("!d") != -1: ##to check for xfer bot_name = "Dragonkeeper" pack_number = "1" # user_in = user_in[3:] ## for option select !d 1 will show as 1 irc.send(bytes("PRIVMSG " + bot_name + " :xdcc send " + pack_number + "\r\n", "UTF-8"))
def _worker(self,worker_url, worker_id=uuid.uuid4()): if (sys.platform.lower().find("linux") >= 0): setproctitle.setproctitle("server-worker") lib.debug.info (worker_url) context = zmq.Context() # Socket to talk to dispatcher socket = context.socket(zmq.REP) socket.poll(timeout=1) socket.connect(worker_url) while True: (request_id_rep, state_name_rep, topic_rep, msg_rep) = socket.recv_multipart() rep_sock.send_multipart([request_id_rep, state_name, msg_rep]) lib.debug.debug(msg_rep) try: msg_reved = simplejson.loads(msg_rep) if (msg_reved['status'] == "free"): hosts_recieved[msg_reved['hostid']] = msg_reved lib.debug.debug("sending state : " + state_name_rep + " : ") else: return (msg_reved['status'] + " : " + msg_reved['request_id']) except: lib.debug.error(str(state_name) + " : " + str(request_id) + " : " + str(sys.exc_info())) return (str(state_name) + " : " + str(request_id) + " : " + str(sys.exc_info())) while True: received = socket.recv_multipart() lib.debug.info("Received request: [ {0} ] -> [ {1} ]".format(str(worker_id),msg_type_args)) reply = self.process(received) reply_to_send = simplejson.dumps(reply) socket.send_multipart([bytes(unicode(hostid)),bytes(unicode(request_id)),bytes(unicode(reply_to_send))]) lib.debug.info("Replied to request: [ {0} ] -> [ {1} ]".format(str(worker_id), msg_type_args))
def InitResource(version): global database, resource, socket, listflie, tfidfmodel, tfidfdict, table_state_strategy if version is 'v1': listfile = 'cnn_qa_human_response_name.list' if version is 'v2': listfile = 'cnn_qa_human_response_name_high_app.list' if version is 'v2.5': listfile = 'cnn_qa_human_response_name_high_app.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') if version is 'v3': listfile = 'cnn_hr_v1_v2.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') if version is 'v4': listfile = 'cnn_hr_v1_v2_v4.list' tfidfdict = corpora.Dictionary.load(tfidfname + '.dict') tfidfmodel = models.tfidfmodel.TfidfModel.load(tfidfname + '.tfidf') datalist=[line.strip() for line in open(listfile)] database = Loader.LoadDataPair(datalist) resource = Loader.LoadLanguageResource() global TemplateLib, TopicLib, TreeState, Template,model TemplateLib = Loader.LoadTemplate(template_list) TopicLib = Loader.LoadTopic(topicfile) TreeState, Template = Control.Init() model = models.Doc2Vec.load('/tmp/word2vec_50') if wizard is 2: context= zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") with open('table_state_strategy.pkl') as f: table_state_strategy = pickle.load(f)
def myConnect(socket,host,port): while True: ## send message to log try: socket.connect(host,port) break except: continue
def obtainTaskSpecFromServer(ServerIP, ServerPort, TeamName): # context = zmq.Context() # connection_address = "tcp://" + ServerIP + ":" + ServerPort # print "Start connection to " + connection_address # # Socket to talk to server # print "Connecting to server..." # socket = context.socket(zmq.REQ) # socket.connect(connection_address) # # print "Sending request ..." # socket.send(TeamName) # # # Get the reply. # message = socket.recv() # socket.send("ACK") # socket.close() # print "Received message: ", message # return message while True: try: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((ServerIP, ServerPort)) errorPrinted = False except socket.error, err: if not errorPrinted: rospy.loginfo("Connection to %s:%s not succsesfull: %s", ServerIP, ServerPort, err) rospy.loginfo("retrying ...") errorPrinted = True rospy.sleep(1.) else: socket.send(MESSAGE) return waitForData(socket) rospy.loginfo("Connected to %s : %s", ServerIP, ServerPort)
def connectTo(peer): socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socket.settimeout(10) try: socket.connect(peer) except: return False return True
def connect(self, socket, channel): n = self.nickname socket.connect((self.ip, self.port)) self.socket_send(socket, "USER "+n+" "+n+" "+n+" :Jestem bogiem irc") self.socket_send(socket, "NICK "+n) time.sleep(10) # otherwise, it tends to not join the channel self.functions.join_channel(self.channel)
def connection(socket,host,port): try: socket.connect((host,port)) return socket except IOError, e: if e.errno == 101: time.sleep(5) connection(socket,host,port)
def create_socket(socktype, endpoints,flag): socket = zmq.Socket(zmq.Context.instance(), socktype) socket.setsockopt(zmq.LINGER, 0) for endpoint in endpoints: if flag==1: socket.bind(endpoint) else: socket.connect(endpoint) return socket
def connect(self, addr): self.connected = False self.connecting = True socket = self.socket socket.setblocking(1) socket.connect(addr) socket.setblocking(0) self.addr = addr self.handle_connect_event()
def run(self): for i in range(self.packets): try: bytes = random._urandom(self.size) socket.connect(self.ip, self.port) socket.setblocking(0) socket.sendto(bytes,(self.ip, self.port)) except: pass
def connectWithPlayer(clientSocket, serverSocket): try: socket.connect('127.0.0.1', 3000) print('Connected with player') return 1 except: print('Waiting for players....') c, addr = serverSocket.accept() print('Connected with player')
def connectToServer(self, ip, port): import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((ip, port)) return socket
def add_socket (self, socket): # get socket to connect socket.connect() if socket.sock is not None : fd = socket.sock.fileno() self.sockets[fd] = socket self.poller.register(socket.sock, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) else : self.logger.log ('unable to add socket to poller, sock==None')
def CONNECTION(): port=input("Enter FTP Port: ") if port == '': port = 21 else: port = port socket.connect((input("Enter FTP Address: "),port)) RECIEVE()
def ban_swabber(ip): if not zmq: raise SystemExit("swabber engine enabled but zmq not available!") context = zmq.Context() socket = context.socket(zmq.PUB) socket.connect("tcp://127.0.0.1:22620") socket.send_multipart(("swabber_bans", ip)) socket.close() return True
def run(socket): socket.bind((address, port)) try: socket.connect((self.DEFAULT_SRC_ADDRESS, self.DEFAULT_SRC_PORT)) self.end_event.wait() socket.free() except Exception, e: traceback.print_exc(e) self.network.close()
def __init__(self): socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: socket.connect((configbone.FloatHOST, configbone.BoneSocket)) while True: data = sensors() socket.send(data) except: sock.close()
def _rpc(action, *args): _logger.debug("About to send rpc request %s with args %s", action, args) with sockets.context.socket(zmq.REQ) as socket: # # To avoid problems when restarting a beacon not long after it's been # closed, force the socket to shut down regardless about 1 second after # it's been closed. # socket.connect("tcp://localhost:%s" % _Beacon.rpc_port) socket.send(_pack([action] + list(args))) return _unpack(socket.recv())
def get_connection(socket, endpoint, ssh_server=None, ssh_keyfile=None): if ssh_server is None: socket.connect(endpoint) else: try: try: ssh.tunnel_connection(socket, endpoint, ssh_server, keyfile=ssh_keyfile) except ImportError: ssh.tunnel_connection(socket, endpoint, ssh_server, keyfile=ssh_keyfile, paramiko=True) except ImportError: raise ImportError("pexpect was not found, and failed to use " "Paramiko. You need to install Paramiko")
def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60): """Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args, and calls socket.connect('tcp://localhost:lport') where lport is the randomly selected local port of the tunnel. """ new_url, tunnel = open_tunnel(addr, server, keyfile=keyfile, password=password, paramiko=paramiko, timeout=timeout) socket.connect(new_url) return tunnel
def server(): while True: # time.sleep(2) try: context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:" + mi_port) try: print("servidor ejecutando...") message = socket.recv_string() print(message) l = message.split("_") # print(l) # print(type(l[0])) #print("cualquier cosa") if l[0] == "p": if l[1] == yo: # aqui se devuelve enviando el puerto del sevicio hasta llegar a cliente print(l) ruta = l[5] # se extrae el diccionario_string ruta # se convierte a diccionario ruta_dic = json.loads(ruta) # agrego mi servicio/nodo a la ruta ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # se agrega el dato ruta actualizado a la lista #l[5] = json.dumps(ruta_dic) print("llaves de ruta: ", keys) # si estamos ubicados en el ultimo nodo mas cercano al cliente cambiamos el token que esta al inicio del mensaje # lo sabemos si en ruta solo quedan dos nodos: el cliente y el que tiene el servicio context_respuesta = zmq.Context() socket_respuesta = context_respuesta.socket(zmq.REQ) print(directorio) # traer la seccion de ruta para analizar cual fue el ultimo nodo agregado # enviar el puerto y el host al ultimo nodo # eliminar el ultimo nodo de la ruta #a = directorio.get(l[4]) a = ruta_dic.get(keys[-2]) # eliminar penultimo nodo de ruta (el ultimo contiene la direccion del servicio buscado) if len(keys) > 2: ruta_dic.pop(keys[-2]) l[5] = json.dumps(ruta_dic) l[0] = "s" nuevo_msm = '_'.join(l) print("nuevo mensaje:", nuevo_msm) socket_respuesta.connect("tcp://" + a['ip'] + ":" + a['puerto']) socket_respuesta.send_string(nuevo_msm) else: cliente = l[4] ruta_str = l[5] # string de ruta ruta_dic = json.loads(ruta_str) # diccionario de ruta print(ruta_dic) ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} ruta_str = json.dumps(ruta_dic) l[5] = ruta_str nuevo_msm = '_'.join(l) keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # tenemos que verificar no replicar el mensaje a los nodos que ya estan dentro de ruta for key in directorio: if key != yo and key != cliente and key not in keys: print("yolo") info = directorio.get(key) print(info) context_replicar = zmq.Context() socket_replicar = context_replicar.socket( zmq.REQ) socket_replicar.connect("tcp://" + info['ip'] + ":" + info['puerto']) socket_replicar.send_string(nuevo_msm) elif l[0] == "r": msm_c = l[1] # operador a = directorio.get(msm_c) if a == None: adicionar(l) print("este es l", l) print(directorio) else: pass # recibir mensaje de confirmacion (servicio encontrado) elif l[0] == "s": # si queda un solo elemento en ruta: conectar directamente # sino seguir pasando el mensaje al penultimo nodo de ruta ruta_str = l[5] ruta_dic = json.loads(ruta_str) keys = [] for key in ruta_dic: keys.append(key) if len(keys) == 2: print("entrooooooo", l) # conectarse directamente aux = ruta_dic.get(l[1]) # "-" #print("entro correctamente felicitaciones !!!", aux) host = aux["ip"] port = aux["puerto"] #print("ruta: ", ruta_dic) ruta_dic.pop(l[1]) l[5] = json.dumps(ruta_dic) nuevo_msm = '_'.join(l) #print("este es el nuevo mensaje: ", nuevo_msm) context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(nuevo_msm) # el servidor recibe conexion directa de elif len(keys) == 1: print("respondiendo...") print(l) respuesta = int(l[2]) - int(l[3]) respuesta = "resultado"+"_" + \ l[1]+"_"+l[2]+"_"+l[3]+"_" + \ str(respuesta) # "resultado_-_2_3_1" print(respuesta) aux = ruta_dic.get(l[4]) # "+" print("este es el cliente", aux) host = aux.get("ip") port = aux.get("puerto") context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(respuesta) else: aux = ruta_dic.get(keys[-2]) # [+,-,/] host = aux["ip"] port = aux["puerto"] ruta_dic.pop(keys[-2]) # [+,/] context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(mensaje) elif l[0] == "e": print("entro a resultado") # "resultado_-_2_3_1" print(l) print(str(l[2]) + str(l[1]) + str(l[3]) + ": " + str(l[4])) elif l[0] == "resultado": # "resultado_-_2_3_1" print(l[2] + l[1] + l[3] + ": " + l[4]) except: pass except: pass # print("ffffff")
import socket # Create socket and connect to the server socket = socket.socket() socket.connect(('localhost',5252)) # Buffer size bufferSize = 8 * 1024 # Create a new empty file to receive the uploaded file file = open('fileReceived.png', 'wb') # Receive the first bytes of the file chunk = socket.recv(bufferSize) # Stay in loop receiving the other parts of the file while chunk: # Write the bytes received in the file file.write(chunk) # Await the sending of new bytes chunk = socket.recv(bufferSize) # Close file file.close() # Close socket socket.close()
import socket # Import socket module A_host = socket.gethostname() # Get local machine name A_port = 50001 # Reserve a port for your service. B_port = 50000 # Reserve a port for your service. B_host = '127.0.0.1' socket = socket.socket() # Create a socket object filename='pingpong.jpg' f = open(filename,'rb') socket.connect((B_host, B_port)) l = f.read(1024) while (l): socket.send(l) l = f.read(1024) f.close() socket.close() with open('received_tcp.jpg', 'wb') as f: print ('file opened') #socket.bind((A_host, A_port)) # Bind to the port socket.listen(5) # Now wait for client connection. while True: conn, addr = socket.accept() # Establish connection with client. print ('Got connection from', addr)
if host == "": host = "127.0.0.1" elif host == "0": host = "192.168.1.140" elif host == "gatien": host = "gatien-oudoire.ddns.net" port, host = (6010, host) decoVoulue = 0 try: print("Tentative de connexion sur -> " + host) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((host, port)) print("La connexion a réussie \n") print("Il est conseillé de décliner son identité dans le premier message\n") while True: data = input("Entrez votre message :\n") print(data) if data == "sortir": data = "XPTDRTDECO" data = data.encode("utf8") socket.sendall(data) time.sleep(2.5) socket.close() decoVoulue = 1 break if data != "": data = data.encode("utf8")
import socket import time data = "data" ADDRESS = '192.168.100.104' PORT = 57214 with socket.socket() as socket: socket.connect((ADDRESS, PORT)) while True: data = socket.recv(3) if not data: break print("image data {}".format(data.decode())) time.sleep(1) print("end")
import socket import logging import traceback import projet messegNum = 0 publicKey = "" try: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip = socket.connect(('localhost', 9090)) # Debut de la session socket.send('hello') chunk = socket.recv(2048) messegNum = messegNum + 1 if messegNum == 1: #recuperation de la cle publique du serveur publicKey = chunk # generation de la cle DES desKey = projet.generateDESKey(64) # chiffrement RSA de la cle DES avec la cle publique du serveur desKeyEncrypted = desKey.to01() # envoi de la cle DES chiffre socket.send(desKeyEncrypted) # rec print "Connection OK" except Exception as e: print logging.error(traceback.format_exc())
print("Peer connected!") client.send("Peer connected!".encode()) while True: server_msg = input('>>> ') if server_msg == '.exit': break client.send(server_msg[:100].encode()) client_msg = client.recv(100).decode() print(client_msg) socket.close() if MODE == 'client': socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('localhost', 42069)) print("Waiting for peer to connect") server_msg = socket.recv(100).decode() print(server_msg) while True: client_msg = input('>>> ') if client_msg == '.exit': break socket.send(client_msg[:100].encode()) server_msg = socket.recv(100).decode() print(server_msg) socket.close()
### ### Start sending the payloads ### payload = generate_bytes() start_time = int(time.time()) window_start_time = int(time.time()) rate_current_second = int(time.time()) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = os.environ["IP_ADDRESS"] port = 9000 print(f"Connecting to address {address}, port {port}") socket.connect((address, port)) print(f"Sending {range(payloads_to_send)} payloads...") for i in range(payloads_to_send): # Check for rate being exceeded, i.e. we are sending data too quickly while rate_exceeded: # Sleep for 10 msec time.sleep(0.01) # Check the current time current_time = int(time.time()) # Remove rate limiting if we are in a new second
def test_connect_DefaultAttemptsFail_Exception(self): socket = ControllerSocket('badhost') with self.assertRaises(SocketConnectionException): socket.connect()
def unbox_recvd_message(resp_data): dict_data = json.loads(resp_data.decode('utf-8')) return dict_data if __name__ == "__main__": parser = sys_arg_parser() args = parser.parse_args() setup_log_config() logging.info(f'Starting client') try: socket = socket.socket() socket.connect((args.addr, int(args.port))) print('Connected to ', args.addr, args.port) logging.info(f'Connected to ", {args.addr}, {args.port}') except Exception as err: logging.error( f'Unnable to connect to server {args.addr}, port {args.port}') socket.close() try: message = make_presence() send_message(message) logging.info(f'Message sent: {message}') except Exception as err: logging.error(f'Unnable to send message {message}!') socket.close()
import socket import argparse parser = argparse.ArgumentParser("This script connects to a server and sends bgp messages read from a file.") parser.add_argument("dst_ip", type=str, help="Server IP") parser.add_argument("port", type=int, help="Port") parser.add_argument("infile", type=str, help="Infile") args = parser.parse_args() dst = args.dst_ip port = args.port infile = args.infile socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((dst, port)) print 'Connected to ',dst,' port ',port with open(infile, 'r') as fd: for line in fd.readlines(): if line[0] != '#': #print line linetab = line.split('|') linetab[2] = '10000' line = '|'.join(linetab) socket.send(line) socket.close()
import socket import AlphaBot server = ('', 7500) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(server) while True: alphabot = AlphaBot.AlphaBot() percorso = socket.recv(4096) steps = (percorso.decode).split(',') alphabot.setMotor() while True: if steps[1][1] == 'f': alphabot.forward(steps[1][1:]) steps.remove(1) elif steps[1][1] == 'b': alphabot.backward(steps[1][1:]) steps.remove(1) elif steps[1][1] == 'l': alphabot.left(steps[1][1:]) steps.remove(1) else: alphabot.right(steps[1][1:]) steps.remove(1)
#!/usr/bin/env python # -*- coding: utf-8 -*- from devinclude import * from bustime.models import * import socket import zmq import cPickle as pickle import time import base64 context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://127.0.0.1:15556") #socket.connect("ipc://bustime_out") #socket.connect("ipc://bustime_in") #socket.setsockopt_string(zmq.SUBSCRIBE, u"") socket.setsockopt(zmq.SUBSCRIBE, "") #socket.setsockopt(zmq.SUBSCRIBE, "bdata_mode0") #socket.setsockopt_string(zmq.SUBSCRIBE, u"busamounts_4") while 1: sr = socket.recv() what, p = sr.split(' ', 1) p = pickle.loads(p) #p = pickle.loads(base64.b64decode(p)) print what #print p print ""
import socket # definisikan IP server tujuan file akan diupload ip_server = "192.168.43.149" # definisikan port number proses di server port_server = 8080 # definisikan ukuran buffer untuk mengirim buffer_size = 1024 # buat socket (apakah bertipe UDP atau TCP?) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # lakukan koneksi ke server socket.connect((ip_server, port_server)) # buka file bernama "hasil_download.txt bertipe byte # masih hard code, file harus ada dalam folder yang sama dengan script python file_download = open("hasil_download.txt", "wb") # loop forever while 1: # terima pesan dari client data = socket.recv(buffer_size) print("Now Download") # tulis pesan yang diterima dari client ke file kita (result.txt) while (data): file_download.write(data) data = socket.recv(buffer_size)
if __name__ == '__main__': if len(sys.argv) != 3: print(f'python {sys.argv[0]} -p <port>') sys.exit() try: port = int(sys.argv[2]) except: print('Invalid port') sys.exit() if not 1025 <= port <= 65535: print('Invalid port') sys.exit() socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: socket.connect(('localhost', port)) except ConnectionRefusedError: print('Connection refused, check host is running') sys.exit() player = Player() game_map = GameMap(player) goals = Goals(game_map) while True: data = receive_socket_data(socket) if not data: socket.close() sys.exit() #print_view(data) game_map.update_map(data) #game_map.print_map()
<edit-config> <target> <candidate/> </target> <config> <configuration> <system> <host-name>{0}</host-name> </system> </configuration> </config> </edit-config> </rpc>""" socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((ROUTER_IP, 22)) trans = paramiko.Transport(socket) trans.connect(username=USERNAME, password=PASSWORD) #CREATE CHANNEL FOR DATA COMM ch = trans.open_session() name = ch.set_name('netconf') #Invoke NETCONF ch.invoke_subsystem('netconf') print "\n[IPSpace NCClient Demo] Opened NETCONF subchannel" NEW_HOSTNAME = "MX03" HOSTNAME_NC_STRING = SET_HOSTNAME.format(NEW_HOSTNAME)
def timeout(sock, user, secs=600): """ Time out a user for a set period of time. Keyword arguments: sock -- the socket over which to send the timeout command user -- the user to be timed out secs -- the length of the timeout in seconds (default 600) """ chat(sock, ".timeout {}".format(user, secs)) #network functions socket = socket.socket() socket.connect((cfg.HOST, cfg.PORT)) socket.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8")) socket.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8")) socket.send("JOIN {}\r\n".format(cfg.CHAN).encode("utf-8")) #maintain the chat in the infinite loop, handle the ping hello = False while True: response = socket.recv(1024).decode("utf-8") if response == "PING :tmi.twitch.tv\r\n": socket.send("PONG :tmi.twitch.tv\r\n".encode("utf-8")) else: CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :") username = re.search(r"\w+", response).group(0) # return the entire match
import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.bind(('127.0.0.1', 9090)) socket.connect(('127.0.0.1', 9090)) socket.send("good morning.\n".encode('utf-8')) socket.close()
import socket import time socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(("100.64.12.40", 8867)) while 1: socket.send("hello".encode()) print("sent") time.sleep(1)
def run_peer(queue, win_size, nb_withdrawals_burst_start, \ nb_withdrawals_burst_end, min_bpa_burst_size, burst_outdir, socket_rib_name, \ nb_withdraws_per_cycle=100, p_w=1, r_w=1, bpa_algo=False, nb_bits_aspath=33, \ run_encoding_threshold=1000000, global_rib_enabled=True, silent=False): global peer_logger import socket try: os.nice(-20) except OSError: peer_logger.info('Cannot change the nice.') # Create the topologies for this peer G = ASTopology(1, silent) # Main topology G_W = ASTopology( nb_withdrawals_burst_start, silent) # Subset of the topology with the withdraws in the queue # Current burst (if any) current_burst = None # Last time the peer wrote the rib and queue size in the log file last_log_write = 0 # Socket connected to the global RIB socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # Exit properly when receiving SIGINT def signal_handler(signal, frame): if current_burst is not None: current_burst.stop(bgp_msg.time) socket.close() peer_logger.info('Received SIGTERM. Exiting.') sys.exit(0) signal.signal(signal.SIGTERM, signal_handler) peer_id = None peer_as = None # Create the RIB for this peer rib = RIBPeer() encoding = None # This function create and initialize the encoding def init_encoding(): encoding = Encoding(peer_id, G, 'encoding', nb_bits_aspath, 5, output=True) encoding.compute_encoding() peer_logger.info( str(int(bgp_msg.time)) + '\t' + str(len(rib)) + '\t' + str(len(W_queue)) + '\t' + 'Encoding computed!') if global_rib_enabled: for p in rib.rib: send_fake_update(p, peer_ip, bgp_msg.time, rib, encoding, socket) return encoding #A_queue = BGPMessagesQueue(win_size) # Queue of Updates W_queue = BGPMessagesQueue(win_size) # Queue of Withdraws last_ts = 0 while True: while True: bgp_msg = queue.get() if bgp_msg is not None: if peer_id is None: peer_id = bgp_msg.peer_id peer_as = bgp_msg.peer_as peer_as_set = set() last_ts = bgp_msg.time peer_ip = peer_id.split('-')[-1] peer_handler = logging.handlers.RotatingFileHandler( log_dir + '/peer_' + str(peer_id), maxBytes=200000000000000, backupCount=5) peer_handler.setFormatter(formatter) peer_logger.removeHandler(handler) peer_logger.addHandler(peer_handler) peer_logger.info('Peer_' + str(peer_id) + '_(AS' + str(str(peer_as)) + ')_started.') if bgp_msg.as_path is not None and len( bgp_msg.as_path) > 0: if peer_as != bgp_msg.as_path[0]: peer_logger.warning( 'Peer AS ' + str(peer_as) + ' and first AS ' + str(bgp_msg.as_path[0]) + ' in AS path does not match. Setting first AS as peer AS.' ) peer_as = bgp_msg.as_path[0] # Make the connection with the global RIB rib_global_socket_address = '/tmp/' + socket_rib_name socket.connect(rib_global_socket_address) peer_logger.info('Peer_' + str(peer_id) + '_(AS' + str(str(peer_as)) + ') connected with the global RIB.') if peer_id != bgp_msg.peer_id: peer_logger.critical( 'Received a bgp_message with peer_id: ' + str(bgp_msg.peer_id)) if bgp_msg.mtype == 'A': # Update the set set of peer_as (useful when doing the naive solution) if len(bgp_msg.as_path) > 0: peer_as_set.add(bgp_msg.as_path[0]) # Update the RIB for this peer old_as_path = rib.update(bgp_msg) # Remove the old as-path in the main graph for this prefix G.remove(old_as_path, bgp_msg.prefix) # Add the new as-path in both the main graph and the graph of advertisments G.add(bgp_msg.as_path, bgp_msg.prefix) # Update the encoding, and send the fake advertisement to the global RIB if encoding is not None: encoding.advertisement(old_as_path, bgp_msg.as_path) if global_rib_enabled: send_fake_update(bgp_msg.prefix, peer_ip, bgp_msg.time, rib, encoding, socket) elif len(rib.rib) > run_encoding_threshold: encoding = init_encoding() elif bgp_msg.mtype == 'W': # Create the encoding if not done yet if encoding is None: encoding = init_encoding() # Update the RIB for this peer bgp_msg.as_path = rib.withdraw(bgp_msg) # Remove the old as-path in the main graph for this prefix G.remove(bgp_msg.as_path, bgp_msg.prefix) # Add the withdrawn as-path in the graph of withdraws G_W.add(bgp_msg.as_path) # Update the queue of withdraws if bgp_msg.as_path != []: W_queue.append(bgp_msg) # Update the encoding encoding.withdraw(bgp_msg.as_path) # Send the withdrawal to the global RIB if global_rib_enabled: send_fake_update(bgp_msg.prefix, peer_ip, bgp_msg.time, None, None, socket) elif bgp_msg.mtype == 'CLOSE': # CLOSE this peer. Clear all the topologies, ribs, queues, bursts, etc if current_burst is not None: best_edge_set, best_fm_score, best_TP, best_FP, best_FN = burst_prediction( current_burst, G, G_W, W_queue, p_w, r_w, bpa_algo, peer_as_set) current_burst.fd_predicted.write( 'PREDICTION_END_CLOSE|' + bpa_algo + '|' + str(len(current_burst)) + '|' + str(best_fm_score) + '|' + str(best_TP) + '|' + str(best_FN) + '|' + str(best_FP) + '\n') current_burst.fd_predicted.write( 'PREDICTION_END_EDGE|') res = '' depth = 9999999999 for e in best_edge_set: depth = min(G_W.get_depth(e[0], e[1]), depth) res += str(e[0]) + '-' + str(e[1]) + ',' current_burst.fd_predicted.write(res[:len(res) - 1] + '|' + str(depth) + '\n') #G_W.draw_graph(peer_as) current_burst.stop(bgp_msg.time) current_burst = None # Withdraw all the routes advertised by this peer if global_rib_enabled: for p in rib.rib: send_fake_update(p, peer_ip, -1, None, None, socket) peer_logger.info('Received CLOSE. CLEANING the peer.') # Stop this peer os.kill(os.getpid(), signal.SIGTERM) else: peer_logger.info(bgp_msg) # Make sure to compute start en end time of burst with a second granularity (only if ther is a burst) if current_burst is not None: while (last_ts != bgp_msg.time): last_ts += 1 # Update the graph of withdraws for w in W_queue.refresh_iter(last_ts): current_burst.deleted_from_W_queue.append(w) # Remove the current burst (if any) if it the size of the withdraws is lower than w_threshold (meaning it has finished) if len( W_queue ) < nb_withdrawals_burst_end: #current_burst.is_expired(bgp_msg.time): # Execute BPA at the end of the burst if the burst is large enough best_edge_set, best_fm_score, best_TP, best_FN, best_FP = burst_prediction( current_burst, G, G_W, W_queue, p_w, r_w, bpa_algo, peer_as_set) current_burst.fd_predicted.write( 'PREDICTION_END|' + bpa_algo + '|' + str(len(current_burst)) + '|' + str(best_fm_score) + '|' + str(best_TP) + '|' + str(best_FN) + '|' + str(best_FP) + '\n') current_burst.fd_predicted.write( 'PREDICTION_END_EDGE|') # Print some information about the prediction on the prediction file res = '' depth = 9999999999 for e in best_edge_set: res += str(e[0]) + '-' + str(e[1]) + ',' depth = min(G_W.get_depth(e[0], e[1]), depth) current_burst.fd_predicted.write(res[:len(res) - 1] + '|' + str(depth) + '\n') #G_W.draw_graph(peer_as, G, current_burst, outfile='as_graph_'+str(current_burst.start_time)+'.dot', threshold=500) # Update the graph of withdrawals for w in current_burst.deleted_from_W_queue: G_W.remove(w.as_path) current_burst.stop(bgp_msg.time) current_burst = None break else: current_burst.last_ts = last_ts # Update the graph of withdraws. if current_burst is None: for w in W_queue.refresh_iter(bgp_msg.time): G_W.remove(w.as_path) # Update the last timestamp seen last_ts = bgp_msg.time # Add the updates in the real prefixes set of the burst, if any if current_burst is not None: #and not silent: if bgp_msg.as_path != []: old_as_path = bgp_msg.as_path if bgp_msg.mtype == 'W' else old_as_path current_burst.add_real_prefix(bgp_msg.time, bgp_msg.prefix, bgp_msg.mtype, old_as_path) # If we are not in the burst yet, we create the burst if current_burst is None and len( W_queue) >= nb_withdrawals_burst_start: current_burst = Burst(peer_id, bgp_msg.time, win_size, burst_outdir, encoding, W_queue, silent) next_bpa_execution = min_bpa_burst_size # Print some log ... if (bgp_msg.time > last_log_write ) or bgp_msg.time - last_log_write >= 3600: peer_logger.info( str(int(bgp_msg.time)) + '\t' + str(len(rib)) + '\t' + str(len(W_queue))) last_log_write = bgp_msg.time # Execute BPA if there is a burst and # i) the current burst is greater than the minimum required # ii) we have wait the number of withdrawals required per cycle or the queue is empty if current_burst is not None: total_current_burst_size = len( current_burst) + nb_withdrawals_burst_start if total_current_burst_size >= min_bpa_burst_size and total_current_burst_size > next_bpa_execution: #\ if nb_withdraws_per_cycle > 0 and total_current_burst_size < 12505: next_bpa_execution += nb_withdraws_per_cycle else: next_bpa_execution = 999999999999 break #print ('Queue size: '+str(len(rib))+'\t'+str(len(W_queue))+'\t'+str(len(current_burst)+nb_withdrawals_burst_start)) if current_burst is not None: # Compute the set of edges with the highest FM score best_edge_set, best_fm_score, best_TP, best_FP, best_FN = burst_prediction( current_burst, G, G_W, W_queue, p_w, r_w, bpa_algo, peer_as_set) # Load that set in the burst if not silent: burst_add_edge(current_burst, rib, encoding, bgp_msg.time, best_edge_set, G, G_W, W_queue, silent) # Inform the global RIB about the set of failed links for e in best_edge_set: depth_set = set() if G_W.has_edge(e[0], e[1]): depth_set = depth_set.union( G_W[e[0]][e[1]]['depth'].keys()) if G.has_edge(e[0], e[1]): depth_set = depth_set.union(G[e[0]][e[1]]['depth'].keys()) for d in depth_set: if encoding.is_encoded(d, e[0], e[1]): vmac_partial = '' bitmask_partial = '' for i in range(2, encoding.max_depth + 2): if i == d: vmac_partial += encoding.mapping[ i].get_mapping_string(e[0]) bitmask_partial += '1' * encoding.mapping[ i].nb_bytes elif i == d + 1: vmac_partial += encoding.mapping[ i].get_mapping_string(e[1]) bitmask_partial += '1' * encoding.mapping[ i].nb_bytes else: if i in encoding.mapping: vmac_partial += '0' * encoding.mapping[ i].nb_bytes bitmask_partial += '0' * encoding.mapping[ i].nb_bytes if global_rib_enabled: socket.send('FR|' + peer_ip + '|' + vmac_partial + '|' + bitmask_partial + '|' + str(d) + '|' + str(last_ts) + '\n') # Print information about the perdiction in the predicted file current_burst.fd_predicted.write('PREDICTION|' + bpa_algo + '|' + str(len(current_burst)) + '|' + str(best_fm_score) + '|' + str(best_TP) + '|' + str(best_FP) + '|' + str(best_FN) + '\n') current_burst.fd_predicted.write('PREDICTION_EDGE|') res = '' depth = 9999999999 for e in best_edge_set: depth = min(G_W.get_depth(e[0], e[1]), depth) res += str(e[0]) + '-' + str(e[1]) + ',' current_burst.fd_predicted.write(res[:len(res) - 1] + '|' + str(depth) + '\n')
def connect_timeout(socket, host_port): return socket.connect(host_port)
if len(sys.argv) < 3: print "usage: ./client.py port input_file" else: port = sys.argv[1] inputFile = sys.argv[2] try: with open(inputFile) as file: #Parse file into lines content = file.readlines() #Remove unnecessary characters content = [x.strip() for x in content] #Create socket and connect to server socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('127.0.0.1', int(port))) #Send data to server one line at a time for line in content: socket.send(line) #Wait for server to respond before sending another line st = socket.recv(100) #Receive terminating message from server #Close socket socket.close() exit(0) except Exception as e: print e exit(1)
def banner(): socket = socket.socket() socket.connect((ip, int(port))) print(socket.recv(1024))
if len(sys.argv) < 2: print('you need to pass the name of the plot!') plotName = sys.argv[1] setupDict = yaml.load(open('smalldata_plot.yml', 'r')) i0var = setupDict[plotName]['i0var'] sigvar = setupDict[plotName]['sigvar'] binWidth = setupDict[plotName]['binWidth'] binEntries = setupDict[plotName]['binEntries'] FilterVar = setupDict[plotName]['FilterVar'] FilterVarMin = setupDict[plotName]['FilterVarMin'] FilterVarMax = setupDict[plotName]['FilterVarMax'] context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://%s:%d" % ('daq-xpp-mon05', 5000)) socket.setsockopt(zmq.SUBSCRIBE, b"") #if socket.poll(timeout=0): nrep = 1 while nrep > 0: socket.send_string("Request_for test") nowStr = time.strftime("%b %d %Y %H:%M:%S", time.localtime()) print("test requested data at %s " % (nowStr)) data_dict = socket.recv_pyobj() print("got data") data = {'scanSteps': []} data['scanValues_on'] = [] scanVarName = 'delay'
import random import socket, string, time, ssl import urllib, re import time from random import shuffle import random socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server = "" # Server channel = "" # Channel keys = "" # Keys botnick = "homestuckbot" # Your bots nick adminname = "" #IRC nickname exitcode = "begone " + botnick socket.connect( (server, 9999)) # Here we connect to the server using the port 6667 ircsock = ssl.wrap_socket(socket) ircsock.send( bytes( "USER " + botnick + " " + botnick + " " + botnick + " " + botnick + "\n", "UTF-8") ) #We are basically filling out a form with this line and saying to set all the fields to the bot nickname. ircsock.send(bytes("NICK " + botnick + "\n", "UTF-8")) # assign the nick to the bot def joinchan(chan): # join channel(s). ircsock.send(bytes("JOIN " + chan + keys + "\r\n", "UTF-8"))
return job, job2 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("encrypted_message", type=str, help="The message you want to decrypt") parser.add_argument("key_length", type=int, help="length of the key") args = parser.parse_args() # fetch IP address of the client socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket.connect(("8.8.8.8", 80)) cluster = dispy.JobCluster(delegate, ip_addr="192.168.0.142", nodes="192.168.0.*", depends=[ 'quadgram_analysis.py', QuadgramAnalyzer, "cipher.py", cipher.decrypt, cipher.decrypt_unknown_key ]) import time start_time = time.time() run_jobs() print(f"--- {time.time() - start_time} seconds ---") cluster.print_status()
# -*- coding: utf-8 -*- import socket def send_data(socket, data): total = 0 while total < len(data): sent = socket.send(data[total:]) total += sent print "Sent %d bytes" % total socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(("localhost", 8888)) viesti = u"шкм" * 1000 data = viesti.encode("utf-8") send_data(socket, data) socket.close()
pass print(server_response) mess = input(">>> ") self.socket.send(mess.encode()) server_response = self.socket.recv(1024) print(server_response.decode()) def close(self): print("Close") self.socket.close() if __name__ == '__main__': hote = "localhost" port = 15555 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((hote, port)) print("Connection on {}".format(port)) response = "" while not response: socket.send('Hello world'.encode()) response = socket.recv(1024) print("<"+response.decode()) print("Close connexion") socket.close()
import socket # 'argparse' is a very useful library for building python tools that are easy # to use from the command line. It greatly simplifies the input validation # and "usage" prompts which really help when trying to debug your own code. parser = argparse.ArgumentParser( description="Solver for 'All Your Base' challenge") parser.add_argument("ip", help="IP (or hostname) of remote instance") parser.add_argument("port", type=int, help="port for remote instance") args = parser.parse_args() # This tells the computer that we want a new TCP "socket" socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # This says we want to connect to the given IP and port socket.connect((args.ip, args.port)) # This gives us a file-like view of the connection which makes reading data # easier since it handles the buffering of lines for you. f = socket.makefile() while True: line = f.readline().strip() print(line) # This iterates over data from the server a line at a time. This can cause # some unexpected behavior like not seeing "prompts" until after you've sent # a reply for it (for example, you won't see "answer:" for this problem). # However, you can still send data and it will be handled correctly. # Handle the information from the server to extact the problem and build # the answer string.
def ActConn(self,socket,port,cport): socket.bind(("",port)) socket.connect((caddr,cport))