Python socket 模块,SHUT_RDWR 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.SHUT_RDWR

项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:PyJFuzz    作者:mseclab    | 项目源码 | 文件源码
def send_testcase(json, ip, port):
        """
        Send a raw testcase
        """
        try:
            json = struct.pack("<I", len(json)) + json
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((ip, int(port)))
                s.send(json)
                s.shutdown(socket.SHUT_RDWR)
                s.close()
                return True
            except socket.error:
                return False
        except socket.error as e:
            raise PJFSocketError(e.message if hasattr(e, "message") else str(e))
        except Exception as e:
            raise  PJFBaseException(e.message)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
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
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise
项目:IotCenter    作者:panjanek    | 项目源码 | 文件源码
def hadleSslCommunication(self, deviceId, sslSocket):
        try:
            while True:
                payload = iotcommon.recvMessage(sslSocket)
                clientAddr = sslSocket.getpeername()
                self.logger.info("Received SSL payload from {0} at {1}:{2}: {3}".format(binascii.hexlify(deviceId), clientAddr[0], clientAddr[1], payload))
                if deviceId in self.sessions:
                    session = self.sessions[deviceId]               
                else:
                    self.logger.debug("    creating new session for SSL device: %s", binascii.hexlify(deviceId))
                    session = IotSession(deviceId, IotSession.TYPE_SSL)
                    self.sessions[deviceId] = session                 
                session.lastUpdateTime = datetime.datetime.now()
                session.lastPayload = payload
                if self.logger.getEffectiveLevel() == logging.DEBUG:
                    self.dumpSessions()                        
                self.passToHandler(deviceId, payload)
        except Exception as e:
            self.logger.exception(e)
            try:
                self.removeSession(deviceId)
                sslSocket.shutdown(socket.SHUT_RDWR)
                sslSocket.close()
            except:
                pass
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def stop(self):
        self.log.debug("Stopping...")
        # Close WS sockets
        if "clients" in dir(self.server):
            for client in self.server.clients.values():
                client.ws.close()
        # Close http sockets
        sock_closed = 0
        for sock in self.server.sockets.values():
            try:
                sock.send("bye")
                sock.shutdown(socket.SHUT_RDWR)
                # sock._sock.close()
                # sock.close()
                sock_closed += 1
            except Exception, err:
                self.log.debug("Http connection close error: %s" % err)
        self.log.debug("Socket closed: %s" % sock_closed)
        time.sleep(0.1)

        self.server.socket.close()
        self.server.stop()
        time.sleep(1)
项目:dataplicity-lomond    作者:wildfoundry    | 项目源码 | 文件源码
def _close_socket(self):
        """Close the socket safely."""
        # Is a no-op if the socket is already closed.
        if self._sock is None:
            return
        try:
            # Get the write lock, so we can be certain data sending
            # in another thread is sent.
            with self._lock:
                self._sock.shutdown(socket.SHUT_RDWR)
                self._sock.close()
        except socket.error:
            # Socket is already closed.
            # That's fine, just a no-op.
            pass
        except Exception as error:
            # Paranoia
            log.warning('error closing socket (%s)', error)
        finally:
            self._sock = None
项目:microbit-gateway    作者:whaleygeek    | 项目源码 | 文件源码
def close(self):
        """Close port"""
        if self._isOpen:
            if self._socket:
                try:
                    self._socket.shutdown(socket.SHUT_RDWR)
                    self._socket.close()
                except:
                    # ignore errors.
                    pass
                self._socket = None
            if self._thread:
                self._thread.join()
            self._isOpen = False
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
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
项目:hologram-python    作者:hologram-io    | 项目源码 | 文件源码
def close_send_socket(self):
        try:
            # Check if we're going to use the AT command version of sockets or the
            # native Python socket lib.
            if self.__to_use_at_sockets():
                self.network.close_socket()
            else:
                try:
                    self.sock.shutdown(socket.SHUT_RDWR)
                except socket.error:
                    pass

                self.sock.close()

            self._is_send_socket_open = False
            self.logger.info('Socket closed.')
        except (IOError):
            self.logger.error('An error occurred while attempting to send the message to the cloud')
            self.logger.error('Please try again.')

    # EFFECTS: Receives data from inbound socket.
