Python ssl 模块,_create_default_https_context() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ssl._create_default_https_context()

项目:pythonUnifiAPI    作者:delian    | 项目源码 | 文件源码
def __init__(self, username=None, password=None, version=None, debug=None,
                 requesttype=None, baseurl=None, site=None):
        if username:
            self.username = username
        if password:
            self.password = password
        if version:
            self.version = version
        if debug:
            self.debug = debug
        if requesttype:
            self.requesttype = requesttype
        if baseurl:
            self.baseurl = baseurl
        if site:
            self.site = site

        ssl._create_default_https_context = ssl._create_unverified_context # This is the way to allow unverified SSL
        self.cj = http.cookiejar.CookieJar()
        opener = urllib.request.build_opener(urllib.request.HTTPHandler(debuglevel=1 if self.debug else 0),
                                             urllib.request.HTTPSHandler(debuglevel=1 if self.debug else 0),
                                             urllib.request.HTTPCookieProcessor(self.cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        urllib.request.install_opener(opener)
项目:pythonUnifiAPI    作者:delian    | 项目源码 | 文件源码
def __init__(self, username=None, password=None, debug=None,
                 requesttype=None, baseurl=None):
        if username:
            self.username = username
        if password:
            self.password = password
        if debug:
            self.debug = debug
        if requesttype:
            self.requesttype = requesttype
        if baseurl:
            self.baseurl = baseurl

        ssl._create_default_https_context = ssl._create_unverified_context # This is the way to allow unverified SSL
        self.cj = http.cookiejar.CookieJar()
        opener = urllib.request.build_opener(urllib.request.HTTPHandler(debuglevel=1 if self.debug else 0),
                                             urllib.request.HTTPSHandler(debuglevel=1 if self.debug else 0),
                                             urllib.request.HTTPCookieProcessor(self.cj))
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        urllib.request.install_opener(opener)
项目:mimesis    作者:lk-geimfari    | 项目源码 | 文件源码
def download_image(url: str = '', save_path: str = '',
                   unverified_ctx: bool = False) -> Union[None, str]:
    """Download image and save in current directory on local machine.

    :param str url: URL to image.
    :param str save_path: Saving path.
    :param bool unverified_ctx: Create unverified context.
    :return: Image name.
    :rtype: str or None
    """
    if unverified_ctx:
        ssl._create_default_https_context = ssl._create_unverified_context

    if url is not None:
        image_name = url.rsplit('/')[-1]
        request.urlretrieve(url, save_path + image_name)
        return image_name
    return None
项目:Cisco-Showroom-RoomControl    作者:gbraux    | 项目源码 | 文件源码
def SetCMSRecording(callID, state):

    ssl._create_default_https_context = ssl._create_unverified_context
    conn = http.client.HTTPSConnection(Config.cmsFqdn)

    if (state == True):
        payload = "recording=true"
    else:
        payload = "recording=false"

    headers = {
        'authorization': Config.cmsGenericAuthRealm,
        'content-type': "application/x-www-form-urlencoded",
        'cache-control': "no-cache",
        'postman-token': "b5f016ed-5e19-d311-563e-c6aa7fdaa591"
        }

    conn.request("PUT", "/api/v1/calls/" + callID, payload, headers)

    res = conn.getresponse()
    data = res.read()

    print(data.decode("utf-8"))
    print("Recording Bit Set")
项目:zacui    作者:yoyopie    | 项目源码 | 文件源码
def index(request):
    if request.method == "GET":
        try:
            ssl._create_default_https_context = ssl._create_unverified_context

            opener = wdf_urllib.build_opener(
                wdf_urllib.HTTPCookieProcessor(CookieJar()))
            wdf_urllib.install_opener(opener)
        except:
            pass
        uuid = getUUID()
        url = 'https://login.weixin.qq.com/qrcode/' + uuid
        params = {
            't': 'webwx',
            '_': int(time.time()),
        }

        request = getRequest(url=url, data=urlencode(params))
        response = wdf_urllib.urlopen(request)
        context = {
            'uuid': uuid,
            'response': response.read(),
            'delyou': '',
            }
        return render_to_response('index.html', context)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def create_api():
    """create a twitter api"""
    from twitter import OAuth, Twitter

    from app import APP_INSTANCE as app
    access_token = app.get_config('api.twitter.access_token')
    access_secret = app.get_config('api.twitter.access_secret')
    consumer_key = app.get_config('api.twitter.consumer_key')
    consumer_secret = app.get_config('api.twitter.consumer_secret')

    # temporary fix for certificate error
    ssl._create_default_https_context = ssl._create_unverified_context

    oauth = OAuth(access_token, access_secret, consumer_key, consumer_secret)

    # Initiate the connection to Twitter API
    return Twitter(auth=oauth)
项目:deb-python-eventlet    作者:openstack    | 项目源码 | 文件源码
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
项目:Starbot    作者:StarbotDiscord    | 项目源码 | 文件源码
def cache_download(url, filename, caller='', ssl_enabled=True):
    '''Download a file to the cache'''
    if caller == '':
        caller_get()
    filename_full = 'cache/{}_{}'.format(caller, filename)
    if os.path.isfile(filename_full):
        return 1
    else:
        try:
            if ssl_enabled:
                urllib.request.urlretrieve(url, filename_full)
            else:
                ssl._create_default_https_context = ssl._create_unverified_context
                urllib.request.urlretrieve(url, filename_full)
            return 1
        except urllib.error.HTTPError:
            return -1
        except urllib.error.URLError:
            return -2
项目:the-115-api    作者:J3n5en    | 项目源码 | 文件源码
def main():
    global mySession
    ssl._create_default_https_context = ssl._create_unverified_context
    headers = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2663.0 Safari/537.36'}
    mySession = requests.Session()
    mySession.headers.update(headers)
    if not getInfos(): 
        print(u'??????')
        return
    getQrcode() # ????
    waitLogin() # ????????
    login() # ????
    print('??????')
    threading.Thread(target=keepLogin) # ?????????
    getTasksign() # ????task????
    getUserinfo() # ????????
    # addLinktask("magnet:?xt=urn:btih:690ba0361597ffb2007ad717bd805447f2acc624")
    # addLinktasks([link]) ????list
    # print tsign
    # print "fuck"
    # get_bt_upload_info()
    # upload_torrent()
    add_many_bt()
项目:rvo    作者:noqqe    | 项目源码 | 文件源码
def get_title_from_webpage(url):
    """ Fetch <title> of a html site for title element
    :url: str (http url)
    :returns: str
    """

    # LOL SECURITY
    ssl._create_default_https_context = ssl._create_unverified_context

    try:
        h = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'}
        u = urllib2.Request(url, headers=h)
        u = urllib2.urlopen(u)
        soup = BeautifulSoup(u, "html.parser")
        s = soup.title.string.replace('\n', ' ').replace('\r', '').lstrip().rstrip()
        s = s.lstrip()
        return s
    except (AttributeError, MemoryError, ssl.CertificateError, IOError) as e:
        return "No title"
    except ValueError:
        return False
项目:python-spider    作者:titrxw    | 项目源码 | 文件源码
def __run(self,req):
        try:
            ssl._create_default_https_context = ssl._create_unverified_context
            if self.__opener is not None:
                response=self.__opener.open(req)
                self.__code=response.code
                return response.read()
            else:
                context = ssl._create_unverified_context()
                response=urllib2.urlopen(req,context=context)
                self.__code=response.code
                return response.read()
        except Exception,e:
            raise Exception(e.message)
项目:python-spider    作者:titrxw    | 项目源码 | 文件源码
def __run(self,req):
        try:
            ssl._create_default_https_context = ssl._create_unverified_context
            if self.__opener is not None:
                response=self.__opener.open(req)
                self.__code=response.code
                return response.read()
            else:
                context = ssl._create_unverified_context()
                response=urllib2.urlopen(req,context=context)
                self.__code=response.code
                return response.read()
        except Exception,e:
            print(e)
            return None
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def __init__(self, options, handle=None):
        self.handle = handle
        self.opts = deepcopy(options)
        # This is ugly but we don't want any fetches to fail - we expect
        # to encounter unverified SSL certs!
        if sys.version_info >= (2, 7, 9):
            ssl._create_default_https_context = ssl._create_unverified_context

    # Bit of a hack to support SOCKS because of the loading order of
    # modules. sfscan will call this to update the socket reference
    # to the SOCKS one.
项目:vulnlab    作者:timkent    | 项目源码 | 文件源码
def main():

    # ignore invalid cert on ESX box
    import ssl
    _create_unverified_https_context = ssl._create_unverified_context
    ssl._create_default_https_context = _create_unverified_https_context

    vm_list = get_vm_list()

    app = Flask(__name__)

    @app.route("/")
    def index():
        result = '''<!DOCTYPE html>
<html>
  <head>
    <title>VulnLab</title>
  </head>
  <body>
    <h1>Reset</h1>
'''
        for name, uuid in sorted(vm_list.items()):
            result += '    <a href="/reset/' + name + '">' + name + '</a><br>\n'

        result += '''  </body>
</html>
'''
        return result, 200

    @app.route("/reset/<string:vm_name>")
    def reset(vm_name):
        reset_vm(vm_list, vm_name)
        return 'OK\n', 200

    # start the web server
    app.run(host="0.0.0.0", port=5000)
项目:vsphere-storage-for-docker    作者:vmware    | 项目源码 | 文件源码
def disable_certificate_check():
    ssl._create_default_https_context = ssl._create_unverified_context
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def __init__(self, options, handle=None):
        self.handle = handle
        self.opts = deepcopy(options)
        # This is ugly but we don't want any fetches to fail - we expect
        # to encounter unverified SSL certs!
        if sys.version_info >= (2, 7, 9):
            ssl._create_default_https_context = ssl._create_unverified_context

    # Bit of a hack to support SOCKS because of the loading order of
    # modules. sfscan will call this to update the socket reference
    # to the SOCKS one.
项目:XtremPerfProbe    作者:nachiketkarmarkar    | 项目源码 | 文件源码
def getVmwServiceContent(vcip, vcuser, vcpwd):
    unverified_context=ssl._create_unverified_context
    ssl._create_default_https_context=unverified_context
    si=Connect(host=vcip,port=443,user=vcuser,pwd=vcpwd)
    return si.RetrieveContent()
项目:cli    作者:madcore-ai    | 项目源码 | 文件源码
def enable_ssl(cls):
        ssl._create_default_https_context = ssl.create_default_context
项目:cli    作者:madcore-ai    | 项目源码 | 文件源码
def disable_ssl(cls):
        ssl._create_default_https_context = ssl._create_unverified_context
项目:delphixpy-examples    作者:CloudSurgeon    | 项目源码 | 文件源码
def serversess(self, f_engine_address, f_engine_username,
                   f_engine_password, f_engine_namespace='DOMAIN'):
        """
        Method to setup the session with the Virtualization Engine

        f_engine_address: The Virtualization Engine's address (IP/DNS Name)
        f_engine_username: Username to authenticate
        f_engine_password: User's password
        f_engine_namespace: Namespace to use for this session. Default: DOMAIN
        """

#        if use_https:
#            if hasattr(ssl, '_create_unverified_context'):
#                ssl._create_default_https_context = \
#                    ssl._create_unverified_context

        try:
            if f_engine_password:
                self.server_session = DelphixEngine(f_engine_address,
                                                    f_engine_username,
                                                    f_engine_password,
                                                    f_engine_namespace)
            elif f_engine_password is None:
                self.server_session = DelphixEngine(f_engine_address,
                                                    f_engine_username,
                                                    None, f_engine_namespace)

        except (HttpError, RequestError, JobError) as e:
            raise DlpxException('ERROR: An error occurred while authenticating'
                                ' to {}:\n {}\n'.format(f_engine_address, e))
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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
项目:miptnews    作者:fiztehradio    | 项目源码 | 文件源码
def refresh(self):
        self.news = []
        for link in tqdm(self.links, desc="Getting news"):
            data = 0
            if hasattr(ssl, '_create_unverified_context'):
                ssl._create_default_https_context = ssl._create_unverified_context
                data = feedparser.parse(link)
            self.news += [News(binascii.b2a_base64(data['feed']['title'].replace(' VK feed', '').encode()).decode(),
                               binascii.b2a_base64(entry['link'].encode()).decode(),
                               int(time.mktime(entry['published_parsed']))) for entry in data['entries']]
            time.sleep(1)
项目:vsphere-automation-sdk-python    作者:vmware    | 项目源码 | 文件源码
def connect(self):
        if self.client is None:
            # Suds library doesn't support passing unverified context to disable
            # server certificate verification. Thus disable checking globally in
            # order to skip verification. This is not recommended in production
            # code. see https://www.python.org/dev/peps/pep-0476/
            if self.skip_verification:
                import ssl
                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

            self.client = Client(url=self.wsdl_url, location=self.soap_url)
            assert self.client is not None
            self.client.set_options(service='LsService', port='LsPort')

        self.managedObjectReference = self.client.factory.create(
            'ns0:ManagedObjectReference')
        self.managedObjectReference._type = 'LookupServiceInstance'
        self.managedObjectReference.value = 'ServiceInstance'

        lookupServiceContent = self.client.service.RetrieveServiceContent(
            self.managedObjectReference)

        self.serviceRegistration = lookupServiceContent.serviceRegistration
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def bigip_api(bigip, user, password, validate_certs, port=443):
    try:
        if bigsuds.__version__ >= '1.0.4':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs, port=port)
        elif bigsuds.__version__ == '1.0.3':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs)
        else:
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
    except TypeError:
        # bigsuds < 1.0.3, no verify param
        if validate_certs:
            # Note: verified we have SSLContext when we parsed params
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
        else:
            import ssl
            if hasattr(ssl, 'SSLContext'):
                # Really, you should never do this.  It disables certificate
                # verification *globally*.  But since older bigip libraries
                # don't give us a way to toggle verification we need to
                # disable it at the global level.
                # From https://www.python.org/dev/peps/pep-0476/#id29
                ssl._create_default_https_context = ssl._create_unverified_context
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)

    return api


