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


Python ssl.create_default_context函数代码示例

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


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

示例1: url_open_resp

def url_open_resp(url):
    global opener, login_user, login_pass
    if not opener:
        print "building opener"
        if login_user:
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        else:
            opener = urllib2.build_opener()
        urllib2.install_opener(opener)

    if login_user:
        params = None
        params = urllib.urlencode(dict(username=login_user,
                                       password=login_pass))

        if not accept_all_certs:
            response = urllib2.urlopen(url, data=params)
        else:
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            response = urllib2.urlopen(url, data=params, context=ctx)
        return response

    if not accept_all_certs:
        response = urllib2.urlopen(url)
    else:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        response = urllib2.urlopen(url, context=ctx)

    return response
开发者ID:orgcandman,项目名称:SearchMailman,代码行数:33,代码来源:SearchMailman.py

示例2: _InitSSLContext

  def _InitSSLContext(self, cafile=None,
                      disable_ssl_certificate_validation=False):
    """Creates a ssl.SSLContext with the given settings.

    Args:
      cafile: A str identifying the resolved path to the cafile. If not set,
        this will use the system default cafile.
      disable_ssl_certificate_validation: A boolean indicating whether
        certificate verification is disabled. For security purposes, it is
        highly recommended that certificate verification remain enabled.

    Returns:
      An ssl.SSLContext instance, or None if the version of Python being used
      doesn't support it.
    """
    # Attempt to create a context; this should succeed in Python 2 versions
    # 2.7.9+ and Python 3 versions 3.4+.
    try:
      if disable_ssl_certificate_validation:
        ssl._create_default_https_context = ssl._create_unverified_context
        ssl_context = ssl.create_default_context()
      else:
        ssl_context = ssl.create_default_context(cafile=cafile)
    except AttributeError:
      # Earlier versions lack ssl.create_default_context()
      # Rather than raising the exception, no context will be provided for
      # legacy support. Of course, this means no certificate validation is
      # taking place!
      return None

    return ssl_context
开发者ID:Precis,项目名称:googleads-python-lib,代码行数:31,代码来源:common.py

示例3: __init__

    def __init__(self, nexenta):
        cfg = ReadConfig()
        username = cfg.get_option(nexenta['hostname'], 'api_user')
        password = cfg.get_option(nexenta['hostname'], 'api_pass')
        self.nms_retry = cfg.get_option(nexenta['hostname'], 'nms_retry')

        if not username or not password:
            raise CritError("No connection info configured for %s" % nexenta['hostname'])
        if not self.nms_retry:
            self.nms_retry = 2
        
        ssl = cfg.get_option(nexenta['hostname'], 'api_ssl')
        insecure = cfg.get_option(nexenta['hostname'], 'api_ssl_insecure')
        self.https = False
        if ssl != "ON":
            protocol = 'http'
        else:
            import ssl 
            protocol = 'https'
            self.https = True
            if insecure == "ON":
                self.ctx = ssl.create_default_context()
                self.ctx.check_hostname = False
                self.ctx.verify_mode = ssl.CERT_NONE
            else:
                self.ctx = ssl.create_default_context()
            
        port = cfg.get_option(nexenta['hostname'], 'api_port')
        if not port:
            port = 2000

        self.base64_string = base64.encodestring('%s:%s' % (username, password))[:-1]
        self.url = '%s://%s:%s/rest/nms/ <%s://%s:%s/rest/nms/>' % (protocol, nexenta['ip'], port, protocol, 
                                                                    nexenta['ip'], port)
开发者ID:schubergphilis,项目名称:Check_Nexenta,代码行数:34,代码来源:check_nexenta.py

示例4: open_url

def open_url(url, timeout=None, verify=True, **kwargs):
  '''Returns a urllib.request object given a URL as a string
  Optional parameters include
  * timeout - Timeout value for request as int
  * verify  - Certificate validation as boolean
  * headers - Add many headers as Header_Name='Val', Header_Name2='Val2'
  '''
  req = urllib.request.Request(url)
  if type(kwargs) is dict:
    for key in kwargs.keys():
      header = key.replace('_', '-')
      req.add_header(header, kwargs[key])
  try:
    if verify:
      ctx = ssl.create_default_context(cafile=os.environ['SSL_CERT_FILE'])
      urlobj = urllib.request.urlopen(req, timeout=timeout, context=ctx)
    else:
      ctx = ssl.create_default_context()
      ctx.check_hostname = False
      ctx.verify_mode = ssl.CERT_NONE
      urlobj = urllib.request.urlopen(req, timeout=timeout, context=ctx)
    return urlobj
  except urllib.request.HTTPError as e:
    logging.error('HTTPError: %s for %s', str(e.code), url)
    if e.code == 304:
      return None
  except urllib.request.URLError as e:
    logging.error('URLError: %s for %s', str(e.reason), url)
  raise Exception('GetURL Failed')
