本文整理匯總了Python中socket.connect方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.connect方法的具體用法?Python socket.connect怎麽用?Python socket.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類socket
的用法示例。
在下文中一共展示了socket.connect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _try_passwordless_paramiko
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavailable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
示例2: _try_passwordless_paramiko
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
示例3: _handle_connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _handle_connect(self):
# Call the superclass method to check for errors.
super(SSLIOStream, self)._handle_connect()
if self.closed():
return
# When the connection is complete, wrap the socket for SSL
# traffic. Note that we do this by overriding _handle_connect
# instead of by passing a callback to super().connect because
# user callbacks are enqueued asynchronously on the IOLoop,
# but since _handle_events calls _handle_connect immediately
# followed by _handle_write we need this to be synchronous.
#
# The IOLoop will get confused if we swap out self.socket while the
# fd is registered, so remove it now and re-register after
# wrap_socket().
self.io_loop.remove_handler(self.socket)
old_state = self._state
self._state = None
self.socket = ssl_wrap_socket(self.socket, self._ssl_options,
server_hostname=self._server_hostname,
do_handshake_on_connect=False)
self._add_io_state(old_state)
示例4: _cache_credentials
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _cache_credentials(self, source, credentials, connect=True):
"""Add credentials to the database authentication cache
for automatic login when a socket is created. If `connect` is True,
verify the credentials on the server first.
"""
if source in self.__auth_credentials:
# Nothing to do if we already have these credentials.
if credentials == self.__auth_credentials[source]:
return
raise OperationFailure('Another user is already authenticated '
'to this database. You must logout first.')
if connect:
member = self.__ensure_member()
sock_info = self.__socket(member)
try:
# Since __check_auth was called in __socket
# there is no need to call it here.
auth.authenticate(credentials, sock_info, self.__simple_command)
sock_info.authset.add(credentials)
finally:
member.maybe_return_socket(sock_info)
self.__auth_credentials[source] = credentials
示例5: end_request
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def end_request(self):
"""**DEPRECATED**: Undo :meth:`start_request`. If :meth:`end_request`
is called as many times as :meth:`start_request`, the request is over
and this thread's connection returns to the pool. Extra calls to
:meth:`end_request` have no effect.
Ending a request allows the :class:`~socket.socket` that has
been reserved for this thread by :meth:`start_request` to be returned to
the pool. Other threads will then be able to re-use that
:class:`~socket.socket`. If your application uses many threads, or has
long-running threads that infrequently perform MongoDB operations, then
judicious use of this method can lead to performance gains. Care should
be taken, however, to make sure that :meth:`end_request` is not called
in the middle of a sequence of operations in which ordering is
important. This could lead to unexpected results.
"""
member = self.__member # Don't try to connect if disconnected.
if member:
member.end_request()
示例6: resolve
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def resolve(
self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> Awaitable[List[Tuple[int, Any]]]:
"""Resolves an address.
The ``host`` argument is a string which may be a hostname or a
literal IP address.
Returns a `.Future` whose result is a list of (family,
address) pairs, where address is a tuple suitable to pass to
`socket.connect <socket.socket.connect>` (i.e. a ``(host,
port)`` pair for IPv4; additional fields may be present for
IPv6). If a ``callback`` is passed, it will be run with the
result as an argument when it is complete.
:raises IOError: if the address cannot be resolved.
.. versionchanged:: 4.4
Standardized all implementations to raise `IOError`.
.. versionchanged:: 6.0 The ``callback`` argument was removed.
Use the returned awaitable object instead.
"""
raise NotImplementedError()
示例7: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def connect(
self, address: Tuple, server_hostname: str = None
) -> "Future[SSLIOStream]":
self._server_hostname = server_hostname
# Ignore the result of connect(). If it fails,
# wait_for_handshake will raise an error too. This is
# necessary for the old semantics of the connect callback
# (which takes no arguments). In 6.0 this can be refactored to
# be a regular coroutine.
# TODO: This is trickier than it looks, since if write()
# is called with a connect() pending, we want the connect
# to resolve before the write. Or do we care about this?
# (There's a test for it, but I think in practice users
# either wait for the connect before performing a write or
# they don't care about the connect Future at all)
fut = super(SSLIOStream, self).connect(address)
fut.add_done_callback(lambda f: f.exception())
return self.wait_for_handshake()
示例8: _finishInit
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _finishInit(self, whenDone, skt, error, reactor):
"""
Called by subclasses to continue to the stage of initialization where
the socket connect attempt is made.
@param whenDone: A 0-argument callable to invoke once the connection is
set up. This is L{None} if the connection could not be prepared
due to a previous error.
@param skt: The socket object to use to perform the connection.
@type skt: C{socket._socketobject}
@param error: The error to fail the connection with.
@param reactor: The reactor to use for this client.
@type reactor: L{twisted.internet.interfaces.IReactorTime}
"""
if whenDone:
self._commonConnection.__init__(self, skt, None, reactor)
reactor.callLater(0, whenDone)
else:
reactor.callLater(0, self.failIfNotConnected, error)
示例9: failIfNotConnected
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def failIfNotConnected(self, err):
"""
Generic method called when the attempts to connect failed. It basically
cleans everything it can: call connectionFailed, stop read and write,
delete socket related members.
"""
if (self.connected or self.disconnected or
not hasattr(self, "connector")):
return
self._stopReadingAndWriting()
try:
self._closeSocket(True)
except AttributeError:
pass
else:
self._collectSocketDetails()
self.connector.connectionFailed(failure.Failure(err))
del self.connector
示例10: _resolveIPv6
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def _resolveIPv6(ip, port):
"""
Resolve an IPv6 literal into an IPv6 address.
This is necessary to resolve any embedded scope identifiers to the relevant
C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
more information.
@param ip: An IPv6 address literal.
@type ip: C{str}
@param port: A port number.
@type port: C{int}
@return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
IPv6 address.
@raise socket.gaierror: if either the IP or port is not numeric as it
should be.
"""
return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4]
示例11: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def connect(self):
"Connects to the Redis server if not already connected"
if self._sock:
return
try:
sock = self._connect()
except socket.error:
e = sys.exc_info()[1]
raise ConnectionError(self._error_message(e))
self._sock = sock
try:
self.on_connect()
except RedisError:
# clean up after any error in on_connect
self.disconnect()
raise
# run any user callbacks. right now the only internal callback
# is for pubsub channel/pattern resubscription
for callback in self._connect_callbacks:
callback(self)
示例12: send_packed_command
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def send_packed_command(self, command):
"Send an already packed command to the Redis server"
if not self._sock:
self.connect()
try:
if isinstance(command, str):
command = [command]
for item in command:
self._sock.sendall(item)
except socket.timeout:
self.disconnect()
raise TimeoutError("Timeout writing to socket")
except socket.error:
e = sys.exc_info()[1]
self.disconnect()
if len(e.args) == 1:
errno, errmsg = 'UNKNOWN', e.args[0]
else:
errno = e.args[0]
errmsg = e.args[1]
raise ConnectionError("Error %s while writing to socket. %s." %
(errno, errmsg))
except:
self.disconnect()
raise
示例13: resolve
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
"""Resolves an address.
The ``host`` argument is a string which may be a hostname or a
literal IP address.
Returns a `.Future` whose result is a list of (family,
address) pairs, where address is a tuple suitable to pass to
`socket.connect <socket.socket.connect>` (i.e. a ``(host,
port)`` pair for IPv4; additional fields may be present for
IPv6). If a ``callback`` is passed, it will be run with the
result as an argument when it is complete.
:raises IOError: if the address cannot be resolved.
.. versionchanged:: 4.4
Standardized all implementations to raise `IOError`.
.. deprecated:: 5.1
The ``callback`` argument is deprecated and will be removed in 6.0.
Use the returned awaitable object instead.
"""
raise NotImplementedError()
示例14: test_ssh_connection_with_password
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def test_ssh_connection_with_password(self, ssh_mock):
hook = SSHHook(remote_host='remote_host',
port='port',
username='username',
password='password',
timeout=10,
key_file='fake.file')
with hook.get_conn():
ssh_mock.return_value.connect.assert_called_once_with(
hostname='remote_host',
username='username',
password='password',
key_filename='fake.file',
timeout=10,
compress=True,
port='port',
sock=None,
look_for_keys=True
)
示例15: test_ssh_connection_without_password
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import connect [as 別名]
def test_ssh_connection_without_password(self, ssh_mock):
hook = SSHHook(remote_host='remote_host',
port='port',
username='username',
timeout=10,
key_file='fake.file')
with hook.get_conn():
ssh_mock.return_value.connect.assert_called_once_with(
hostname='remote_host',
username='username',
key_filename='fake.file',
timeout=10,
compress=True,
port='port',
sock=None,
look_for_keys=True
)