當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。