开发者ID:komand,项目名称:plugin-sdk-python,代码行数:29,代码来源:helper.py

示例5: _setup_http_conn

def _setup_http_conn(url, cacert=None):
    """Prepare http connection object and return it."""
    (protocol, url) = url.split('://', 1)
    conn = None
    if protocol == 'http':
        port = 80
    else:
        port = 443
    if url.find('/') >= 0:
        (server, _) = url.split('/', 1)
    else:
        server = url
    if ':' in server:
        (server, portstr) = server.split(':', 1)
        port = int(portstr)
    if protocol == 'http':
        conn = httplib.HTTPConnection(server, port=port)
    elif protocol == 'https':
        try:
            ssl_context = ssl.create_default_context()
            if cacert is not None:
                ssl_context = ssl.create_default_context(cafile=cacert)
            conn = httplib.HTTPSConnection(server, port=port,
                                           context=ssl_context)
        except AttributeError:
            conn = httplib.HTTPSConnection(server, port, None, cacert)
    else:
        print "Error, unknown protocol %s" % protocol
        return None
    return conn
开发者ID:bne86,项目名称:shifter,代码行数:30,代码来源:dockerv2.py

示例6: setupHttpConn

 def setupHttpConn(self, url, cacert=None):
     (protocol, url) = url.split('://', 1)
     location = None
     conn = None
     port = 443
     if (url.find('/') >= 0):
         (server, location) = url.split('/', 1)
     else:
         server = url
     if ':' in server:
         (server, port) = server.split(':')
     if protocol == 'http':
         conn = httplib.HTTPConnection(server)
     elif protocol == 'https':
         try:
             sslContext = ssl.create_default_context()
             if cacert is not None:
                 sslContext = ssl.create_default_context(cafile=cacert)
             conn = httplib.HTTPSConnection(server, context=sslContext)
         except AttributeError:
             conn = httplib.HTTPSConnection(server, port, None, cacert)
     else:
         print "Error, unknown protocol %s" % protocol
         return None
     return conn
开发者ID:imatge-upc,项目名称:shifter,代码行数:25,代码来源:dockerv2.py

示例7: connect

    def connect(self):
        """
        Connect to a host on a given (SSL) port.
        If ca_file is pointing somewhere, use it to check Server Certificate.

        Redefined/copied and extended from httplib.py.
        """
        sock = self._create_connection((self.host, self.port),
                                       self.timeout, self.source_address)

        if self._tunnel_host:
            self.sock = sock
            self._tunnel()

        if self.ca_file:
            context = ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH,
                cafile=self.ca_file)
        else:
            context = ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH)

        if self.key_file or self.cert_file:
            context.load_cert_chain(certfile=self.cert_file,
                                    keyfile=self.key_file)

        self.sock = context.wrap_socket(sock, server_side=False,
                                        server_hostname=self.host)
开发者ID:jwiltshire,项目名称:nrpe-ng,代码行数:28,代码来源:http.py

示例8: verify_cafile

def verify_cafile(cafile=None, cadata=None):
    try:
        create_default_context(cafile=cafile, cadata=cadata)
    except IOError as e:
        if cafile:
            LOG.error('Invalid cafile %s: %s' % (cafile, e))
        else:
            LOG.error('Invalid cadata: %s' % e)
        sys.exit(1)
开发者ID:jtschichold,项目名称:minemeld-core,代码行数:9,代码来源:cacert_merge.py