项目:hologram-python    作者:hologram-io    | 项目源码 | 文件源码
def closeReceiveSocket(self):

        self.logger.info('Closing socket...')

        if self.__to_use_at_sockets():
            self.network.close_socket()
            return

        self._receive_cv.acquire()

        self.socketClose = True
        self._receive_cv.release()

        self._accept_thread.join()

        self._receive_cv.acquire()
        try:
            self._receive_socket.shutdown(socket.SHUT_RDWR)
        except socket.error:
            pass
        self._receive_socket.close()

        self._receive_cv.release()

        self.logger.info('Socket closed.')
项目:mb_remote    作者:whaleygeek    | 项目源码 | 文件源码
def close(self):
        """Close port"""
        if self._isOpen:
            if self._socket:
                try:
                    self._socket.shutdown(socket.SHUT_RDWR)
                    self._socket.close()
                except:
                    # ignore errors.
                    pass
                self._socket = None
            if self._thread:
                self._thread.join()
            self._isOpen = False
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
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
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def handle(self):
        DST_ADDR, DST_PORT=self.server.remote_address
        logging.debug("forwarding local addr %s to remote %s "%(self.server.server_address, self.server.remote_address))
        rsocket_mod=self.server.rpyc_client.conn.modules.socket
        rsocket=rsocket_mod.socket(rsocket_mod.AF_INET, rsocket_mod.SOCK_STREAM)
        rsocket.settimeout(5)
        try:
            rsocket.connect((DST_ADDR, DST_PORT))
        except Exception as e:
            logging.debug("error: %s"%e)
            if e[0]==10060:
                logging.debug("unreachable !")
            self.request.shutdown(socket.SHUT_RDWR)
            self.request.close()
            return
        logging.debug("connection succeeded !")
        sp1=SocketPiper(self.request, rsocket)
        sp2=SocketPiper(rsocket, self.request)
        sp1.start()
        sp2.start()
        sp1.join()
        sp2.join()
        logging.debug("conn to %s:%s closed"%(DST_ADDR,DST_PORT))
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def get_remote_port_fwd_cb(remote_addr, local_addr):
    def func(rsocket):
        logging.debug("forwarding remote addr %s to local %s "%(remote_addr, local_addr))
        lsocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        lsocket.settimeout(5)
        try:
            lsocket.connect(local_addr)
        except Exception as e:
            logging.debug("error: %s"%e)
            if e[0]==10060:
                logging.debug("unreachable !")
            rsocket.shutdown(socket.SHUT_RDWR)
            rsocket.close()
            return
        logging.debug("connection succeeded !")
        sp1=SocketPiper(lsocket, rsocket)
        sp2=SocketPiper(rsocket, lsocket)
        sp1.start()
        sp2.start()
        sp1.join()
        sp2.join()
        logging.debug("conn to %s from %s closed"%(local_addr, remote_addr))

    return func
项目:relaax    作者:deeplearninc    | 项目源码 | 文件源码
def start_worker(cls, connection, address):
        try:
            RLXWorker.run(connection, address)
        except KeyboardInterrupt:
            pass
        finally:
            log.debug('Closing connection %s:%d' % address)
            if sys.platform == 'win32':
                os._exit(-1)             
            else:            
                try:
                    connection.shutdown(socket.SHUT_RDWR)
                except socket.error as e:
                    # we don't care if the socket is already closed;
                    # this will often be the case if client closed connection first
                    if e.errno != errno.ENOTCONN:
                        raise
                finally:
                    connection.close()
项目:gcodeplot    作者:arpruss    | 项目源码 | 文件源码
def close(self):
        """Close port"""
        self.is_open = False
        if self._socket:
            try:
                self._socket.shutdown(socket.SHUT_RDWR)
                self._socket.close()
            except:
                # ignore errors.
                pass
        if self._thread:
            self._thread.join(7)  # XXX more than socket timeout
            self._thread = None
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)
        self._socket = None
