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


Python ssl._create_default_https_context方法代码示例

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


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

示例1: retrieve_status_page

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def retrieve_status_page(user, password, url):

    try:
        ssl._create_unverified_context
    except AttributeError:
        pass
    else:
        ssl._create_default_https_context = ssl._create_unverified_context

    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, url, user, password)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)

    req = urllib2.Request(url)
    try:
        response = urllib2.urlopen(req)
        return response.read()
    except Exception:
        raise CrawlError("can't access to http://%s", url) 
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:23,代码来源:liberty_crawler.py

示例2: _download_via_urllib

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def _download_via_urllib(url, file_path, show_progress, disable_ssl_verification):
    reporthook = None
    if show_progress:
        reporthook = _UrlRetrieveReportHook()
    if disable_ssl_verification:
        import ssl
        # TODO: Remove this or properly implement disabling SSL certificate verification
        orig_https_context = ssl._create_default_https_context #pylint: disable=protected-access
        ssl._create_default_https_context = ssl._create_unverified_context #pylint: disable=protected-access
    try:
        urllib.request.urlretrieve(url, str(file_path), reporthook=reporthook)
    finally:
        # Try to reduce damage of hack by reverting original HTTPS context ASAP
        if disable_ssl_verification:
            ssl._create_default_https_context = orig_https_context #pylint: disable=protected-access
    if show_progress:
        print() 
开发者ID:Eloston,项目名称:ungoogled-chromium,代码行数:19,代码来源:downloads.py

示例3: _request

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def _request(url, json_decode=True):
    ssl._create_default_https_context = ssl._create_unverified_context
    req = urllib.request.Request(url)

    try:
        result = urllib.request.urlopen(req)
    except urllib.error.HTTPError as e:
        raise RuntimeError("HTTP error ({})".format(str(e.code)))
    except urllib.error.URLError as e:
        raise RuntimeError("URL error ({})".format(str(e.reason)))

    data = result.read()
    result.close()

    if json_decode:
        try:
            return json.JSONDecoder().decode(data.decode())
        except Exception as e:
            raise RuntimeError("API response has invalid JSON format ({})"
                               .format(str(e.reason)))

    return data.decode() 
开发者ID:nutti,项目名称:Screencast-Keys,代码行数:24,代码来源:addon_updator.py

示例4: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
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_default_https_context()
            will_verify = context.verify_mode != ssl.CERT_NONE
            if check_hostname is None:
                check_hostname = context.check_hostname
            if 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:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:client.py

示例5: loadUcsConfig

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def loadUcsConfig():
	from ConfigParser import SafeConfigParser

	configFile = os.path.join(os.path.dirname(__file__),"UcsConfig.cfg")
	parser = SafeConfigParser()
	parser.read(configFile)

	sslProtocol = parser.get('ssl_connection', 'ssl_protocol').strip('"')
	isVerifyCertificate = parser.getboolean('ssl_connection', 'verify_certificate')

	if not sys.version_info < (2, 6):
		from functools import partial
		import ssl

		sslProtocolDict = {'TLSv1': ssl.PROTOCOL_TLSv1}

		ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=sslProtocolDict[sslProtocol])

		if not sys.version_info < (2, 7, 9) and not isVerifyCertificate:
			ssl._create_default_https_context = ssl._create_unverified_context 
开发者ID:CiscoUcs,项目名称:UcsPythonSDK,代码行数:22,代码来源:UcsBase.py

示例6: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def __init__(self):

        # Whether we already have a valid HTTP session with the remote server
        self.http_session_valid = False

        # PEP 476: verify HTTPS certificates by default (implemented from Python 2.7.9)
        # https://bugs.python.org/issue22417
        if sys.hexversion >= 0x02070900:
            import ssl
            ssl._create_default_https_context = ssl._create_unverified_context

        # https://mechanicalsoup.readthedocs.io/
        self.browser = mechanicalsoup.StatefulBrowser()

        # Set custom user agent header
        self.browser.set_user_agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36')

        self.searchurl = self.baseurl + 'einsteiger' #?lang={language}'
        self.accessurl = self.baseurl + 'register:showalleverfahrenstabellen?AKZ={number}&lang={language}'

        self.reference_pattern = re.compile('.*\?AKZ=(.+?)&.*') 
开发者ID:ip-tools,项目名称:patzilla,代码行数:23,代码来源:dpmaregister.py

示例7: downloadFile

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def downloadFile(url, destination, x, y, z):

		url = Utils.qualifyURL(url, x, y, z)

		code = 0

		# monkey patching SSL certificate issue
		# DONT use it in a prod/sensitive environment
		ssl._create_default_https_context = ssl._create_unverified_context

		try:
			path, response = urllib.request.urlretrieve(url, destination)
			code = 200
		except urllib.error.URLError as e:
			if not hasattr(e, "code"):
				print(e)
				code = -1
			else:
				code = e.code

		return code 
开发者ID:AliFlux,项目名称:MapTilesDownloader,代码行数:23,代码来源:utils.py