# Fully Qualified name (with the partition)
项目:office_helper    作者:mikumikulch    | 项目源码 | 文件源码
def get_staff_info(self, openner, url='https://kaoqin.bangongyi.com/attend/index/record?_=1498544871927'):
        """
        ?????????????????????????????????
        :param openner: http openner
        :param url: ????
        :return: ???? json ??
        """
        logger.info('?? cookiee ????????')
        ssl._create_default_https_context = ssl._create_unverified_context
        now = datetime.now()
        # ???????????????????
        yesterday_month = now - timedelta(days=1)
        if now.day == 1:
            formated_month = yesterday_month.strftime('%Y-%m')
        else:
            formated_month = now.strftime('%Y-%m')
        post_data = {"date": formated_month, "staffid": "6590415"}
        post_data = parse.urlencode(post_data).encode()
        response = openner.open(url, post_data)
        # request = urllib.request.Request(self.request_url, post_data, headers=LixinStaffInfoSpider.head)
        # ??openner????
        # response = urllib.request.urlopen(request)
        ungzip_response = self.__ungzip(response.read()).decode('utf-8')
        logger.debug(ungzip_response)
        logger.info('????????')
        return ungzip_response
项目:office_helper    作者:mikumikulch    | 项目源码 | 文件源码
def get_staff_cookie(self, openner,
                         url='https://kaoqin.bangongyi.com/attend/index/index?corpid=wx7a3ce8cf2cdfb04c&t=3'):
        """
        ????????? session????????.
        :param openner: ???????? http urllib ????
        :param url: ??????? session ???
        :return: ????? session ?????? cookie ? http openner ??
        """
        logger.info('???????????? cookie ??')
        ssl._create_default_https_context = ssl._create_unverified_context
        openner.open(url)
        logger.info('?? cookie ????')
        return
