Python socket 模块,create_connection() 实例源码

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

项目: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
项目:sauna    作者:NicolasLM    | 项目源码 | 文件源码
def _fetch_memcached_stats(self):
        """Connect to Memcached and retrieve stats."""
        data = bytes()
        with socket.create_connection((self.config['host'],
                                       self.config['port']),
                                      timeout=self.config['timeout']) as s:
            s.sendall(b'stats\r\n')
            while True:
                buffer = bytearray(4096)
                bytes_received = s.recv_into(buffer)
                if bytes_received == 0:
                    # Remote host closed connection
                    break
                data += buffer
                if b'\r\nEND\r\n' in data:
                    # End of the stats command
                    break
        return data
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
    """Retrieve the certificate from the server at the specified address,
    and return it as a PEM-encoded string.
    If 'ca_certs' is specified, validate the server cert against it.
    If 'ssl_version' is specified, use it in the connection attempt."""

    host, port = addr
    if ca_certs is not None:
        cert_reqs = CERT_REQUIRED
    else:
        cert_reqs = CERT_NONE
    context = _create_stdlib_context(ssl_version,
                                     cert_reqs=cert_reqs,
                                     cafile=ca_certs)
    with closing(create_connection(addr)) as sock:
        with closing(context.wrap_socket(sock)) as sslsock:
            dercert = sslsock.getpeercert(True)
    return DER_cert_to_PEM_cert(dercert)
