Python socket.SHUT_RDWR() Examples

The following are code examples for showing how to use socket.SHUT_RDWR(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 9 votes vote down vote up
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 
Example 2
Project: PyJFuzz   Author: mseclab   File: pjf_testcase_server.py    (MIT License) View Source Project 7 votes vote down vote up
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) 
Example 3
Project: Flask_Blog   Author: sugarguo   File: ssl_support.py    (GNU General Public License v3.0) View Source Project 7 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 4
Project: chihu   Author: yelongyu   File: ssl_support.py    (license) View Source Project 7 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
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 6 votes vote down vote up
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 
Example 6
Project: IotCenter   Author: panjanek   File: iotserver.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 7
Project: zeronet-debian   Author: bashrc   File: UiServer.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 8
Project: dataplicity-lomond   Author: wildfoundry   File: session.py    (license) View Source Project 6 votes vote down vote up
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 
Example 9
Project: microbit-gateway   Author: whaleygeek   File: rfc2217.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 10
Project: flasky   Author: RoseOu   File: ssl_support.py    (license) View Source Project 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 11
Project: hologram-python   Author: hologram-io   File: CustomCloud.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 12
Project: hologram-python   Author: hologram-io   File: CustomCloud.py    (license) View Source Project 6 votes vote down vote up
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.') 
Example 13
Project: mb_remote   Author: whaleygeek   File: rfc2217.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 14
Project: hakkuframework   Author: 4shadoww   File: client.py    (license) View Source Project 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 15
Project: pupy   Author: ru-faraon   File: portfwd.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 16
Project: pupy   Author: ru-faraon   File: portfwd.py    (license) View Source Project 6 votes vote down vote up
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 
Example 17
Project: relaax   Author: deeplearninc   File: rlx_port.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 18
Project: gcodeplot   Author: arpruss   File: rfc2217.py    (license) View Source Project 6 votes vote down vote up
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 
Example 19
Project: gcodeplot   Author: arpruss   File: rfc2217.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 20
Project: sslpsk   Author: drbild   File: test_sslpsk.py    (license) View Source Project 6 votes vote down vote up
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 
Example 21
Project: zippy   Author: securesystemslab   File: client.py    (license) View Source Project 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 22
Project: bitio   Author: whaleygeek   File: rfc2217.py    (license) View Source Project 6 votes vote down vote up
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 
Example 23
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 5 votes vote down vote up
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 
Example 24
Project: HTP   Author: nklose   File: ChatServer.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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() 
Example 25
Project: python-   Author: secondtonone1   File: util.py    (license) View Source Project 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 26
Project: python-   Author: secondtonone1   File: ssl_support.py    (license) View Source Project 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 27
Project: my-first-blog   Author: AnkurBegining   File: util.py    (license) View Source Project 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 28
Project: my-first-blog   Author: AnkurBegining   File: ssl_support.py    (license) View Source Project 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 29
Project: gimel   Author: Alephbet   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 30
Project: BitBot   Author: crack00r   File: tcp_client.py    (license) View Source Project 5 votes vote down vote up
def close(self):
        """Closes the connection"""
        if self.connected:
            self._socket.shutdown(socket.SHUT_RDWR)
            self._socket.close()
            self.connected = False
            self._recreate_socket() 
Example 31
Project: BitBot   Author: crack00r   File: threaded_tcp_client.py    (license) View Source Project 5 votes vote down vote up
def close(self):
        """Closes the connection"""
        if self.connected:
            self._socket.shutdown(socket.SHUT_RDWR)
            self._socket.close()
            self.connected = False
            self._recreate_socket() 
Example 32
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 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 33
Project: mongodb-monitoring   Author: jruaux   File: client.py    (Apache License 2.0) View Source Project 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 34
Project: Flask_Blog   Author: sugarguo   File: util.py    (GNU General Public License v3.0) View Source Project 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:
            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 
Example 35
Project: pip-update-requirements   Author: alanhamlett   File: util.py    (BSD 2-Clause "Simplified" License) View Source Project 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 36
Project: Splunk_CBER_App   Author: MHaggis   File: client.py    (license) View Source Project 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 37
Project: electrum-martexcoin-server   Author: martexcoin   File: stratum_tcp.py    (license) View Source Project 5 votes vote down vote up
def shutdown(self):
        try:
            self._connection.shutdown(socket.SHUT_RDWR)
        except:
            # print_log("problem shutting down", self.address)
            pass
        self._connection.close() 
Example 38
Project: RSPET   Author: panagiks   File: rspet_client.py    (MIT License) View Source Project 5 votes vote down vote up
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() 
Example 39
Project: RSPET   Author: panagiks   File: rspet_server.py    (MIT License) View Source Project 5 votes vote down vote up
def purge(self):
        """Delete host not so gracefully."""
        self.connection["sock"].shutdown(SHUT_RDWR)
        self.connection["sock"].close()
        self.deleteme = True 
Example 40
Project: swjtu-pyscraper   Author: Desgard   File: util.py    (MIT License) View Source Project 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:
            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 
Example 41
Project: swjtu-pyscraper   Author: Desgard   File: ssl_support.py    (MIT License) View Source Project 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 42
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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:
            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 
Example 43
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 44
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: ssl_support.py    (MIT License) View Source Project 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 45
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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:
            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 
Example 46
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 47
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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:
            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 
Example 48
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: ssl_support.py    (MIT License) View Source Project 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 49
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: util.py    (MIT License) View Source Project 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:
            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 
Example 50
Project: sauna   Author: NicolasLM   File: tcp_server.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
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')