Python socket.SHUT_RDWR Examples

The following are 30 code examples of socket.SHUT_RDWR(). 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 also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: tcp_client.py    From LiMEaide with GNU General Public License v3.0 7 votes vote down vote up
def run(self):
        retry = True

        self.logger.info("Connecting to Socket")
        sel = selectors.DefaultSelector()
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.setsockopt(
            socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
        conn.setblocking(False)

        conn.connect_ex((self.ip, self.port))
        sel.register(conn, selectors.EVENT_READ, data=None)

        while retry:
            events = sel.select()
            for key, mask in events:
                retry = self.__handle_client__(key, mask, sel)

        sel.unregister(conn)
        if self.result['success']:
            conn.shutdown(socket.SHUT_RDWR)

        self.qresult.put(self.result)
        self.logger.info("Socket Closed") 
Example #2
Source File: server.py    From stream with MIT License 6 votes vote down vote up
def handle_LIST(self, arg):
    self.request.sendall(b'150 Opening IMAGE mode data connection for LIST\r\n')
    s = self.data_s.accept()[0]
    reply = []
    f = self.get_file_by_namelist(self.cwd)
    if type(f) is not dict:
      # TODO send error
      return
    for el, el_data in f.items():
      if type(el_data) is dict:
        reply.append("drwxrwx--- 1 root vboxsf 4096 Oct  4 21:58 %s" % el)
      else:
        reply.append("-rwxrwx--- 1 root vboxsf 1234 Oct  4 21:58 %s" % el)

    reply.append('')

    reply = '\r\n'.join(reply)
    s.sendall(bytes(reply, "utf-8"))
    s.shutdown(socket.SHUT_RDWR)
    s.close()

    self.request.sendall(b'226 Transfer complete\r\n') 
Example #3
Source File: client.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def connect(self):
            "Connect to a host on a given (SSL) port."

            sock = socket_create_connection((self.host, self.port),
                                            self.timeout, self.source_address)

            if self._tunnel_host:
                self.sock = sock
                self._tunnel()

            server_hostname = self.host if ssl.HAS_SNI else None
            self.sock = self._context.wrap_socket(sock,
                                                  server_hostname=server_hostname)
            try:
                if self._check_hostname:
                    ssl.match_hostname(self.sock.getpeercert(), self.host)
            except Exception:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise 
Example #4
Source File: ssl_support.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()

        self.sock = ssl.wrap_socket(
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
        )
        try:
            match_hostname(self.sock.getpeercert(), self.host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #5
Source File: server.py    From stream with MIT License 6 votes vote down vote up
def handle_LIST(self, arg):
    self.request.sendall(b'150 Opening IMAGE mode data connection for LIST\r\n')
    s = self.data_s.accept()[0]
    reply = []
    f = self.get_file_by_namelist(self.cwd)
    if type(f) is not dict:
      # TODO send error
      return
    for el in f.keys():
      reply.append("-rwxrwx--- 1 root vboxsf 4114 Oct  4 21:58 %s" % el)

    reply = '\r\n'.join(reply)
    s.sendall(bytes(reply, "utf-8"))
    s.shutdown(socket.SHUT_RDWR)
    s.close()

    self.request.sendall(b'226 Transfer complete\r\n') 
Example #6
Source File: worker.py    From PumpkinLB with GNU General Public License v3.0 6 votes vote down vote up
def closeConnections(self):
        try:
            self.workerSocket.shutdown(socket.SHUT_RDWR)
        except:
            pass
        try:
            self.workerSocket.close()
        except:
            pass
        try:
            self.clientSocket.shutdown(socket.SHUT_RDWR)
        except:
            pass
        try:
            self.clientSocket.close()
        except:
            pass
        signal.signal(signal.SIGTERM, signal.SIG_DFL) 
Example #7
Source File: vpn_indicator.py    From vpngate-with-proxy with GNU General Public License v2.0 6 votes vote down vote up
def send(self, msg):
        msg = msg.encode()
        if msg == b'dead':
            self.is_dead = True
            if self.is_connected:
                self.sock.shutdown(socket.SHUT_RDWR)
                print("shutdown socket")
            return True
        elif self.is_connected:
            try:
                self.client.sendall(msg + b'\n')
                return True
            except socket.error:
                return False
        else:
            return False 
Example #8
Source File: proxyhttp.py    From stream with MIT License 6 votes vote down vote up
def send_thread(c, p, end, rth):
  start = time.time()
  while not end.is_set():
    if time.time() - start > TIMEOUT:
      print("TIMEOUT")
      sys.stdout.flush()
      break

    try:
      data = p.recv(4096)
    except socket.timeout:
      continue

    if not data:
      break

    c.sendall(data)

  end.set()

  rth.join()
  p.shutdown(socket.SHUT_RDWR)
  c.shutdown(socket.SHUT_RDWR)
  p.close()
  c.close() 
Example #9
Source File: _socket_proxy.py    From oscrypto with MIT License 6 votes vote down vote up
def proxy(src, dst, callback=None):
    timeout = 10
    try:
        read_ready, _, _ = select.select([src], [], [], timeout)
        while len(read_ready):
            if callback:
                callback(src, dst)
            else:
                dst.send(src.recv(8192))
            read_ready, _, _ = select.select([src], [], [], timeout)
    except (socket.error, select.error, OSError, ValueError):
        pass
    try:
        src.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    src.close()
    try:
        dst.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    dst.close() 
Example #10
Source File: ssl_support.py    From lambda-packs with MIT License 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        if hasattr(ssl, 'create_default_context'):
            ctx = ssl.create_default_context(cafile=self.ca_bundle)
            self.sock = ctx.wrap_socket(sock, server_hostname=actual_host)
        else:
            # This is for python < 2.7.9 and < 3.4?
            self.sock = ssl.wrap_socket(
                sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
            )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #11
Source File: util.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def connect(self):
            sock = socket.create_connection((self.host, self.port), self.timeout)
            if getattr(self, '_tunnel_host', False):
                self.sock = sock
                self._tunnel()

            if not hasattr(ssl, 'SSLContext'):
                # For 2.x
                if self.ca_certs:
                    cert_reqs = ssl.CERT_REQUIRED
                else:
                    cert_reqs = ssl.CERT_NONE
                self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                                            cert_reqs=cert_reqs,
                                            ssl_version=ssl.PROTOCOL_SSLv23,
                                            ca_certs=self.ca_certs)
            else:  # pragma: no cover
                context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                context.options |= ssl.OP_NO_SSLv2
                if self.cert_file:
                    context.load_cert_chain(self.cert_file, self.key_file)
                kwargs = {}
                if self.ca_certs:
                    context.verify_mode = ssl.CERT_REQUIRED
                    context.load_verify_locations(cafile=self.ca_certs)
                    if getattr(ssl, 'HAS_SNI', False):
                        kwargs['server_hostname'] = self.host
                self.sock = context.wrap_socket(sock, **kwargs)
            if self.ca_certs and self.check_domain:
                try:
                    match_hostname(self.sock.getpeercert(), self.host)
                    logger.debug('Host verified: %s', self.host)
                except CertificateError:  # pragma: no cover
                    self.sock.shutdown(socket.SHUT_RDWR)
                    self.sock.close()
                    raise 
Example #12
Source File: util.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def connect(self):
            sock = socket.create_connection((self.host, self.port), self.timeout)
            if getattr(self, '_tunnel_host', False):
                self.sock = sock
                self._tunnel()

            if not hasattr(ssl, 'SSLContext'):
                # For 2.x
                if self.ca_certs:
                    cert_reqs = ssl.CERT_REQUIRED
                else:
                    cert_reqs = ssl.CERT_NONE
                self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                                            cert_reqs=cert_reqs,
                                            ssl_version=ssl.PROTOCOL_SSLv23,
                                            ca_certs=self.ca_certs)
            else:  # pragma: no cover
                context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                context.options |= ssl.OP_NO_SSLv2
                if self.cert_file:
                    context.load_cert_chain(self.cert_file, self.key_file)
                kwargs = {}
                if self.ca_certs:
                    context.verify_mode = ssl.CERT_REQUIRED
                    context.load_verify_locations(cafile=self.ca_certs)
                    if getattr(ssl, 'HAS_SNI', False):
                        kwargs['server_hostname'] = self.host
                self.sock = context.wrap_socket(sock, **kwargs)
            if self.ca_certs and self.check_domain:
                try:
                    match_hostname(self.sock.getpeercert(), self.host)
                    logger.debug('Host verified: %s', self.host)
                except CertificateError:  # pragma: no cover
                    self.sock.shutdown(socket.SHUT_RDWR)
                    self.sock.close()
                    raise 