示例9: compile

 def compile(cls, uri, relay=None):
     scheme, _, uri = uri.partition('://')
     url = urllib.parse.urlparse('s://'+uri)
     rawprotos = scheme.split('+')
     err_str, protos = proto.get_protos(rawprotos)
     if err_str:
         raise argparse.ArgumentTypeError(err_str)
     if 'ssl' in rawprotos or 'secure' in rawprotos:
         import ssl
         sslserver = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
         sslclient = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
         if 'ssl' in rawprotos:
             sslclient.check_hostname = False
             sslclient.verify_mode = ssl.CERT_NONE
     else:
         sslserver = sslclient = None
     protonames = [i.name for i in protos]
     if 'pack' in protonames and relay and relay != cls.DIRECT:
         raise argparse.ArgumentTypeError('pack protocol cannot relay to other proxy')
     urlpath, _, plugins = url.path.partition(',')
     urlpath, _, lbind = urlpath.partition('@')
     plugins = plugins.split(',') if plugins else None
     cipher, _, loc = url.netloc.rpartition('@')
     if cipher:
         from .cipher import get_cipher
         if ':' not in cipher:
             try:
                 cipher = base64.b64decode(cipher).decode()
             except Exception:
                 pass
             if ':' not in cipher:
                 raise argparse.ArgumentTypeError('userinfo must be "cipher:key"')
         err_str, cipher = get_cipher(cipher)
         if err_str:
             raise argparse.ArgumentTypeError(err_str)
         if plugins:
             from .plugin import get_plugin
             for name in plugins:
                 if not name: continue
                 err_str, plugin = get_plugin(name)
                 if err_str:
                     raise argparse.ArgumentTypeError(err_str)
                 cipher.plugins.append(plugin)
     match = cls.compile_rule(url.query) if url.query else None
     if loc:
         host_name, _, port = loc.partition(':')
         port = int(port) if port else (22 if 'ssh' in rawprotos else 8080)
     else:
         host_name = port = None
     return ProxyURI(protos=protos, rproto=protos[0], cipher=cipher, auth=url.fragment.encode(), \
                     match=match, bind=loc or urlpath, host_name=host_name, port=port, \
                     unix=not loc, lbind=lbind, sslclient=sslclient, sslserver=sslserver, \
                     alive=True, direct='direct' in protonames, tunnel='tunnel' in protonames, \
                     reuse='pack' in protonames or relay and relay.reuse, backward='in' in rawprotos, \
                     ssh='ssh' in rawprotos, relay=relay)
开发者ID:qwj,项目名称:python-proxy,代码行数:55,代码来源:server.py

示例10: getSSLcontext

def getSSLcontext(servercert="", serverkey="", clientcert="", clientkey="", cacerts="", keypassword=""):
    """creates an SSL context and caches it, so you have to set the parameters correctly before doing anything"""
    global __ssl_client_context, __ssl_server_context
    if not ssl:
        raise ValueError("SSL requested but ssl module is not available")
    else:
        # Theoretically, the SSL support works on python versions older than the ones checked below.
        # however, a few important security changes were included in these versions
        # (disabling vulnerable cyphers and protocols by default). So change this at your own peril.
        if sys.version_info < (2, 7, 11):
            raise RuntimeError("need Python 2.7.11 or newer to properly use SSL")
        if (3, 0) < sys.version_info < (3, 4, 4):
            raise RuntimeError("need Python 3.4.4 or newer to properly use SSL")
    if servercert:
        if clientcert:
            raise ValueError("can't have both server cert and client cert")
        # server context
        if __ssl_server_context:
            return __ssl_server_context
        if not os.path.isfile(servercert):
            raise IOError("server cert file not found")
        if serverkey and not os.path.isfile(serverkey):
            raise IOError("server key file not found")
        __ssl_server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        __ssl_server_context.load_cert_chain(servercert, serverkey or None, keypassword or None)
        if cacerts:
            if os.path.isdir(cacerts):
                __ssl_server_context.load_verify_locations(capath=cacerts)
            else:
                __ssl_server_context.load_verify_locations(cafile=cacerts)
        if config.SSL_REQUIRECLIENTCERT:
            __ssl_server_context.verify_mode = ssl.CERT_REQUIRED   # 2-way ssl, server+client certs
        else:
            __ssl_server_context.verify_mode = ssl.CERT_NONE   # 1-way ssl, server cert only
        return __ssl_server_context
    else:
        # client context
        if __ssl_client_context:
            return __ssl_client_context
        __ssl_client_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        if clientcert:
            if not os.path.isfile(clientcert):
                raise IOError("client cert file not found")
            __ssl_client_context.load_cert_chain(clientcert, clientkey or None, keypassword or None)
        if cacerts:
            if os.path.isdir(cacerts):
                __ssl_client_context.load_verify_locations(capath=cacerts)
            else:
                __ssl_client_context.load_verify_locations(cafile=cacerts)
        return __ssl_client_context