项目:office_helper    作者:mikumikulch    | 项目源码 | 文件源码
def get_server_time(self, openner,
                        url='https://kaoqin.bangongyi.com/attend/check/get-time?v=1506595896876&_=1506595896882'):
        """
        ?? session ????????
        :param openner:
        :param url: ?????????????
        :return:???????? epoch time
        """
        logger.info('?? session ????????')
        ssl._create_default_https_context = ssl._create_unverified_context
        response = openner.open(url)
        ungzip_response = self.__ungzip(response.read()).decode('utf-8')
        logger.info('session ????????? %s ' % ungzip_response)
        return ungzip_response
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:peas    作者:mwrlabs    | 项目源码 | 文件源码
def disable_certificate_verification():

    ssl._create_default_https_context = ssl._create_unverified_context
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:AirMapSDK-Embedded    作者:airmap    | 项目源码 | 文件源码
def __init__(self):
        """Initialize connect find os set ssl context, get IP address

            :param None:
            :returns: None

        :todo: Add ifconfig command to try to get ip address
            """

        try:
            if self.os.name == 'nt':
                ssl.create_default_context()
            elif self.os.name == 'posix':
                ssl._create_default_https_context = ssl._create_unverified_context
            else:
                ssl._create_default_https_context = ssl._create_unverified_context

        except Exception,e:
            pass

        try:
            #print socket.gethostname()
            thisIP = "IP Address: " + socket.gethostbyname(socket.gethostname())
            #Globals.strPrint (self.thisGlobals, thisIP)

        except Exception,e:
            #Globals.strPrint (self.thisGlobals, "No IP Found...")
            pass