Example #13
Source File: ssl_support.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        self.sock = ssl.wrap_socket(
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
        )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #14
Source File: ssl_support.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        if hasattr(ssl, 'create_default_context'):
            ctx = ssl.create_default_context(cafile=self.ca_bundle)
            self.sock = ctx.wrap_socket(sock, server_hostname=actual_host)
        else:
            # This is for python < 2.7.9 and < 3.4?
            self.sock = ssl.wrap_socket(
                sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
            )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #15
Source File: 1.py    From fuzzdb-collect with GNU General Public License v3.0 5 votes vote down vote up
def _xstream(num, s1, s2):
	'''
	交换两个流的数据
	num为当前流编号,主要用于调试目的,区分两个回路状态用。
	'''
	try:
		while True:
			#注意,recv函数会阻塞,直到对端完全关闭(close后还需要一定时间才能关闭,最快关闭方法是shutdow)
			buff = s1.recv(1024)
			if debug > 0:
				print num,"recv"
			if len(buff) == 0: #对端关闭连接,读不到数据
				print num,"one closed"
				break
			s2.sendall(buff)
			if debug > 0:
				print num,"sendall"
	except :
		print num,"one connect closed."

	try:
		s1.shutdown(socket.SHUT_RDWR)
		s1.close()
	except:
		pass

	try:
		s2.shutdown(socket.SHUT_RDWR)
		s2.close()
	except:
		pass

	streams[0] = None
	streams[1] = None
	print num, "CLOSED" 