项目:greenstalk    作者:mayhewj    | 项目源码 | 文件源码
def __init__(self,
                 host: str = '127.0.0.1',
                 port: int = 11300,
                 encoding: Optional[str] = 'utf-8',
                 use: str = DEFAULT_TUBE,
                 watch: Union[str, Iterable[str]] = DEFAULT_TUBE) -> None:
        self._sock = socket.create_connection((host, port))
        self._reader = self._sock.makefile('rb')  # type: BinaryIO
        self.encoding = encoding

        if use != DEFAULT_TUBE:
            self.use(use)

        if isinstance(watch, str):
            if watch != DEFAULT_TUBE:
                self.watch(watch)
                self.ignore(DEFAULT_TUBE)
        else:
            for tube in watch:
                self.watch(tube)
            if DEFAULT_TUBE not in watch:
                self.ignore(DEFAULT_TUBE)
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
                      proxy_port=None, proxy_username=None,
                      proxy_password=None, timeout=None,
                      source_address=None):
    """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object

    Like socket.create_connection(), but connects to proxy
    before returning the socket object.

    dest_pair - 2-tuple of (IP/hostname, port).
    **proxy_args - Same args passed to socksocket.set_proxy() if present.
    timeout - Optional socket timeout value, in seconds.
    source_address - tuple (host, port) for the socket to bind to as its source
    address before connecting (only for compatibility)
    """
    sock = socksocket()
    if isinstance(timeout, (int, float)):
        sock.settimeout(timeout)
    if proxy_type is not None:
        sock.set_proxy(proxy_type, proxy_addr, proxy_port,
                       proxy_username, proxy_password)
    sock.connect(dest_pair)
    return sock
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def connect(self, host='', port=0, timeout=-999):
        '''Connect to host.  Arguments are:
         - host: hostname to connect to (string, default previous host)
         - port: port to connect to (integer, default previous port)
        '''
        if host != '':
            self.host = host
        if port > 0:
            self.port = port
        if timeout != -999:
            self.timeout = timeout
        self.sock = socket.create_connection((self.host, self.port), self.timeout)
        self.af = self.sock.family
        self.file = self.sock.makefile('rb')
        self.welcome = self.getresp()
        return self.welcome
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it

        :return: a new socket connection
        """
        try:
            conn = socket.create_connection(
                (self.host, self.port),
                self.timeout,
                self.source_address,
            )
        except AttributeError: # Python 2.6
            conn = socket.create_connection(
                (self.host, self.port),
                self.timeout,
            )
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,
                        self.tcp_nodelay)
        return conn
项目:voctomix-outcasts    作者:CarlFK    | 项目源码 | 文件源码
def main():
    p = argparse.ArgumentParser()
    p.add_argument('--host', default='localhost',
                   help='Hostname of voctocore')
    p.add_argument('--port', type=int, default=9999,
                   help='Port to connect to, on voctocore')
    p.add_argument('--file', type=argparse.FileType('a'),
                   help='Filename to write cuts to')
    args = p.parse_args()

    sock = socket.create_connection((args.host, args.port))
    for cut in capture_cuts(sock):
        ts = datetime.datetime.now().strftime("%Y-%m-%d/%H_%M_%S")
        print(ts)
        sys.stdout.flush()
        if args.file:
            args.file.write('%s\n' % ts)
            args.file.flush()
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def connect(self):
        """Create SSL socket and connect to peer
        """
        if getattr(self, 'ssl_context', None):
            if not isinstance(self.ssl_context, SSL.Context):
                raise TypeError('Expecting OpenSSL.SSL.Context type for "'
                                'ssl_context" attribute; got %r instead' %
                                self.ssl_context)
            ssl_context = self.ssl_context
        else:
            ssl_context = SSL.Context(self.__class__.default_ssl_method)

        sock = socket.create_connection((self.host, self.port), self.timeout)

        # Tunnel if using a proxy - ONLY available for Python 2.6.2 and above      
        if getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()

        self.sock = SSLSocket(ssl_context, sock)

        # Go to client mode.
        self.sock.set_connect_state()
项目:sauna    作者:NicolasLM    | 项目源码 | 文件源码
def _fetch_showq(self):
        """Connect to Postfix showq inet daemon and retrieve queue.

        This method is faster than executing mailq because it doesn't fork
        processes.
        It requires to have showq inet daemon activated which is not the case
        by default. To make showq listen on the loopback interface on port
        4280, add to your master.cf:
        127.0.0.1:4280     inet  n       -       -       -       -       showq
        """
        showq = bytes()
        with socket.create_connection((self.config['host'],
                                       self.config['port']),
                                      timeout=self.config['timeout']) as s:
            while True:
                buffer = bytearray(4096)
                bytes_received = s.recv_into(buffer)
                if bytes_received == 0:
                    break
                showq += buffer
        return showq.decode(encoding='utf-8')
项目:abusehelper    作者:Exploit-install    | 项目源码 | 文件源码
def open(self, host="", port=_DEFAULT_PORT_IMAP4_SSL):
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port), timeout=self._timeout)

        with ca_certs(self.ca_certs) as certs:
            self.sslobj = ssl.wrap_socket(
                self.sock,
                keyfile=self.keyfile,
                certfile=self.certfile,
                cert_reqs=ssl.CERT_REQUIRED,
                ca_certs=certs
            )
        cert = self.sslobj.getpeercert()
        match_hostname(cert, host)

        self.file = self.sslobj.makefile("rb")
项目:abusehelper    作者:Exploit-install    | 项目源码 | 文件源码
def open(self, host="", port=_DEFAULT_PORT_IMAP4_SSL):
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port), timeout=self._timeout)

        with ca_certs(self.ca_certs) as certs:
            self.sslobj = ssl.wrap_socket(
                self.sock,
                keyfile=self.keyfile,
                certfile=self.certfile,
                cert_reqs=ssl.CERT_REQUIRED,
                ca_certs=certs
            )
        cert = self.sslobj.getpeercert()
        match_hostname(cert, host)

        self.file = self.sslobj.makefile("rb")
项目:MUTE    作者:K4YT3X    | 项目源码 | 文件源码
def internet_connected():
    """
    This fucntion detects if the internet is available
    Returns a Boolean value
    """
    if STARTUP:
        print(OR + '[X] STARTUP: ' + W + 'Checking Internet..............' + W, end='')
    else:
        print(Y + '[+] INFO: ' + W + 'Checking Internet.................' + W, end='')
    try:
        socket.create_connection(('172.217.3.3', 443), 5)  # Test connection by connecting to google
        socket.create_connection(('192.30.253.113', 443), 5)
        print(G + 'OK!' + W)
        return True
    except socket.error:
        print(R + 'NO INTERNET!' + W)
        return False
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def connect(self, host='', port=0, timeout=-999):
        '''Connect to host.  Arguments are:
         - host: hostname to connect to (string, default previous host)
         - port: port to connect to (integer, default previous port)
        '''
        if host != '':
            self.host = host
        if port > 0:
            self.port = port
        if timeout != -999:
            self.timeout = timeout
        self.sock = socket.create_connection((self.host, self.port), self.timeout)
        self.af = self.sock.family
        self.file = self.sock.makefile('rb')
        self.welcome = self.getresp()
        return self.welcome
项目:azure-python-siteextensions    作者:Azure    | 项目源码 | 文件源码
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
    """Retrieve the certificate from the server at the specified address,
    and return it as a PEM-encoded string.
    If 'ca_certs' is specified, validate the server cert against it.
    If 'ssl_version' is specified, use it in the connection attempt."""

    host, port = addr
    if ca_certs is not None:
        cert_reqs = CERT_REQUIRED
    else:
        cert_reqs = CERT_NONE
    context = _create_stdlib_context(ssl_version,
                                     cert_reqs=cert_reqs,
                                     cafile=ca_certs)
    with closing(create_connection(addr)) as sock:
        with closing(context.wrap_socket(sock)) as sslsock:
            dercert = sslsock.getpeercert(True)
    return DER_cert_to_PEM_cert(dercert)
项目:azure-python-siteextensions    作者:Azure    | 项目源码 | 文件源码
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
    """Retrieve the certificate from the server at the specified address,
    and return it as a PEM-encoded string.
    If 'ca_certs' is specified, validate the server cert against it.
    If 'ssl_version' is specified, use it in the connection attempt."""

    host, port = addr
    if ca_certs is not None:
        cert_reqs = CERT_REQUIRED
    else:
        cert_reqs = CERT_NONE
    context = _create_stdlib_context(ssl_version,
                                     cert_reqs=cert_reqs,
                                     cafile=ca_certs)
    with  create_connection(addr) as sock:
        with context.wrap_socket(sock) as sslsock:
            dercert = sslsock.getpeercert(True)
    return DER_cert_to_PEM_cert(dercert)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def tryPort(self, ip, port):
        try:
            sock = socket.create_connection((ip, port), self.opts['timeout'])
            sock.settimeout(self.opts['timeout'])
            self.portResults[ip + ":" + str(port)] = True
        except Exception as e:
            self.portResults[ip + ":" + str(port)] = False
            return

        # If the port was open, see what we can read
        try:
            self.portResults[ip + ":" + str(port)] = sock.recv(4096)
        except Exception as e:
            sock.close()
            return

        sock.close()
项目:bossimage    作者:cloudboss    | 项目源码 | 文件源码
def wait_for_connection(addr, port, inventory, group, end):
    env = os.environ.copy()
    env.update(dict(ANSIBLE_HOST_KEY_CHECKING='False'))

    while(True):
        if time.time() > end:
            message = 'Timeout while connecting to {}:{}'.format(addr, port)
            raise ConnectionTimeout(message)
        try:
            # First check if port is open.
            socket.create_connection((addr, port), 1)

            # We didn't raise an exception, so port is open.
            # Now check if we can actually log in.
            with open('/dev/null', 'wb') as devnull:
                ret = subprocess.call([
                    'ansible', group,
                    '-i', inventory, '-m', 'raw', '-a', 'exit'
                ], stderr=devnull, stdout=devnull, env=env)
                if ret == 0:
                    break
                else:
                    raise
        except:
            time.sleep(15)
项目:sslkill    作者:m4n3dw0lf    | 项目源码 | 文件源码
def connect_relay(self):
        address = self.path.split(':', 1)
        address[1] = int(address[1]) or 443
        try:
            s = socket.create_connection(address, timeout=self.timeout)
        except Exception as e:
            self.send_error(502)
            return
        self.send_response(200, 'Connection Established')
        self.end_headers()

        conns = [self.connection, s]
        self.close_connection = 0
        while not self.close_connection:
            rlist, wlist, xlist = select.select(conns, [], conns, self.timeout)
            if xlist or not rlist:
                break
            for r in rlist:
                other = conns[1] if r is conns[0] else conns[0]
                data = r.recv(8192)
                if not data:
                    self.close_connection = 1
                    break
                other.sendall(data)
项目:xfinity-usage    作者:jantman    | 项目源码 | 文件源码
def _graphite_send(self, send_str):
        """
        Send data to graphite

        :param send_str: data string to send
        :type send_str: str
        """
        logger.debug('Opening socket connection to %s:%s', self.host, self.port)
        sock = socket.create_connection((self.host, self.port), 10)
        logger.debug('Sending data: "%s"', send_str)
        if sys.version_info[0] > 2:
            sock.sendall(send_str.encode('utf-8'))
        else:
            sock.sendall(send_str)
        logger.info('Data sent to Graphite')
        sock.close()
项目:Bethesda_SublimeFO4    作者:Scrivener07    | 项目源码 | 文件源码
def connect(self):
        # Add certificate verification
        sock = socket.create_connection((self.host, self.port), self.timeout)

        # Wrap socket using verification with the root certs in
        # trusted_root_certs
        self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
                                    cert_reqs=self.cert_reqs,
                                    ca_certs=self.ca_certs,
                                    server_hostname=self.host,
                                    ssl_version=self.ssl_version)

        if self.ca_certs:
            match_hostname(self.sock.getpeercert(), self.host)


## Pool objects
项目:cc98    作者:zjuchenyuan    | 项目源码 | 文件源码
def function_hook_parameter(oldfunc, parameter_index, parameter_name, parameter_value):
    """
    ?????????????IP?????????????????????????

    ????wrapper?????oldfunc????parameter_index??parameter_name?????????parameter_value; ??????????????????
    ??? ??? = function_hook_parameter(???, ?1????????????, ???????, ?????????)

    ??? ????socket.create_connection????????????? 
               create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None)
           ?????3???source_address???value???????
               socket.create_connection = function_hook_parameter(socket.create_connection, 3, "source_address", value)
    """
    real_func = oldfunc

    def newfunc(*args, **kwargs):  # args?????list?kwargs?????keyword???dict
        newargs = list(args)
        if len(args) >= parameter_index:  # ???????????????????????????????args?????????????
            newargs[parameter_index - 1] = parameter_value  # ?3????list????2
        else:  # ?????????????kwargs? ???????????????????kwargs??
            kwargs[parameter_name] = parameter_value
        return real_func(*newargs, **kwargs)

    return newfunc
项目:watchmen    作者:lycclsltt    | 项目源码 | 文件源码
def test_defer_connect(self):
        import socket
        for db in self.databases:
            d = db.copy()
            try:
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                sock.connect(d['unix_socket'])
            except KeyError:
                sock = socket.create_connection(
                                (d.get('host', 'localhost'), d.get('port', 3306)))
            for k in ['unix_socket', 'host', 'port']:
                try:
                    del d[k]
                except KeyError:
                    pass

            c = pymysql.connect(defer_connect=True, **d)
            self.assertFalse(c.open)
            c.connect(sock)
            c.close()
            sock.close()
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def tryPort(self, ip, port):
        try:
            sock = socket.create_connection((ip, port), self.opts['timeout'])
            sock.settimeout(self.opts['timeout'])
            self.portResults[ip + ":" + str(port)] = True
        except Exception as e:
            self.portResults[ip + ":" + str(port)] = False
            return

        # If the port was open, see what we can read
        try:
            self.portResults[ip + ":" + str(port)] = sock.recv(4096)
        except Exception as e:
            sock.close()
            return

        sock.close()
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def test_defer_connect(self):
        import socket
        for db in self.databases:
            d = db.copy()
            try:
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                sock.connect(d['unix_socket'])
            except KeyError:
                sock = socket.create_connection(
                                (d.get('host', 'localhost'), d.get('port', 3306)))
            for k in ['unix_socket', 'host', 'port']:
                try:
                    del d[k]
                except KeyError:
                    pass

            c = pymysql.connect(defer_connect=True, **d)
            self.assertFalse(c.open)
            c.connect(sock)
            c.close()
            sock.close()
项目:capnpy    作者:antocuni    | 项目源码 | 文件源码
def test_BufferedStream(self, benchmark, server):
        # this is like BufferedSocket, but with the overhead that _readchunk
        # is written in Python instead of Cython; this simulates what happens
        # if an user of capnpy wants to wrap its own stream reader
        class MyStream(BufferedStream):
            def __init__(self, host, port):
                super(MyStream, self).__init__()
                self.sock = socket.create_connection((host, port))

            def _readchunk(self):
                return self.sock.recv(8192)

        def open_connection():
            host, port = server.host, server.port
            return MyStream(host, port)
        self.do_benchmark(benchmark, open_connection)
项目:imcsdk    作者:CiscoUcs    | 项目源码 | 文件源码
def connect(self):
        """Overrides HTTPSConnection.connect to specify TLS version"""
        # Standard implementation from HTTPSConnection, which is not
        # designed for extension, unfortunately
        if sys.version_info >= (2, 7):
            sock = socket.create_connection((self.host, self.port),
                                            self.timeout, self.source_address)
        elif sys.version_info >= (2, 6):
            sock = socket.create_connection((self.host, self.port),
                                            self.timeout)
        else:
            sock = socket.create_connection((self.host, self.port))

        if getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()

        # This is the only difference; default wrap_socket uses SSLv23
        self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                                    ssl_version=ssl.PROTOCOL_TLSv1)
项目:tidb-ansible    作者:pingcap    | 项目源码 | 文件源码
def _create_connection(host, port, connect_timeout):
    """
    Connect to a 2-tuple (host, port) and return
    the socket object.

    Args:
        2-tuple (host, port) and connection timeout
    Returns:
        Socket object
    """
    if sys.version_info < (2, 6):
        (family, _) = (_convert_host_to_ip(host))[0]
        connect_socket = socket.socket(family, socket.SOCK_STREAM)
        connect_socket.settimeout(connect_timeout)
        connect_socket.connect( (host, port) )
    else:
        connect_socket = socket.create_connection( (host, port), connect_timeout)
    return connect_socket
项目:tinychain    作者:jamesob    | 项目源码 | 文件源码
def send_to_peer(data, peer=None):
    """Send a message to a (by default) random peer."""
    global peer_hostnames

    peer = peer or random.choice(list(peer_hostnames))
    tries_left = 3

    while tries_left > 0:
        try:
            with socket.create_connection((peer, PORT), timeout=1) as s:
                s.sendall(encode_socket_data(data))
        except Exception:
            logger.exception(f'failed to send to peer {peer}')
            tries_left -= 1
            time.sleep(2)
        else:
            return

    logger.info(f"[p2p] removing dead peer {peer}")
    peer_hostnames = {x for x in peer_hostnames if x != peer}
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def create_tcp_connection(self, hostname, port, timeout, **kwargs):
        sock = socket.create_connection((self.proxy_host, int(self.proxy_port)))
        if hostname.endswith('.appspot.com'):
            hostname = 'www.google.com'
        request_data = 'CONNECT %s:%s HTTP/1.1\r\n' % (hostname, port)
        if self.proxy_username and self.proxy_password:
            request_data += 'Proxy-Authorization: Basic %s\r\n' % base64.b64encode(('%s:%s' % (self.proxy_username, self.proxy_password)).encode()).decode().strip()
        request_data += '\r\n'
        sock.sendall(request_data)
        response = httplib.HTTPResponse(sock)
        response.fp.close()
        response.fp = sock.makefile('rb', 0)
        response.begin()
        if response.status >= 400:
            raise httplib.BadStatusLine('%s %s %s' % (response.version, response.status, response.reason))
        return sock
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
                      proxy_port=None, proxy_username=None,
                      proxy_password=None, timeout=None):
    """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object

    Like socket.create_connection(), but connects to proxy
    before returning the socket object.

    dest_pair - 2-tuple of (IP/hostname, port).
    **proxy_args - Same args passed to socksocket.set_proxy().
    timeout - Optional socket timeout value, in seconds.
    """
    sock = socksocket()
    if isinstance(timeout, (int, float)):
        sock.settimeout(timeout)
    sock.set_proxy(proxy_type, proxy_addr, proxy_port,
                   proxy_username, proxy_password)
    sock.connect(dest_pair)
    return sock
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def connect(self, host='', port=0, timeout=-999):
        '''Connect to host.  Arguments are:
         - host: hostname to connect to (string, default previous host)
         - port: port to connect to (integer, default previous port)
        '''
        if host != '':
            self.host = host
        if port > 0:
            self.port = port
        if timeout != -999:
            self.timeout = timeout
        self.sock = socket.create_connection((self.host, self.port), self.timeout)
        self.af = self.sock.family
        self.file = self.sock.makefile('rb')
        self.welcome = self.getresp()
        return self.welcome
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it

        :return: a new socket connection
        """
        try:
            conn = socket.create_connection(
                (self.host, self.port),
                self.timeout,
                self.source_address,
            )
        except AttributeError: # Python 2.6
            conn = socket.create_connection(
                (self.host, self.port),
                self.timeout,
            )
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,
                        self.tcp_nodelay)
        return conn