项目:ansible_f5    作者:mcgonagle    | 项目源码 | 文件源码
def bigip_api(bigip, user, password, validate_certs, port=443):
    try:
        if bigsuds.__version__ >= '1.0.4':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs, port=port)
        elif bigsuds.__version__ == '1.0.3':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs)
        else:
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
    except TypeError:
        # bigsuds < 1.0.3, no verify param
        if validate_certs:
            # Note: verified we have SSLContext when we parsed params
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
        else:
            import ssl
            if hasattr(ssl, 'SSLContext'):
                # Really, you should never do this.  It disables certificate
                # verification *globally*.  But since older bigip libraries
                # don't give us a way to toggle verification we need to
                # disable it at the global level.
                # From https://www.python.org/dev/peps/pep-0476/#id29
                ssl._create_default_https_context = ssl._create_unverified_context
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)

    return api


# Fully Qualified name (with the partition)
项目:netapp-ansible    作者:jeorryb    | 项目源码 | 文件源码
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
项目:netapp-ansible    作者:jeorryb    | 项目源码 | 文件源码
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
项目:Cisco-Showroom-RoomControl    作者:gbraux    | 项目源码 | 文件源码
def GetCMSCallID(endpointUri):

    ssl._create_default_https_context = ssl._create_unverified_context
    conn = http.client.HTTPSConnection(Config.cmsFqdn)

    headers = {
        'authorization': Config.cmsGenericAuthRealm,
        'cache-control': "no-cache",
        'postman-token': "9620f24c-7e1e-36f2-cede-e016ef0641e4"
        }

    conn.request("GET", "/api/v1/calllegs", headers=headers)

    res = conn.getresponse()
    data = res.read()

    print(data.decode("utf-8"))

    tree = etree.fromstring(data)
    print(tree)

    callID = ""
    found = False
    for child in tree:
        for child2 in child:



            print(child2.tag)
            print(child2.attrib)
            print(child2.text)

            if ((child2.tag == "remoteParty") & (child2.text == endpointUri)):
                found = True 

            if ((child2.tag == "call") & (found == True)):
                return child2.text
