当前位置: 首页>>代码示例>>Python>>正文


Python ssl.create_default_context方法代码示例

本文整理汇总了Python中ssl.create_default_context方法的典型用法代码示例。如果您正苦于以下问题:Python ssl.create_default_context方法的具体用法?Python ssl.create_default_context怎么用?Python ssl.create_default_context使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ssl的用法示例。


在下文中一共展示了ssl.create_default_context方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: EnableSSL

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def EnableSSL(self, certFile, keyFile, caFile=None) :
        import ssl
        if not hasattr(ssl, 'SSLContext') :
            raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
        if not isinstance(certFile, str) or len(certFile) == 0 :
            raise ValueError('"certFile" must be a not empty string.')
        if not isinstance(keyFile, str) or len(keyFile) == 0 :
            raise ValueError('"keyFile" must be a not empty string.')
        if caFile is not None and not isinstance(caFile, str) :
            raise ValueError('"caFile" must be a string or None.')
        self._validateChangeConf()
        try :
            ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
                                              cafile = caFile )
        except :
            raise ValueError('"caFile" must indicate a valid PEM file.')
        try :
            ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
        except :
            raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
        self._sslContext = ctx
        if self._bindAddr[1] == 80 :
            self._bindAddr = (self._bindAddr[0], 443)

    # ------------------------------------------------------------------------ 
开发者ID:jczic,项目名称:MicroWebSrv2,代码行数:27,代码来源:microWebSrv2.py

示例2: jenkins

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def jenkins(url, port):
    try:
        cli_port = False
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            output = urllib2.urlopen('https://'+url+':'+port+"/jenkins/", context=ctx, timeout=8).info()
            cli_port = int(output['X-Jenkins-CLI-Port'])
        except urllib2.HTTPError, e:
            if e.getcode() == 404:
                try:
                    output = urllib2.urlopen('https://'+url+':'+port, context=ctx, timeout=8).info()
                    cli_port = int(output['X-Jenkins-CLI-Port'])
                except:
                    pass
        except:
            pass 
开发者ID:johndekroon,项目名称:serializekiller,代码行数:20,代码来源:serializekiller.py

示例3: _new_socket

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [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 
开发者ID:greenbone,项目名称:python-gvm,代码行数:25,代码来源:connections.py

示例4: _create_ssl_ctx

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [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 
开发者ID:MarcelloLins,项目名称:ServerlessCrawler-VancouverRealState,代码行数:18,代码来源:connections.py

示例5: _connect

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def _connect(self):
        """
        Connects a ssl socket.
        """
        self._connect_socket()
        try:
            ctx = ssl.create_default_context()
            if not self.verify_cert:
                ctx.verify_mode = ssl.CERT_OPTIONAL
            if not self.verify_addr:
                ctx.check_hostname = False
            self._sock = ctx.wrap_socket(self._base_sock,
                                         server_hostname=self.address)
        except ssl.SSLError:
            LOG.error('could not establish SSL connection')
            raise ClientError('could not establish SSL connection') 
开发者ID:vshn,项目名称:tikapy,代码行数:18,代码来源:__init__.py

示例6: _certifi_ssl_context

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def _certifi_ssl_context(self):
        if (sys.version_info.major == 2 and sys.hexversion >= 0x02070900 or
           sys.version_info.major == 3 and sys.hexversion >= 0x03040300):
            where = certifi.where()
            self._log(DEBUG1, 'certifi %s: %s', certifi.__version__, where)
            return ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH,
                cafile=where)
        else:
            return None


#
# XXX USE OF cloud_ssl_context() IS DEPRECATED!
#
# If your operating system certificate store is out of date you can
# install certifi (https://pypi.python.org/pypi/certifi) and its CA
# bundle will be used for SSL server certificate verification when
# ssl_context is None.
# 
开发者ID:PaloAltoNetworks,项目名称:terraform-templates,代码行数:22,代码来源:wfapi.py

示例7: connect

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        self.logger.info('Connecting to %s', self._prefix)
        account = 'opensuse'
        server = 'rabbit.opensuse.org'
        if self._prefix == 'suse':
            account = 'suse'
            server = 'rabbit.suse.de'
        credentials = pika.PlainCredentials(account, account)
        context = ssl.create_default_context()
        ssl_options = pika.SSLOptions(context, server)
        parameters = pika.ConnectionParameters(server, 5671, '/', credentials, ssl_options=ssl_options, socket_timeout=10)
        return pika.SelectConnection(parameters,
                                     on_open_callback=self.on_connection_open) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:22,代码来源:PubSubConsumer.py

示例8: aiohttp_session

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def aiohttp_session(*, auth: Optional[Auth] = None, **kwargs: Any) -> ClientSession:
    headers = {'User-Agent': USER_AGENT}
    if auth:
        headers['Authorization'] = auth.encode()

    # setup SSL
    cafile = config.get('ca')
    if not cafile:
        cafile = certifi.where()
    ssl_context = create_default_context(cafile=cafile)
    try:
        connector = TCPConnector(ssl=ssl_context)
    except TypeError:
        connector = TCPConnector(ssl_context=ssl_context)

    return ClientSession(headers=headers, connector=connector, **kwargs) 
开发者ID:dephell,项目名称:dephell,代码行数:18,代码来源:networking.py

示例9: certificateInformation

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def certificateInformation(url,dosyaAdi):
    try:
        context = ssl.create_default_context()
        server = context.wrap_socket(socket.socket(), server_hostname=url)
        server.connect((url, 443))
        certificate = server.getpeercert()
        print "[+]Certificate Serial Number: ",certificate.get('serialNumber')
        print "[+]Certificate SSL Version:", certificate.get('version')
        print "[+]Certificate:",certificate
        raporIcerik="[+]Certificate Serial Number: "+str(certificate.get('serialNumber'))+"\n"
        raporIcerik+="[+]Certificate SSL Version:"+str(certificate.get('version'))+"\n"
        raporIcerik+="[+]Certificate:"+str(certificate)+"\n"
        rapor = open(dosyaAdi, "a")
        rapor.write(raporIcerik)
        rapor.close()
    except:
        pass 
开发者ID:tulpar,项目名称:tulpar,代码行数:19,代码来源:tulpar.py

示例10: request

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def request(url, data=None, headers={}, cookies={}, auth=None):
 if cookies:
  headers['Cookie'] = '; '.join(quote(k) + '=' + quote(v) for (k, v) in cookies.items())
 request = Request(str(url), data, headers)
 manager = HTTPPasswordMgrWithDefaultRealm()
 if auth:
  manager.add_password(None, request.get_full_url(), auth[0], auth[1])
 handlers = [HTTPBasicAuthHandler(manager), HTTPDigestAuthHandler(manager)]
 try:
  import certifi, ssl
  handlers.append(HTTPSHandler(context=ssl.create_default_context(cafile=certifi.where())))
 except:
  # App engine
  pass
 response = build_opener(*handlers).open(request)
 cj = CookieJar()
 cj.extract_cookies(response, request)
 headers = dict(response.headers)
 raw_contents = response.read()
 contents = raw_contents.decode(headers.get('charset', 'latin1'))
 return HttpResponse(urlparse(response.geturl()), contents, raw_contents, headers, dict((c.name, c.value) for c in cj)) 
开发者ID:ma1co,项目名称:Sony-PMCA-RE,代码行数:23,代码来源:http.py

示例11: urlopen

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
            cafile=None, capath=None, cadefault=False, context=None):
    global _opener
    if cafile or capath or cadefault:
        if context is not None:
            raise ValueError(
                "You can't pass both context and any of cafile, capath, and "
                "cadefault"
            )
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH,
                                             cafile=cafile,
                                             capath=capath)
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif context:
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:urllib2.py