项目: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
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
                      proxy_port=None, proxy_username=None,
                      proxy_password=None, timeout=None):
    """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object

    Like socket.create_connection(), but connects to proxy
    before returning the socket object.

    dest_pair - 2-tuple of (IP/hostname, port).
    **proxy_args - Same args passed to socksocket.set_proxy().
    timeout - Optional socket timeout value, in seconds.
    """
    sock = socksocket()
    if isinstance(timeout, (int, float)):
        sock.settimeout(timeout)
    sock.set_proxy(proxy_type, proxy_addr, proxy_port,
                   proxy_username, proxy_password)
    sock.connect(dest_pair)
    return sock
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def connect(self, host='', port=0, timeout=-999):
        '''Connect to host.  Arguments are:
         - host: hostname to connect to (string, default previous host)
         - port: port to connect to (integer, default previous port)
        '''
        if host != '':
            self.host = host
        if port > 0:
            self.port = port
        if timeout != -999:
            self.timeout = timeout
        self.sock = socket.create_connection((self.host, self.port), self.timeout)
        self.af = self.sock.family
        self.file = self.sock.makefile('rb')
        self.welcome = self.getresp()
        return self.welcome
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
    """Retrieve the certificate from the server at the specified address,
    and return it as a PEM-encoded string.
    If 'ca_certs' is specified, validate the server cert against it.
    If 'ssl_version' is specified, use it in the connection attempt."""

    host, port = addr
    if ca_certs is not None:
        cert_reqs = CERT_REQUIRED
    else:
        cert_reqs = CERT_NONE
    context = _create_stdlib_context(ssl_version,
                                     cert_reqs=cert_reqs,
                                     cafile=ca_certs)
    with closing(create_connection(addr)) as sock:
        with closing(context.wrap_socket(sock)) as sslsock:
            dercert = sslsock.getpeercert(True)
    return DER_cert_to_PEM_cert(dercert)
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def wait_net_port(ip, port, timeout, try_interval=2):
    LOG.debug("Waiting for {0}:{1} to become available.".format(ip, port))
    end = time.time() + timeout
    while time.time() < end:
        try:
            s = socket.create_connection((ip, port), timeout=5)
        except socket.timeout:
            # cannot connect after timeout
            continue
        except socket.error as ex:
            # cannot connect immediately (e.g. no route)
            # wait timeout before next try
            LOG.debug("Wait cycle msg: {0}".format(repr(ex)))
            time.sleep(try_interval)
            continue
        else:
            # success!
            s.close()
            return
    raise PublicPortWaitTimeoutException()
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def connect(self):
        "Connect to a host on a given (SSL) port."
        if hasattr(self, "timeout"):
            sock = socket.create_connection((self.host, self.port), self.timeout)
        else:
            sock = socket.create_connection((self.host, self.port))
        msg = "wrapping ssl socket; "
        if self.ca_certs:
            msg += "CA certificate file=%s" % self.ca_certs
        else:
            msg += "using system provided SSL certs"
        boto.log.debug(msg)
        self.sock = ssl.wrap_socket(sock, keyfile=self.key_file,
                                    certfile=self.cert_file,
                                    cert_reqs=ssl.CERT_REQUIRED,
                                    ca_certs=self.ca_certs)
        cert = self.sock.getpeercert()
        hostname = self.host.split(':', 0)[0]
        if not ValidateCertificateHostname(cert, hostname):
            raise InvalidCertificateException(hostname,
                                              cert,
                                              'remote hostname "%s" does not match '
                                              'certificate' % hostname)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _create_connection(host, port, connect_timeout):
    """
    Connect to a 2-tuple (host, port) and return
    the socket object.

    Args:
        2-tuple (host, port) and connection timeout
    Returns:
        Socket object
    """
    if sys.version_info < (2, 6):
        (family, _) = (_convert_host_to_ip(host))[0]
        connect_socket = socket.socket(family, socket.SOCK_STREAM)
        connect_socket.settimeout(connect_timeout)
        connect_socket.connect( (host, port) )
    else:
        connect_socket = socket.create_connection( (host, port), connect_timeout)
    return connect_socket
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def connect(self):
            "Connect to a host on a given (SSL) port."

            if hasattr(self, 'source_address'):
                sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
            else:
                sock = socket.create_connection((self.host, self.port), self.timeout)

            server_hostname = self.host
            # Note: self._tunnel_host is not available on py < 2.6 but this code
            # isn't used on py < 2.6 (lack of create_connection)
            if self._tunnel_host:
                self.sock = sock
                self._tunnel()
                server_hostname = self._tunnel_host

            if HAS_SSLCONTEXT:
                self.sock = self.context.wrap_socket(sock, server_hostname=server_hostname)
            elif HAS_URLLIB3_SNI_SUPPORT:
                self.sock = ssl_wrap_socket(sock, keyfile=self.key_file, cert_reqs=ssl.CERT_NONE, certfile=self.cert_file, ssl_version=PROTOCOL,
                        server_hostname=server_hostname)
            else:
                self.sock = ssl.wrap_socket(sock, keyfile=self.key_file, certfile=self.cert_file, ssl_version=PROTOCOL)
项目: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 _connect(self):
        "Create a TCP socket connection"
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)

                # connect
                sock.connect(socket_address)

                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()

        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list")
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def connect(self):
        """Connect to the host and port specified in __init__."""
        self.sock = socket.create_connection((self.host,self.port),
                                             self.timeout, self.source_address)

        if self._tunnel_host:
            self._tunnel()
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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()
            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def open(self, host = '', port = IMAP4_PORT):
        """Setup connection to remote server on "host:port"
            (default: localhost:standard IMAP4 port).
        This connection will be used by the routines:
            read, readline, send, shutdown.
        """
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port))
        self.file = self.sock.makefile('rb')
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def open(self, host = '', port = IMAP4_SSL_PORT):
            """Setup connection to remote server on "host:port".
                (default: localhost:standard IMAP4 SSL port).
            This connection will be used by the routines:
                read, readline, send, shutdown.
            """
            self.host = host
            self.port = port
            self.sock = socket.create_connection((host, port))
            self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
            self.file = self.sslobj.makefile('rb')