项目:f5-aws-vpn    作者:f5devcentral    | 项目源码 | 文件源码
def disable_ssl_cert_validation():
    # You probably only want to do this for testing and never in production.
    # From https://www.python.org/dev/peps/pep-0476/#id29
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context
项目:gopro-py-api    作者:KonradIT    | 项目源码 | 文件源码
def pair(self):
        #This is a pairing procedure needed for HERO4 and HERO5 cameras. When those type GoPro camera are purchased the GoPro Mobile app needs an authentication code when pairing the camera to a mobile device for the first time. 
        #The code is useless afterwards. This function will pair your GoPro to the machine without the need of using the mobile app -- at all.
        print("Make sure your GoPro camera is in pairing mode!\nGo to settings > Wifi > PAIR > GoProApp to start pairing.\nThen connect to it, the ssid name should be GOPRO-XXXX/GPXXXXX/GOPRO-BP-XXXX and the password is goprohero")
        code=str(input("Enter pairing code: "))
        context = ssl._create_unverified_context()
        ssl._create_default_https_context = ssl._create_unverified_context
        response_raw = urllib.request.urlopen('https://10.5.5.9/gpPair?c=start&pin=' + code + '&mode=0', context=context).read().decode('utf8')
        print(response_raw)
        response_raw = urllib.request.urlopen('https://10.5.5.9/gpPair?c=finish&pin=' + code + '&mode=0', context=context).read().decode('utf8')
        print(response_raw)
        wifi_ssid=input("Enter your desired camera wifi ssid name: ")
        wifi_pass=input("Enter new wifi password: ")
        self.gpControlCommand("wireless/ap/ssid?ssid=" + wifi_ssid + "&pw=" + wifi_pass)
        print("Connect now!")
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
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
项目:plugin.video.unofficial9anime    作者:Prometheusx-git    | 项目源码 | 文件源码
def play(self):
        if self.link == '':
            return

        import urlresolver

        ''' 
            Kodi v17 updated to Python 2.7.10 from 2.7.5 in v16, which introduced this error when 
            trying to resolve the url:
            http://stackoverflow.com/questions/27835619/ssl-certificate-verify-failed-error

            In Kodi v16, python would not verify the SSL certs or at least ignore, but they changed
            with the upgrade to v17.  Sometimes the cert from the initial decrypted URL is invalid,
            so to avoid errors, we temporarily disable SSL to get the resolved URL.  Although this
            workaround isn't secure, I figure it's not any worse than before...
        '''
        try:
            url = urlresolver.resolve(self.link)
        except:
            helper.log_debug('Attempt to resolve URL failed; trying again with SSL temporarily disabled (v16 behavior)')
            import ssl
            default_context = ssl._create_default_https_context # save default context
            ssl._create_default_https_context = ssl._create_unverified_context
            url = urlresolver.resolve(self.link)
            ssl._create_default_https_context = default_context # restore default context

        helper.log_debug("UrlResolver's resolved link: %s" % url)
        helper.resolve_url(url)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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