Example #16
Source File: imaplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def shutdown(self):
        """Close I/O established in "open"."""
        self.file.close()
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except socket.error as e:
            # The server might already have closed the connection.
            # On Windows, this may result in WSAEINVAL (error 10022):
            # An invalid operation was attempted.
            if e.errno not in (errno.ENOTCONN, 10022):
                raise
        finally:
            self.sock.close() 
Example #17
Source File: jdwp.py    From ReDroid with MIT License 5 votes vote down vote up
def stop(self):
        """
        close the JDWP connection
        """
        try:
            self.unplug()
            self.join(timeout=JOIN_TIMEOUT)
            self.socket_conn.shutdown(socket.SHUT_RDWR)
            self.socket_conn.close()
        except Exception, e:
            pass 
Example #18
Source File: NetUtils.py    From Venus with Apache License 2.0 5 votes vote down vote up
def getLocalIPAddr(self):
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip=s.getsockname()[0]
        s.shutdown(socket.SHUT_RDWR)
        s.close()
        return ip

    #检测本机特定端口是否被占用 
Example #19
Source File: serial_host_send_receive.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def close_connect(connect, connect_type):
    if connect_type == 'socket':
        connect.shutdown(socket.SHUT_RDWR)
        connect.close()
    else:
        os.close(connect) 
Example #20
Source File: gdblike.py    From debugger with MIT License 5 votes vote down vote up
def kill_comms(self):
		if not self.sock:
			return

		# this should unblock any callers on recv()
		self.sock.shutdown(socket.SHUT_RDWR)
		self.sock.close()
		self.sock = None

	# asynchronously called when inside a "go" to inform us of stdout (and
	# possibly other stuff) 
Example #21
Source File: gdblike.py    From debugger with MIT License 5 votes vote down vote up
def detach(self):
		try:
			self.rspConn.send_payload('D')
			self.sock.shutdown(socket.SHUT_RDWR)
			self.sock.close()
			self.sock = None
		except rsp.RspDisconnected:
			pass
		except OSError:
			pass 
Example #22
Source File: imaplib.py    From meddle with MIT License 5 votes vote down vote up
def shutdown(self):
        """Close I/O established in "open"."""
        self.file.close()
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except socket.error as e:
            # The server might already have closed the connection
            if e.errno != errno.ENOTCONN:
                raise
        finally:
            self.sock.close() 
Example #23
Source File: ssl_support.py    From python-netsurv with MIT License 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        self.sock = ssl.wrap_socket(
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
        )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #24
Source File: ssl_support.py    From python-netsurv with MIT License 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        self.sock = ssl.wrap_socket(
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
        )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise 
