Python socket.create_connection() Examples

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

Example 1
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 2
Project: sauna   Author: NicolasLM   File: memcached.py    (BSD 2-Clause "Simplified" License) View Source Project 7 votes vote down vote up
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 
Example 3
Project: hostapd-mana   Author: adde88   File: ssl.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 4
Project: greenstalk   Author: mayhewj   File: greenstalk.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 5
Project: zeronet-debian   Author: bashrc   File: socks.py    (license) View Source Project 7 votes vote down vote up
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 
Example 6
Project: imcsdk   Author: CiscoUcs   File: imcdriver.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 7
Project: kinect-2-libras   Author: inessadl   File: ftplib.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 8
Project: Flask_Blog   Author: sugarguo   File: connection.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 9
Project: voctomix-outcasts   Author: CarlFK   File: generate-cut-list.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 10
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: https.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 11
Project: sauna   Author: NicolasLM   File: postfix.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
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') 
Example 12
Project: abusehelper   Author: Exploit-install   File: imapbot.py    (license) View Source Project 6 votes vote down vote up
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") 
Example 13
Project: abusehelper   Author: Exploit-install   File: imapbot.py    (license) View Source Project 6 votes vote down vote up
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") 
Example 14
Project: MUTE   Author: K4YT3X   File: mute.py    (license) View Source Project 6 votes vote down vote up
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 
Example 15
Project: hostapd-mana   Author: adde88   File: ftplib.py    (license) View Source Project 6 votes vote down vote up
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 
Example 16
Project: azure-python-siteextensions   Author: Azure   File: ssl.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 17
Project: azure-python-siteextensions   Author: Azure   File: ssl.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 18
Project: llk   Author: Tycx2ry   File: sfp_portscan_tcp.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 19
Project: bossimage   Author: cloudboss   File: core.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 20
Project: sslkill   Author: m4n3dw0lf   File: sslkill.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 21
Project: xfinity-usage   Author: jantman   File: xfinity_usage.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 22
Project: Bethesda_SublimeFO4   Author: Scrivener07   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
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 
Example 23
Project: cc98   Author: zjuchenyuan   File: xinling.py    (license) View Source Project 6 votes vote down vote up
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 
Example 24
Project: watchmen   Author: lycclsltt   File: test_connection.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 25
Project: spiderfoot   Author: wi-fi-analyzer   File: sfp_portscan_tcp.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 26
Project: touch-pay-client   Author: HackPucBemobi   File: test_connection.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 27
Project: capnpy   Author: antocuni   File: test_buffered.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 28
Project: tidb-ansible   Author: pingcap   File: wait_for.py    (license) View Source Project 6 votes vote down vote up
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 
Example 29
Project: tinychain   Author: jamesob   File: tinychain.py    (license) View Source Project 6 votes vote down vote up
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} 
Example 30
Project: Intranet-Penetration   Author: yuxiaokui   File: proxylib.py    (license) View Source Project 6 votes vote down vote up
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 
Example 31
Project: Intranet-Penetration   Author: yuxiaokui   File: socks.py    (license) View Source Project 6 votes vote down vote up
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 
Example 32
Project: Intranet-Penetration   Author: yuxiaokui   File: ftplib.py    (license) View Source Project 6 votes vote down vote up
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 
Example 33
Project: flasky   Author: RoseOu   File: connection.py    (license) View Source Project 6 votes vote down vote up
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 
Example 34
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 35
Project: MKFQ   Author: maojingios   File: socks.py    (license) View Source Project 6 votes vote down vote up
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 
Example 36
Project: MKFQ   Author: maojingios   File: ftplib.py    (license) View Source Project 6 votes vote down vote up
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 
Example 37
Project: MKFQ   Author: maojingios   File: ssl.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 38
Project: kuberdock-platform   Author: cloudlinux   File: utils.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 39
Project: cuny-bdif   Author: aristotle-tek   File: https_connection.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 40
Project: DevOps   Author: YoLoveLife   File: wait_for.py    (license) View Source Project 6 votes vote down vote up
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 
Example 41
Project: DevOps   Author: YoLoveLife   File: urls.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 42
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 43
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 44
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 45
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 46
Project: gimel   Author: Alephbet   File: connection.py    (MIT License) View Source Project 5 votes vote down vote up
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") 
Example 47
Project: kinect-2-libras   Author: inessadl   File: httplib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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() 
Example 48
Project: kinect-2-libras   Author: inessadl   File: httplib.py    (Apache License 2.0) View Source Project 5 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()
            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) 
Example 49
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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') 
Example 50
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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')