本文整理汇总了Python中ssl._create_stdlib_context函数的典型用法代码示例。如果您正苦于以下问题:Python _create_stdlib_context函数的具体用法?Python _create_stdlib_context怎么用?Python _create_stdlib_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_create_stdlib_context函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
开发者ID:vlevit,项目名称:mbwatch,代码行数:26,代码来源:imapidle.py
示例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
开发者ID:tyru,项目名称:vim-gista,代码行数:25,代码来源:github.py
示例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
开发者ID:cjw296,项目名称:python-workfront,代码行数:26,代码来源:script.py
示例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)
开发者ID:francois-wellenreiter,项目名称:cpython,代码行数:29,代码来源:ftplib.py
示例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
开发者ID:collinanderson,项目名称:ensurepip,代码行数:26,代码来源:client.py
示例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))
开发者ID:albertogviana,项目名称:jenkins_middleware,代码行数:7,代码来源:jenkins_api.py
示例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()))
开发者ID:planctechnologies,项目名称:gns3-gui,代码行数:32,代码来源:websocket_client.py
示例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)
开发者ID:rdrewd,项目名称:cpython,代码行数:56,代码来源:selector_events.py
示例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()
开发者ID:aquaristar,项目名称:python-broker,代码行数:10,代码来源:hello.py
示例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)
开发者ID:FFMG,项目名称:myoddweb.piger,代码行数:55,代码来源:smtplib.py
示例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)
开发者ID:cjw296,项目名称:python-workfront,代码行数:11,代码来源:test_session.py
示例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()
开发者ID:Anovi-Soft,项目名称:Python,代码行数:11,代码来源:pop3.py
示例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)
开发者ID:SantoKo,项目名称:RPI3-Desktop,代码行数:11,代码来源:nntplib.py
示例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'))
开发者ID:Kelauni22,项目名称:Meeple,代码行数:11,代码来源:test_httplib.py
示例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
开发者ID:sahlinet,项目名称:httptest,代码行数:14,代码来源:utils.py
示例16: __init__
def __init__(self, host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None):
if ssl_context is not None and keyfile is not None:
raise ValueError("ssl_context and keyfile arguments are mutually "
"exclusive")
if ssl_context is not None and certfile is not None:
raise ValueError("ssl_context and certfile arguments are mutually "
"exclusive")
self.keyfile = keyfile
self.certfile = certfile
if ssl_context is None:
ssl_context = ssl._create_stdlib_context(certfile=certfile,
keyfile=keyfile)
self.ssl_context = ssl_context
IMAP4.__init__(self, host, port)
开发者ID:Alex9029,项目名称:cpython,代码行数:15,代码来源:imaplib.py
示例17: __init__
def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=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")
self.keyfile = keyfile
self.certfile = certfile
if context is None:
context = ssl._create_stdlib_context(certfile=certfile,
keyfile=keyfile)
self.context = context
POP3.__init__(self, host, port, timeout)
开发者ID:Illirgway,项目名称:cpython,代码行数:15,代码来源:poplib.py
示例18: __init__
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, context=None,
source_address=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, check_hostname=False,
**kw):
HTTPConnection.__init__(self, host, port, timeout=timeout, source_address=source_address, **kw)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_stdlib_context()
self._context = context
self._check_hostname = check_hostname
self.is_verified = False
开发者ID:rdbhost,项目名称:yieldfromUrllib3,代码行数:15,代码来源:connection.py
示例19: urlopen
def urlopen(url, data = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT,
*, cafile = None, capath = None, cadefault = False):
global _opener
if cafile or capath or cadefault:
if not _have_ssl:
raise ValueError('SSL support not available')
context = ssl._create_stdlib_context(cert_regs = ssl.CRET_REQUIRED,
cafile = cafile,
capath = capath)
https_handler = HTTPHandler(context = context, check_hostname = True)
opener = buile_opener(https_handler)
elif _opener is None:
_opener = opener = build_opener()
else:
opener = _opener
return opener.open(url, data, timeout)
开发者ID:changjf,项目名称:Pythons,代码行数:16,代码来源:requestcopy.py
示例20: test_ssl
def test_ssl(self):
def application(environ, start_response):
status = "200 OK"
headers = [("Content-type", "text/plain; charset=utf-8")]
start_response(status, headers)
return [b"hello ssl"]
server_ssl_context = make_adhoc_ssl_context()
client_ssl_context = ssl._create_stdlib_context() # TODO
with TestServer(application, ssl_context=server_ssl_context) as server:
client = HTTPSConnection(server.host, server.port, context=client_ssl_context)
client.request("GET", "/")
resp = client.getresponse()
self.assertEqual(resp.status, 200)
开发者ID:bwhmather,项目名称:verktyg-server,代码行数:16,代码来源:test_testing.py
注:本文中的ssl._create_stdlib_context函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论