Example #25
Source File: proto_connector.py    From pydota2_archive with Apache License 2.0 5 votes vote down vote up
def connect_with_server(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((HOST, self.port))
            
            try:
                self.bDone = False
                self.recv_threshold = FRAME_INTERVAL/30.0
                last_recv_time = datetime.now()
                while not self.bDone:
                    readers, _, _ = select.select([s], [], [])
                    new_time = datetime.now()
                    if len(readers) > 0 and self.recv_threshold < (new_time - last_recv_time).total_seconds():
                        last_recv_time = new_time
                        binSize = readers[0].recv(4)

                        if not binSize:
                            print("%s proto stream not found! Exiting!" % self.name)
                            break

                        else:
                            protoSize = unpack("@I", binSize)
                            print("%s protoSize: %d" % (self.name, protoSize[0]))
                            binData = readers[0].recv(protoSize[0])

                            if self.save_proto:
                                self.save_proto_to_file(binData)
                            if self.process_proto:
                                self.add_to_proto_queue(binData)

                            self.num_proto += 1
                            print("Process %d protos" % self.num_proto)
            finally:
                print("Closing Socket")
                s.shutdown(socket.SHUT_RDWR)
                s.close() 
Example #26
Source File: client.py    From SplunkForPCAP with MIT License 5 votes vote down vote up
def attached_socket(self, *args, **kwargs):
        """Opens a raw socket in a ``with`` block to write data to Splunk.

        The arguments are identical to those for :meth:`attach`. The socket is
        automatically closed at the end of the ``with`` block, even if an
        exception is raised in the block.

        :param host: The host value for events written to the stream.
        :type host: ``string``
        :param source: The source value for events written to the stream.
        :type source: ``string``
        :param sourcetype: The sourcetype value for events written to the
            stream.
        :type sourcetype: ``string``

        :returns: Nothing.

        **Example**::

            import splunklib.client as client
            s = client.connect(...)
            index = s.indexes['some_index']
            with index.attached_socket(sourcetype='test') as sock:
                sock.send('Test event\\r\\n')

        """
        try:
            sock = self.attach(*args, **kwargs)
            yield sock
        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close() 
Example #27
Source File: socket.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self) -> None:
    """
    Shuts down the socket. If it's already closed then this is a no-op.
    """

    with self._send_lock:
      # Function is idempotent with one exception: we notify _close() if this
      # is causing our is_alive() state to change.

      is_change = self.is_alive()

      if self._socket:
        # if we haven't yet established a connection then this raises an error
        # socket.error: [Errno 107] Transport endpoint is not connected

        try:
          self._socket.shutdown(socket.SHUT_RDWR)
        except socket.error:
          pass

        self._socket.close()

      if self._socket_file:
        try:
          self._socket_file.close()
        except BrokenPipeError:
          pass

      self._socket = None
      self._socket_file = None
      self._is_alive = False
      self._connection_time = time.time()

      if is_change:
        self._close() 
Example #28
Source File: client.py    From Games with MIT License 5 votes vote down vote up
def closeEvent(self, event):
        self.tcp_socket.sendall(packSocketData({'type': 'action', 'detail': 'exit'}))
        self.tcp_socket.shutdown(socket.SHUT_RDWR)
        self.tcp_socket.close()
        return super().closeEvent(event) 
Example #29
Source File: server.py    From Games with MIT License 5 votes vote down vote up
def closeEvent(self, event):
        if self.tcp_socket:
            self.tcp_socket.sendall(packSocketData({'type': 'action', 'detail': 'exit'}))
            self.tcp_socket.shutdown(socket.SHUT_RDWR)
            self.tcp_socket.close()
        self.tcp_server.close()
        return super().closeEvent(event) 
Example #30
Source File: ssl_support.py    From jbox with MIT License 5 votes vote down vote up
def connect(self):
        sock = socket.create_connection(
            (self.host, self.port), getattr(self, 'source_address', None)
        )

        # Handle the socket if a (proxy) tunnel is present
        if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
            # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
            # change self.host to mean the proxy server host when tunneling is
            # being used. Adapt, since we are interested in the destination
            # host for the match_hostname() comparison.
            actual_host = self._tunnel_host
        else:
            actual_host = self.host

        self.sock = ssl.wrap_socket(
            sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
        )
        try:
            match_hostname(self.sock.getpeercert(), actual_host)
        except CertificateError:
            self.sock.shutdown(socket.SHUT_RDWR)
            self.sock.close()
            raise