我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.create_connection()。
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
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
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)
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)
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
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
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
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()
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()
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')
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")
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
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)
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()
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)
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)
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()
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
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
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()
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)
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)
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
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}
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
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
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()
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)
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)
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
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
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")
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()
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)
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')
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')