示例8: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def __init__(self, host, user, password, wine, use_ssl=False,
                 verify_ssl=False, port=80):
        super(oxcSERVER, self).__init__()
        self.host = host
        self.hostname = host
        self.wine = wine
        self.user = user
        self.password = password
        self.ssl = use_ssl
        self.verify_ssl = verify_ssl
        self.port = port

        self.dbg_track_num = 0

        if not verify_ssl and hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context 
开发者ID:OpenXenManager,项目名称:openxenmanager,代码行数:18,代码来源:oxcSERVER.py

示例9: get_version

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def get_version():
    version = platform.python_version()

    if version >= '3':
        import urllib.request as openurl
    else:
        import urllib2 as openurl

    socket.setdefaulttimeout(1.2)
    ssl._create_default_https_context = ssl._create_unverified_context

    url = "https://service-qgphxt7y-1253970226.gz.apigw.tencentcs.com/release/client_daily_task"
    post_data = "{}"
    request = openurl.Request(data=post_data.encode("utf-8") if version >= '3' else post_data,
                              url=url) if version >= '3' else openurl.Request(url, data=post_data)
    response = json.loads(json.loads(openurl.urlopen(request).read().decode("utf-8")))
    release_version = response["version"]
    message = response["message"]
    release_version_list = release_version.split(".")
    local_version_list = __version__.split(".")
    for i in range(0, len(release_version_list)):
        if int(release_version_list[i]) > int(local_version_list[i]):
            return {"version": release_version, "message": message}

    return {} 
开发者ID:tencentyun,项目名称:scfcli,代码行数:27,代码来源:daily_task.py

示例10: ensure_ca_load

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_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

示例11: patch

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def patch():
    if hasattr(ssl, '_create_unverified_context'):
        # Python >=2.7.9
        ssl._create_default_https_context = ssl._create_unverified_context
    else:
        # Python <2.7.9
        ssl.wrap_socket = sslwrap(ssl.wrap_socket) 
开发者ID:rapid7,项目名称:nexpose-client-python,代码行数:9,代码来源:sslfix.py

示例12: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def __init__(self, host, port=None, key_file=None, cert_file=None,
                     strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                     source_address=None, context=None):
            HTTPConnection.__init__(self, host, port, strict, timeout,
                                    source_address)
            self.key_file = key_file
            self.cert_file = cert_file
            if context is None:
                context = ssl._create_default_https_context()
            if key_file or cert_file:
                context.load_cert_chain(cert_file, key_file)
            self._context = context 
开发者ID:war-and-code,项目名称:jawfish,代码行数:14,代码来源:httplib.py

示例13: _checkout

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def _checkout(self, local_dir):
        url = self.config.get("url")
        logger.info("Downloading...")
        user_agent = self.config.get("user-agent")
        if not self.config.get("verify_cert", True):
            import ssl

            ssl._create_default_https_context = ssl._create_unverified_context

        if user_agent and sys.version_info[0] >= 3:
            opener = urllib.build_opener()
            opener.addheaders = [("User-agent", user_agent)]
            urllib.install_opener(opener)
        try:
            (filename, headers) = urllib.urlretrieve(url)
        except (URLError, HTTPError) as e:
            raise RuntimeError("Failed to download '{}'. '{}'".format(url, e.reason))

        filetype = self.config.get("filetype")
        if filetype == "tar":
            t = tarfile.open(filename)
            t.extractall(local_dir)
        elif filetype == "zip":
            with zipfile.ZipFile(filename, "r") as z:
                z.extractall(local_dir)
        elif filetype == "simple":
            _filename = url.rsplit("/", 1)[1]
            os.makedirs(local_dir)
            shutil.copy2(filename, os.path.join(local_dir, _filename))
        else:
            raise RuntimeError(
                "Unknown file type '" + filetype + "' in [provider] section"
            ) 
开发者ID:olofk,项目名称:fusesoc,代码行数:35,代码来源:url.py

示例14: invoke_ssl_no_verify

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def invoke_ssl_no_verify():
    try:
        _create_unverified_https_context = ssl._create_unverified_context
        
    except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
        pass
    else:
    # Handle target environment that doesn't support HTTPS verification
        ssl._create_default_https_context = _create_unverified_https_context 
开发者ID:jeorryb,项目名称:netapp-ansible,代码行数:12,代码来源:ntap_util.py

示例15: __init__

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import _create_default_https_context [as 别名]
def __init__(self, cloud_info, inf):
        self.cloud = cloud_info
        """Data about the Cloud Provider."""
        self.inf = inf
        """Infrastructure this CloudConnector is associated with."""
        self.logger = logging.getLogger('CloudConnector')
        """Logger object."""
        self.error_messages = ""
        """String with error messages to be shown to the user."""
        self.verify_ssl = Config.VERIFI_SSL
        """Verify SSL connections """
        if not self.verify_ssl:
            # To avoid errors with host certificates
            try:
                import ssl
                ssl._create_default_https_context = ssl._create_unverified_context
            except Exception:
                pass

            try:
                # To avoid annoying InsecureRequestWarning messages in some Connectors
                import requests.packages
                from requests.packages.urllib3.exceptions import InsecureRequestWarning
                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            except Exception:
                pass 
开发者ID:grycap,项目名称:im,代码行数:28,代码来源:CloudConnector.py


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