示例12: make_https_server

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def make_https_server(case, context=None, certfile=CERTFILE,
                      host=HOST, handler_class=None):
    if context is None:
        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    # We assume the certfile contains both private key and certificate
    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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:ssl_servers.py

示例13: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def __init__(self, *args, **kwargs):
        self.ssl_context = kwargs.pop('ssl_context', None)
        self.cipherSuite = kwargs.pop('cipherSuite', None)
        self.source_address = kwargs.pop('source_address', None)

        if self.source_address:
            if isinstance(self.source_address, str):
                self.source_address = (self.source_address, 0)

            if not isinstance(self.source_address, tuple):
                raise TypeError(
                    "source_address must be IP address string or (ip, port) tuple"
                )

        if not self.ssl_context:
            self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            self.ssl_context.set_ciphers(self.cipherSuite)
            self.ssl_context.set_ecdh_curve('prime256v1')
            self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)

        super(CipherSuiteAdapter, self).__init__(**kwargs)

    # ------------------------------------------------------------------------------- # 
开发者ID:a4k-openproject,项目名称:a4kScrapers,代码行数:25,代码来源:cloudscraper.py

示例14: myFunction

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def myFunction():
  # We create this context so that we can crawl 
  # https sites
  myssl = ssl.create_default_context();
  myssl.check_hostname=False
  myssl.verify_mode=ssl.CERT_NONE
  with Timer() as t:
    req = Request('https://tutorialedge.net', headers={'User-Agent': 'Mozilla/5.0'})
    response = urlopen(req, context=myssl)

  print("Elapsed Time: {} seconds".format(t.elapsed)) 
开发者ID:PacktPublishing,项目名称:Learning-Concurrency-in-Python,代码行数:13,代码来源:timeitContext.py

示例15: ensure_ca_load

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import create_default_context [as 别名]
def ensure_ca_load():
	if ssl.create_default_context().cert_store_stats()['x509_ca'] == 0:
		if has_certifi:
			def create_certifi_context(purpose = ssl.Purpose.SERVER_AUTH, *, cafile = None, capath = None, cadata = None):
				return ssl.create_default_context(purpose, cafile = certifi.where())

			ssl._create_default_https_context = create_certifi_context

		else:
			print('%s[!]%s Python was unable to load any CA bundles. Additionally, the fallback %scertifi%s module is not available. Install it with %spip3 install certifi%s for TLS connection support.' % (Fore.RED, Fore.RESET, Fore.GREEN, Fore.RESET, Fore.GREEN, Fore.RESET))
			sys.exit(-1)


# parse image[:tag] | archive argument 
开发者ID:RoliSoft,项目名称:WSL-Distribution-Switcher,代码行数:16,代码来源:utils.py


注:本文中的ssl.create_default_context方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。