本文整理汇总了Python中ssl._create_stdlib_context函数的典型用法代码示例。如果您正苦于以下问题:Python _create_stdlib_context函数的具体用法?Python _create_stdlib_context怎么用?Python _create_stdlib_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_create_stdlib_context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: starttls
def starttls(con, ssl_context=None):
"""Python3's imaplib starttls port for Python2."""
name = 'STARTTLS'
if getattr(con, '_tls_established', False):
raise con.abort('TLS session already established')
if name not in con.capabilities:
raise con.abort('TLS not supported by server')
# Generate a default SSL context if none was passed.
if ssl_context is None:
ssl_context = ssl._create_stdlib_context()
tag = con._new_tag()
_send(con, '%s %s' % (tag, name))
token = None
while token != tag:
token, resp, text = _recv(con)
if resp == 'OK':
con.sock = ssl_context.wrap_socket(con.sock, server_hostname=con.host)
con.file = con.sock.makefile('rb')
con._tls_established = True
# update capabilities
typ, dat = con.capability()
if dat == [None]:
raise con.error('no CAPABILITY response from server')
con.capabilities = tuple(dat[-1].upper().split())
else:
raise con.error("Couldn't establish TLS session")
示例2: request
def request(url, headers={}, method=None):
if method:
if sys.version_info.major >= 3:
req = Request(url, headers=headers, method=method)
else:
req = Request(url, headers=headers)
req.get_method = lambda: method
else:
req = Request(url, headers=headers)
if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context()
elif hasattr(ssl, '_create_stdlib_context'):
context = ssl._create_stdlib_context()
elif hasattr(ssl, 'SSLContext'):
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
else:
context = None
if context:
res = urlopen(req, context=context)
else:
res = urlopen(req)
if not hasattr(res, 'getheader'):
# urllib2 does not have getheader
res.getheader = lambda name, self=res: self.info().getheader(name)
return res
示例3: script_setup
def script_setup(parser):
args = parser.parse_args()
if any(getattr(args, name)!= parser.get_default(name)
for name in ('protocol', 'domain', 'version')) and args.url:
parser.error('--url can not be used with '
'--protocol, --domain or --version')
logging.basicConfig(level=args.log_level)
if args.unsafe_certs:
ssl_context = ssl._create_stdlib_context()
else:
ssl_context = None
if args.url:
session = Session(None,
url_template=args.url,
ssl_context=ssl_context)
else:
session = Session(protocol=args.protocol,
domain=args.domain,
api_version=args.version,
ssl_context=ssl_context)
return args, session
示例4: __init__
def __init__(
self,
host="",
user="",
passwd="",
acct="",
keyfile=None,
certfile=None,
context=None,
timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
):
if context is not None and keyfile is not None:
raise ValueError("context and keyfile arguments are mutually " "exclusive")
if context is not None and certfile is not None:
raise ValueError("context and certfile arguments are mutually " "exclusive")
if keyfile is not None or certfile is not None:
import warnings
warnings.warn(
"keyfile and certfile are deprecated, use a" "custom context instead", DeprecationWarning, 2
)
self.keyfile = keyfile
self.certfile = certfile
if context is None:
context = ssl._create_stdlib_context(self.ssl_version, certfile=certfile, keyfile=keyfile)
self.context = context
self._prot_p = False
FTP.__init__(self, host, user, passwd, acct, timeout, source_address)
示例5: __init__
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
*,
context=None,
check_hostname=None
):
super(HTTPSConnection, self).__init__(host, port, timeout, source_address)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_stdlib_context()
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
示例6: __init__
def __init__(self, url, username=None, password=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
super().__init__(url, username, password, timeout)
# Setting ssl key verificationas false
context = ssl._create_stdlib_context(check_hostname=False)
unverified_handler = HTTPSHandler(context=context, check_hostname=False)
install_opener(build_opener(unverified_handler))
示例7: connect
def connect(self):
log.debug('In SecureWebSocketClient.connect()')
import ssl
import socket
from .tunnel import tunnel
if self.use_ssl:
self.login_url = "https://{host}:{port}/login".format(host=self.host, port=self.port)
self.version_url = "https://{host}:{port}/version".format(host=self.host, port=self.port)
self.ssl_options = {'ca_certs': self._ca_file}
context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED, cafile=self._ca_file)
self.https_handler = urllib.request.HTTPSHandler(context=context, check_hostname=False)
else:
self.login_url = "http://{host}:{port}/login".format(host=self.host, port=self.port)
self.version_url = "http://{host}:{port}/version".format(host=self.host, port=self.port)
self.ssl_options = {}
self.https_handler = urllib.request.HTTPHandler()
self.cookie_processor = urllib.request.HTTPCookieProcessor()
self.opener = urllib.request.build_opener(self.https_handler, self.cookie_processor)
self.check_server_version()
data = urllib.parse.urlencode({'name': self._auth_user, 'password': self._auth_password}).encode('utf-8')
f = self.opener.open(self.login_url, data, socket._GLOBAL_DEFAULT_TIMEOUT)
log.debug('login result: {}'.format(f.read()))
self._connect()
log.debug(self.sock)
self._tunnel = tunnel.Tunnel(self.host, 22, username='root', client_key=self._ssh_pkey)
log.debug('tunnel status: {}'.format(self._tunnel.is_connected()))
示例8: __init__
def __init__(
self,
loop,
rawsock,
protocol,
sslcontext,
waiter=None,
server_side=False,
server_hostname=None,
extra=None,
server=None,
):
if ssl is None:
raise RuntimeError("stdlib ssl module not available")
if server_side:
if not sslcontext:
raise ValueError("Server side ssl needs a valid SSLContext")
else:
if not sslcontext:
# Client side may pass ssl=True to use a default
# context; in that case the sslcontext passed is None.
# The default is the same as used by urllib with
# cadefault=True.
if hasattr(ssl, "_create_stdlib_context"):
sslcontext = ssl._create_stdlib_context(
cert_reqs=ssl.CERT_REQUIRED, check_hostname=bool(server_hostname)
)
else:
# Fallback for Python 3.3.
sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslcontext.options |= ssl.OP_NO_SSLv2
sslcontext.set_default_verify_paths()
sslcontext.verify_mode = ssl.CERT_REQUIRED
wrap_kwargs = {"server_side": server_side, "do_handshake_on_connect": False}
if server_hostname and not server_side and ssl.HAS_SNI:
wrap_kwargs["server_hostname"] = server_hostname
sslsock = sslcontext.wrap_socket(rawsock, **wrap_kwargs)
super().__init__(loop, sslsock, protocol, extra, server)
self._server_hostname = server_hostname
self._waiter = waiter
self._sslcontext = sslcontext
self._paused = False
# SSL-specific extra info. (peercert is set later)
self._extra.update(sslcontext=sslcontext)
if self._loop.get_debug():
logger.debug("%r starts SSL handshake", self)
start_time = self._loop.time()
else:
start_time = None
self._on_handshake(start_time)
示例9: callWebService
def callWebService(pURL,pSOAPEnvelope,pMethod,pSOAPAction):
encoded_request = pSOAPEnvelope.encode('utf-8')
headers={"Content-Type":"text/xml; charset=UTF-8","Content-Length":len(encoded_request),"SOAPAction":pSOAPAction}
request = uc.Request(pURL,encoded_request,headers)
context = ssl._create_stdlib_context()
response = uc.urlopen(request,context=context)
data = response.read()
#print (data)
response.close()
return data.decode()
示例10: starttls
def starttls(self, keyfile=None, certfile=None, context=None):
"""Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
"""
self.ehlo_or_helo_if_needed()
if not self.has_extn("starttls"):
raise SMTPNotSupportedError(
"STARTTLS extension not supported by server.")
(resp, reply) = self.docmd("STARTTLS")
if resp == 220:
if not _have_ssl:
raise RuntimeError("No SSL support included in this Python")
if context is not None and keyfile is not None:
raise ValueError("context and keyfile arguments are mutually "
"exclusive")
if context is not None and certfile is not None:
raise ValueError("context and certfile arguments are mutually "
"exclusive")
if keyfile is not None or certfile is not None:
import warnings
warnings.warn("keyfile and certfile are deprecated, use a "
"custom context instead", DeprecationWarning, 2)
if context is None:
context = ssl._create_stdlib_context(certfile=certfile,
keyfile=keyfile)
self.sock = context.wrap_socket(self.sock,
server_hostname=self._host)
self.file = None
# RFC 3207:
# The client MUST discard any knowledge obtained from
# the server, such as the list of SMTP service extensions,
# which was not obtained from the TLS negotiation itself.
self.helo_resp = None
self.ehlo_resp = None
self.esmtp_features = {}
self.does_esmtp = 0
else:
# RFC 3207:
# 501 Syntax error (no parameters allowed)
# 454 TLS not available due to temporary reason
raise SMTPResponseException(resp, reply)
return (resp, reply)
示例11: test_insecure_context
def test_insecure_context(self):
context = ssl._create_stdlib_context()
session = Session('test', ssl_context=context)
self.server.add(
url='/login',
params='method=GET',
response='{"data": "foo"}',
ssl_context=context
)
compare(session.get('/login'), expected='foo')
self.server.assert_called(times=1)
示例12: __init__
def __init__(self, host,
ssl=True,
port=None,
timeout=_GLOBAL_DEFAULT_TIMEOUT):
if port is None:
port = POP3PORTSSL if ssl else POP3PORT
self.sock = create_connection((host, port), timeout)
if ssl:
self.sock = _create_stdlib_context().wrap_socket(self.sock)
self.read_sock = self.sock.makefile('rb')
self.first_message = self.get_answer()
示例13: _encrypt_on
def _encrypt_on(sock, context, hostname):
"""Wrap a socket in SSL/TLS. Arguments:
- sock: Socket to wrap
- context: SSL context to use for the encrypted connection
Returns:
- sock: New, encrypted socket.
"""
# Generate a default SSL context if none was passed.
if context is None:
context = ssl._create_stdlib_context()
return context.wrap_socket(sock, server_hostname=hostname)
示例14: test_networked_noverification
def test_networked_noverification(self):
# Switch off cert verification
import ssl
test_support.requires('network')
with test_support.transient_internet('self-signed.pythontest.net'):
context = ssl._create_stdlib_context()
h = httplib.HTTPSConnection('self-signed.pythontest.net', 443,
context=context)
h.request('GET', '/')
resp = h.getresponse()
self.assertIn('nginx', resp.getheader('server'))
示例15: getcert
def getcert(addr, timeout=None):
"""Retrieve server's certificate at the specified address (host, port)."""
# it is similar to ssl.get_server_certificate() but it returns a dict
# and it verifies ssl unconditionally, assuming create_default_context does
context = ssl._create_stdlib_context()
context.set_ciphers(("HIGH:-aNULL:-eNULL:-PSK:RC4-SHA:RC4-MD5"))
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CA_CERTS)
sock = socket.create_connection(addr, timeout=timeout)
sslsock = context.wrap_socket(sock, server_hostname=addr[0])
cert = sslsock.getpeercert()
sock.close()
return cert