本文整理匯總了Python中ssl.SSLContext方法的典型用法代碼示例。如果您正苦於以下問題:Python ssl.SSLContext方法的具體用法?Python ssl.SSLContext怎麽用?Python ssl.SSLContext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ssl
的用法示例。
在下文中一共展示了ssl.SSLContext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: StartSSL
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def StartSSL( self,
keyfile = None,
certfile = None,
server_side = False,
cert_reqs = 0,
ca_certs = None ) :
if not hasattr(ssl, 'SSLContext') :
raise XAsyncTCPClientException('StartSSL : This SSL implementation is not supported.')
if self.IsSSL :
raise XAsyncTCPClientException('StartSSL : SSL already started.')
try :
self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
self._asyncSocketsPool.NotifyNextReadyForReading(self, False)
self._socket = ssl.wrap_socket( self._socket,
keyfile = keyfile,
certfile = certfile,
server_side = server_side,
cert_reqs = cert_reqs,
ca_certs = ca_certs,
do_handshake_on_connect = False )
except Exception as ex :
raise XAsyncTCPClientException('StartSSL : %s' % ex)
self._doSSLHandshake()
# ------------------------------------------------------------------------
示例2: StartSSLContext
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def StartSSLContext(self, sslContext, serverSide=False) :
if not hasattr(ssl, 'SSLContext') :
raise XAsyncTCPClientException('StartSSLContext : This SSL implementation is not supported.')
if not isinstance(sslContext, ssl.SSLContext) :
raise XAsyncTCPClientException('StartSSLContext : "sslContext" is incorrect.')
if self.IsSSL :
raise XAsyncTCPClientException('StartSSLContext : SSL already started.')
try :
self._asyncSocketsPool.NotifyNextReadyForWriting(self, False)
self._asyncSocketsPool.NotifyNextReadyForReading(self, False)
self._socket = sslContext.wrap_socket( self._socket,
server_side = serverSide,
do_handshake_on_connect = False )
except Exception as ex :
raise XAsyncTCPClientException('StartSSLContext : %s' % ex)
self._doSSLHandshake()
# ------------------------------------------------------------------------
示例3: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, **_3to2kwargs):
if 'check_hostname' in _3to2kwargs: check_hostname = _3to2kwargs['check_hostname']; del _3to2kwargs['check_hostname']
else: check_hostname = None
if 'context' in _3to2kwargs: context = _3to2kwargs['context']; del _3to2kwargs['context']
else: context = None
super(HTTPSConnection, self).__init__(host, port, strict, timeout,
source_address)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
# Some reasonable defaults
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = will_verify
elif check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
self._context = context
self._check_hostname = check_hostname
示例4: make_https_server
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def make_https_server(case, certfile=CERTFILE, host=HOST, handler_class=None):
# we assume the certfile contains both private key and certificate
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain(certfile)
server = HTTPSServerThread(context, host, handler_class)
flag = threading.Event()
server.start(flag)
flag.wait()
def cleanup():
if support.verbose:
sys.stdout.write('stopping HTTPS server\n')
server.stop()
if support.verbose:
sys.stdout.write('joining HTTPS thread\n')
server.join()
case.addCleanup(cleanup)
return server
示例5: urlopen
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **_3to2kwargs):
if 'cadefault' in _3to2kwargs: cadefault = _3to2kwargs['cadefault']; del _3to2kwargs['cadefault']
else: cadefault = False
if 'capath' in _3to2kwargs: capath = _3to2kwargs['capath']; del _3to2kwargs['capath']
else: capath = None
if 'cafile' in _3to2kwargs: cafile = _3to2kwargs['cafile']; del _3to2kwargs['cafile']
else: cafile = None
global _opener
if cafile or capath or cadefault:
if not _have_ssl:
raise ValueError('SSL support not available')
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2
context.verify_mode = ssl.CERT_REQUIRED
if cafile or capath:
context.load_verify_locations(cafile, capath)
else:
context.set_default_verify_paths()
https_handler = HTTPSHandler(context=context, check_hostname=True)
opener = build_opener(https_handler)
elif _opener is None:
_opener = opener = build_opener()
else:
opener = _opener
return opener.open(url, data, timeout)
示例6: ssl_wrap_socket
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
"""Returns an ``ssl.SSLSocket`` wrapping the given socket.
``ssl_options`` may be either an `ssl.SSLContext` object or a
dictionary (as accepted by `ssl_options_to_context`). Additional
keyword arguments are passed to ``wrap_socket`` (either the
`~ssl.SSLContext` method or the `ssl` module function as
appropriate).
"""
context = ssl_options_to_context(ssl_options)
if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext):
if server_hostname is not None and getattr(ssl, 'HAS_SNI'):
# Python doesn't have server-side SNI support so we can't
# really unittest this, but it can be manually tested with
# python3.2 -m tornado.httpclient https://sni.velox.ch
return context.wrap_socket(socket, server_hostname=server_hostname,
**kwargs)
else:
return context.wrap_socket(socket, **kwargs)
else:
return ssl.wrap_socket(socket, **dict(context, **kwargs))
示例7: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def __init__(self, *args, **kwargs):
"""The ``ssl_options`` keyword argument may either be an
`ssl.SSLContext` object or a dictionary of keywords arguments
for `ssl.wrap_socket`
"""
self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults)
super(SSLIOStream, self).__init__(*args, **kwargs)
self._ssl_accepting = True
self._handshake_reading = False
self._handshake_writing = False
self._ssl_connect_callback = None
self._server_hostname = None
# If the socket is already connected, attempt to start the handshake.
try:
self.socket.getpeername()
except socket.error:
pass
else:
# Indirectly start the handshake, which will run on the next
# IOLoop iteration and then the real IO state will be set in
# _handle_events.
self._add_io_state(self.io_loop.WRITE)
示例8: _new_socket
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def _new_socket(self):
transport_socket = socketlib.socket(
socketlib.AF_INET, socketlib.SOCK_STREAM
)
if self.certfile and self.cafile and self.keyfile:
context = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=self.cafile
)
context.check_hostname = False
context.load_cert_chain(
certfile=self.certfile,
keyfile=self.keyfile,
password=self.password,
)
sock = context.wrap_socket(transport_socket, server_side=False)
else:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
sock = context.wrap_socket(transport_socket)
sock.settimeout(self._timeout)
return sock
示例9: _create_ssl_ctx
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def _create_ssl_ctx(self, sslp):
if isinstance(sslp, ssl.SSLContext):
return sslp
ca = sslp.get('ca')
capath = sslp.get('capath')
hasnoca = ca is None and capath is None
ctx = ssl.create_default_context(cafile=ca, capath=capath)
ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True)
ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
if 'cert' in sslp:
ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
if 'cipher' in sslp:
ctx.set_ciphers(sslp['cipher'])
ctx.options |= ssl.OP_NO_SSLv2
ctx.options |= ssl.OP_NO_SSLv3
return ctx
示例10: load_ssl_context
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def load_ssl_context(cert_file, pkey_file=None, protocol=None):
"""Loads SSL context from cert/private key files and optional protocol.
Many parameters are directly taken from the API of
:py:class:`ssl.SSLContext`.
:param cert_file: Path of the certificate to use.
:param pkey_file: Path of the private key to use. If not given, the key
will be obtained from the certificate file.
:param protocol: One of the ``PROTOCOL_*`` constants in the stdlib ``ssl``
module. Defaults to ``PROTOCOL_SSLv23``.
"""
if protocol is None:
protocol = ssl.PROTOCOL_SSLv23
ctx = _SSLContext(protocol)
ctx.load_cert_chain(cert_file, pkey_file)
return ctx
示例11: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def __init__(
self,
url: str,
timeout: int = 30,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
default_headers: Dict[str, str] = {},
):
"""API client for Incoming Webhooks and response_url
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
:param timeout: request timeout (in seconds)
:param ssl: ssl.SSLContext to use for requests
:param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000)
:param default_headers: request headers to add to all requests
"""
self.url = url
self.timeout = timeout
self.ssl = ssl
self.proxy = proxy
self.default_headers = default_headers
示例12: test_good_certificate
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def test_good_certificate():
# Disable due to https://github.com/urllib3/urllib3/issues/497
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.SubjectAltNameWarning)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.load_cert_chain('tests/ssl/goodkey.crt', 'tests/ssl/goodkey.key')
server = Process(target=run_simple_https_server, args=(ssl_context,))
server.start()
time.sleep(0.5)
try:
s = requests.Session()
s.mount('https://localhost:8080/', HTTPSAdapter())
r = s.get('https://localhost:8080/', verify='tests/ssl/rootCA.crt')
assert r.text == 'Passed'
server.terminate()
except Exception:
server.terminate()
raise
示例13: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def __init__(self, target):
# Target comes as protocol://target:port/path
self.target = target
proto, host, path = target.split(':')
host = host[2:]
self.path = '/' + path.split('/', 1)[1]
if proto.lower() == 'https':
#Create unverified (insecure) context
try:
uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
self.session = HTTPSConnection(host,context=uv_context)
except AttributeError:
#This does not exist on python < 2.7.11
self.session = HTTPSConnection(host)
else:
self.session = HTTPConnection(host)
self.lastresult = None
示例14: _getConnection
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def _getConnection(self):
if self.__connection is not None:
return self.__connection
url = self.__url
if url.scheme == 'http':
connection = http.client.HTTPConnection(url.hostname, url.port)
elif url.scheme == 'https':
ctx = None if self.__sslVerify else ssl.SSLContext(ssl.PROTOCOL_SSLv23)
connection = http.client.HTTPSConnection(url.hostname, url.port,
context=ctx)
else:
raise BuildError("Unsupported URL scheme: '{}'".format(url.schema))
self.__connection = connection
return connection
示例15: test_context
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import SSLContext [as 別名]
def test_context(self):
self.client.quit()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
context=ctx)
self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
context=ctx)
self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
keyfile=CERTFILE, context=ctx)
self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
self.client.connect(self.server.host, self.server.port)
self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
self.client.auth()
self.assertIs(self.client.sock.context, ctx)
self.assertIsInstance(self.client.sock, ssl.SSLSocket)
self.client.prot_p()
sock = self.client.transfercmd('list')
try:
self.assertIs(sock.context, ctx)
self.assertIsInstance(sock, ssl.SSLSocket)
finally:
sock.close()