项目:gcodeplot    作者:arpruss    | 项目源码 | 文件源码
def close(self):
        """Close port"""
        if self._isOpen:
            if self._socket:
                try:
                    self._socket.shutdown(socket.SHUT_RDWR)
                    self._socket.close()
                except:
                    # ignore errors.
                    pass
                self._socket = None
            if self._thread:
                self._thread.join()
            self._isOpen = False
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)
项目:sslpsk    作者:drbild    | 项目源码 | 文件源码
def tearDown(self):
        for sock in [self.client_psk_sock or self.client_socket,
                     self.server_psk_sock or self.server_socket,
                     self.accept_socket]:
            try:
                sock.shutdown(socket.SHUT_RDWR)
            except socket.error:
                pass
            finally:
                sock.close()

        self.client_socket = None
        self.server_socket = None
        self.accept_socket = None
        self.client_psk_sock = None
        self.server_psk_sock = None
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:bitio    作者:whaleygeek    | 项目源码 | 文件源码
def close(self):
        """Close port"""
        self.is_open = False
        if self._socket:
            try:
                self._socket.shutdown(socket.SHUT_RDWR)
                self._socket.close()
            except:
                # ignore errors.
                pass
        if self._thread:
            self._thread.join(7)  # XXX more than socket timeout
            self._thread = None
            # in case of quick reconnects, give the server some time
            time.sleep(0.3)
        self._socket = None
项目:HTP    作者:nklose    | 项目源码 | 文件源码
def disconnect():
    log('send', '<' + nick + '> left')
    print('Disconnecting from chat server...')
    msg_channel('Terminating connection. Beep boop.')
    irc.send('QUIT :The chatbots shall inherit the earth!\r\n')
    time.sleep(5)
    irc.shutdown(socket.SHUT_RDWR)
    irc.close()
    quit()
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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
项目:gimel    作者:Alephbet    | 项目源码 | 文件源码
def disconnect(self):
        "Disconnects from the Redis server"
        self._parser.on_disconnect()
        if self._sock is None:
            return
        try:
            self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
        except socket.error:
            pass
        self._sock = None
项目:BitBot    作者:crack00r    | 项目源码 | 文件源码
def close(self):
        """Closes the connection"""
        if self.connected:
            self._socket.shutdown(socket.SHUT_RDWR)
            self._socket.close()
            self.connected = False
            self._recreate_socket()
项目:BitBot    作者:crack00r    | 项目源码 | 文件源码
def close(self):
        """Closes the connection"""
        if self.connected:
            self._socket.shutdown(socket.SHUT_RDWR)
            self._socket.close()
            self.connected = False
            self._recreate_socket()
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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()
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
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()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:pip-update-requirements    作者:alanhamlett    | 项目源码 | 文件源码
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
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
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()
项目:electrum-martexcoin-server    作者:martexcoin    | 项目源码 | 文件源码
def shutdown(self):
        try:
            self._connection.shutdown(socket.SHUT_RDWR)
        except:
            # print_log("problem shutting down", self.address)
            pass
        self._connection.close()
项目:RSPET    作者:panagiks    | 项目源码 | 文件源码
def loop(self):
        """Client's main body. Accept and execute commands."""
        while not self.quit_signal:
            en_data = self.receive(5)
            try:
                en_data = self.comm_dict[en_data]
            except KeyError:
                if en_data == '':
                    self.reconnect()
                continue
            self.comm_swtch[en_data]()
        self.sock.shutdown(SHUT_RDWR)
        self.sock.close()
项目:RSPET    作者:panagiks    | 项目源码 | 文件源码
def purge(self):
        """Delete host not so gracefully."""
        self.connection["sock"].shutdown(SHUT_RDWR)
        self.connection["sock"].close()
        self.deleteme = True
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
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
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def disconnect(self):
        "Disconnects from the Redis server"
        self._parser.on_disconnect()
        if self._sock is None:
            return
        try:
            self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
        except socket.error:
            pass
        self._sock = None
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def disconnect(self):
        "Disconnects from the Redis server"
        self._parser.on_disconnect()
        if self._sock is None:
            return
        try:
            self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
        except socket.error:
            pass
        self._sock = None
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
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:
            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:
                self.sock.shutdown(socket.SHUT_RDWR)
                self.sock.close()
                raise
项目:sauna    作者:NicolasLM    | 项目源码 | 文件源码
def _close_socket(self, s):
        try:
            s.shutdown(socket.SHUT_RDWR)
        except socket.error:
            pass
        try:
            s.close()
        except socket.error:
            pass
        self._remove_from_list(self.write_wanted, s)
        self._remove_from_list(self.read_wanted, s)
        try:
            del self.write_buffers[s]
        except KeyError:
            pass
        self.logger.debug('Closed connection')