开发者ID:Peque,项目名称:Pyro4,代码行数:50,代码来源:socketutil.py

示例11: create_thriftpy_context

def create_thriftpy_context(server_side=False, ciphers=None):
    """Backport create_default_context for older python versions.

    The SSLContext has some default security options, you can disable them
    manually, for example::

        from thriftpy.transport import _ssl
        context = _ssl.create_thriftpy_context()
        context.options &= ~_ssl.OP_NO_SSLv3

    You can do the same to enable compression.
    """
    if MODERN_SSL:
        if server_side:
            context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        else:
            context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)

        if ciphers:
            context.set_ciphers(ciphers)

    else:
        context = SSLContext(ssl.PROTOCOL_SSLv23)
        context.options |= OP_NO_SSLv2
        context.options |= OP_NO_SSLv3
        context.options |= OP_NO_COMPRESSION

        # server/client default options
        if server_side:
            context.options |= OP_CIPHER_SERVER_PREFERENCE
            context.options |= OP_SINGLE_DH_USE
            context.options |= OP_SINGLE_ECDH_USE
        else:
            context.verify_mode = ssl.CERT_REQUIRED
            # context.check_hostname = True
            warnings.warn(
                "ssl check hostname support disabled, upgrade your python",
                InsecurePlatformWarning)

        # Platform-specific: Python 2.6
        if getattr(context, 'supports_set_ciphers', True):
            if ciphers:
                context.set_ciphers(ciphers)
        else:
            warnings.warn("ssl ciphers support disabled, upgrade your python",
                          InsecurePlatformWarning)

    return context
开发者ID:AllanDaemon,项目名称:thriftpy,代码行数:48,代码来源:_ssl.py

示例12: teardown_http_get

def teardown_http_get(e):
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    p = os.path.dirname(os.path.abspath(__file__))
    response = urllib2.urlopen('https://localhost:8088/shutdown', context=ctx)
    html = response.read()
开发者ID:9mrcookie9,项目名称:Arduino,代码行数:7,代码来源:test_http_client.py

示例13: create_ssl_context

def create_ssl_context():
    if not CONF.use_ssl:
        return

    MIN_VERSION = (2, 7, 9)

    if sys.version_info < MIN_VERSION:
        LOG.warning(_LW('Unable to use SSL in this version of Python: '
                        '%{current}, please ensure your version of Python is '
                        'greater than %{min} to enable this feature.'),
                    {'current': '.'.join(map(str, sys.version_info[:3])),
                     'min': '.'.join(map(str, MIN_VERSION))})
        return

    context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
    if CONF.ssl_cert_path and CONF.ssl_key_path:
        try:
            context.load_cert_chain(CONF.ssl_cert_path, CONF.ssl_key_path)
        except IOError as exc:
            LOG.warning(_LW('Failed to load certificate or key from defined '
                            'locations: %{cert} and %{key}, will continue to '
                            'run with the default settings: %{exc}'),
                        {'cert': CONF.ssl_cert_path, 'key': CONF.ssl_key_path,
                         'exc': exc})
        except ssl.SSLError as exc:
            LOG.warning(_LW('There was a problem with the loaded certificate '
                            'and key, will continue to run with the default '
                            'settings: %s'), exc)
    return context
开发者ID:mandre,项目名称:ironic-inspector,代码行数:29,代码来源:main.py

示例14: __init__

    def __init__(self, apikey, server):
        self.apikey = apikey
        self.server = server

        self.ctx = ssl.create_default_context()
        self.ctx.check_hostname = False
        self.ctx.verify_mode = ssl.CERT_NONE
开发者ID:morgenroth,项目名称:unifi-video-api,代码行数:7,代码来源:__init__.py

示例15: _additional_handlers

    def _additional_handlers(self):

        handlers = []

        if self.session.get('proxy'):
            protocol, host, port = self._get_proxy()

            if protocol and host and port:
                handlers.append(
                    sockshandler.SocksiPyHandler(
                        protocol,
                        host,
                        port
                    )
                )
            else:
                raise ChannelException(messages.channels.error_proxy_format)

        # Skip certificate checks
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        
        handlers.append(urllib2.HTTPSHandler(context=ctx))

        return handlers
开发者ID:apal7,项目名称:weevely3,代码行数:26,代码来源:channel.py


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