项目:land-leg-PY    作者:xfkencon    | 项目源码 | 文件源码
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
项目:accurate_weibo_crawler    作者:wdwind    | 项目源码 | 文件源码
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    #sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
    #sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
    #sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    ssl._create_default_https_context = ssl._create_unverified_context

    config = init_config()
    if not config:
        return

    logger.log('[x] Weibo crawler v0.4', 'green')
    logger.log('[x] Configuration initialized')

    set_client(config['access_token'], config['expires_in'])
    response = login_private(config['access_token'])
    if response is None:
        logger.log('[x] User login fails.', 'red')
        return
    cookie = response['cookie']['cookie']['.weibo.com']
    config['cookie'] = cookie[4:cookie.index(';')]
    run(config)
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
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
项目:lbry-android    作者:lbryio    | 项目源码 | 文件源码
def https_context():
    #urllib2
    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

    '''
    # requests
    from functools import partial
    class partialmethod(partial):
        def __get__(self, instance, owner):
            if instance is None:
                return self

            return partial(self.func, instance, *(self.args or ()), **(self.keywords or {}))

    default_request = requests.Session.request
    requests.Session.request = partialmethod(default_request, verify=False)
    '''

# LBRY Daemon
项目:jenova    作者:dungba88    | 项目源码 | 文件源码
def download():
    """skip unverified certificate and show download dialog"""
    try:
        create_unverified_https_context = ssl._create_unverified_context
    except AttributeError:
        pass
    else:
        ssl._create_default_https_context = create_unverified_https_context

    nltk.download()
项目:ansible-provider-docs    作者:alibaba    | 项目源码 | 文件源码
def bigip_api(bigip, user, password, validate_certs, port=443):
    try:
        if bigsuds.__version__ >= '1.0.4':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs, port=port)
        elif bigsuds.__version__ == '1.0.3':
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password, verify=validate_certs)
        else:
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
    except TypeError:
        # bigsuds < 1.0.3, no verify param
        if validate_certs:
            # Note: verified we have SSLContext when we parsed params
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)
        else:
            import ssl
            if hasattr(ssl, 'SSLContext'):
                # Really, you should never do this.  It disables certificate
                # verification *globally*.  But since older bigip libraries
                # don't give us a way to toggle verification we need to
                # disable it at the global level.
                # From https://www.python.org/dev/peps/pep-0476/#id29
                ssl._create_default_https_context = ssl._create_unverified_context
            api = bigsuds.BIGIP(hostname=bigip, username=user, password=password)

    return api


# Fully Qualified name (with the partition)