Python urllib3.exceptions.InsecureRequestWarning() Examples
The following are 28
code examples of urllib3.exceptions.InsecureRequestWarning().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
urllib3.exceptions
, or try the search function
.
Example #1
Source File: core.py From lanzou-gui with MIT License | 6 votes |
def __init__(self): self._session = requests.Session() self._captcha_handler = None self._timeout = 5 # 每个请求的超时(不包含下载响应体的用时) self._max_size = 100 # 单个文件大小上限 MB self._upload_delay = (0, 0) # 文件上传延时 self._host_url = 'https://www.lanzous.com' self._doupload_url = 'https://pc.woozooo.com/doupload.php' self._account_url = 'https://pc.woozooo.com/account.php' self._mydisk_url = 'https://pc.woozooo.com/mydisk.php' self._cookies = None self._headers = { 'User-Agent': USER_AGENT, 'Referer': 'https://www.lanzous.com', 'Accept-Language': 'zh-CN,zh;q=0.9', # 提取直连必需设置这个,否则拿不到数据 } disable_warnings(InsecureRequestWarning) # 全局禁用 SSL 警告
Example #2
Source File: core.py From LanZouCloud-API with MIT License | 6 votes |
def __init__(self): self._session = requests.Session() self._captcha_handler = None self._limit_mode = True # 是否保持官方限制 self._timeout = 15 # 每个请求的超时(不包含下载响应体的用时) self._max_size = 100 # 单个文件大小上限 MB self._upload_delay = (0, 0) # 文件上传延时 self._host_url = 'https://www.lanzous.com' self._doupload_url = 'https://pc.woozooo.com/doupload.php' self._account_url = 'https://pc.woozooo.com/account.php' self._mydisk_url = 'https://pc.woozooo.com/mydisk.php' self._cookies = None self._headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36', 'Referer': 'https://www.lanzous.com', 'Accept-Language': 'zh-CN,zh;q=0.9', # 提取直连必需设置这个,否则拿不到数据 } disable_warnings(InsecureRequestWarning) # 全局禁用 SSL 警告
Example #3
Source File: test_openmetrics.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_send_request_with_dynamic_prometheus_url(mocked_openmetrics_check_factory, text_data): instance = dict( { 'prometheus_url': 'https://www.example.com', 'metrics': [{'foo': 'bar'}], 'namespace': 'openmetrics', 'ssl_verify': False, } ) check = mocked_openmetrics_check_factory(instance) scraper_config = check.get_scraper_config(instance) # `prometheus_url` changed just before calling `send_request` scraper_config['prometheus_url'] = 'https://www.example.com/foo/bar' with pytest.warns(None) as record: resp = check.send_request('https://httpbin.org/get', scraper_config) assert "httpbin.org" in resp.content.decode('utf-8') assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #4
Source File: session.py From onegram with MIT License | 6 votes |
def enter_contexts(self): self._requests = yield requests.Session() proxies = self.settings.get('PROXIES') if proxies: self._requests.proxies = proxies verify_ssl = self.settings.get('VERIFY_SSL', True) self._requests.verify = verify_ssl if not verify_ssl: urllib3.disable_warnings(InsecureRequestWarning) self._requests.headers.update(DEFAULT_HEADERS) user_agent = self.settings.get('USER_AGENT') if user_agent is not None: self._requests.headers['User-Agent'] = user_agent else: self._requests.headers.pop('User-Agent', None) response = self._requests.get(URLS['start']) response.raise_for_status() self._update_csrftoken(response) self._update_rhx_gis(response) self.rate_limiter = RateLimiter(self)
Example #5
Source File: service.py From b0mb3r with GNU General Public License v3.0 | 6 votes |
def __init__(self, phone, country_data, sms_text='Произошёл троллинг'): self.phone = phone self.country_code = country_data[0] self.phone_code = country_data[1] self.sms_text = sms_text if sms_text != '' else 'Произошёл троллинг' self.formatted_phone = self.phone_code + self.phone self.session = requests.Session() if os.path.isfile('debug'): self.session_get = self.session.get self.session_post = self.session.post self.session.get = self.get self.session.post = self.post self.session.headers = {'User-Agent': self.generate_random_user_agent()} requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
Example #6
Source File: test_openmetrics.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_ssl_verify_not_raise_warning(mocked_openmetrics_check_factory, text_data): instance = dict( { 'prometheus_url': 'https://www.example.com', 'metrics': [{'foo': 'bar'}], 'namespace': 'openmetrics', 'ssl_verify': False, } ) check = mocked_openmetrics_check_factory(instance) scraper_config = check.get_scraper_config(instance) with pytest.warns(None) as record: resp = check.send_request('https://httpbin.org/get', scraper_config) assert "httpbin.org" in resp.content.decode('utf-8') assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #7
Source File: http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_tls_warning(self): with disable_warnings_ctx(InsecureRequestWarning, disable=True): yield
Example #8
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_instance_no_ignore(self): instance = {'tls_ignore_warning': False} init_config = {'tls_ignore_warning': True} http = RequestsWrapper(instance, init_config) with pytest.warns(InsecureRequestWarning): http.get('https://www.google.com', verify=False)
Example #9
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_default_init_no_ignore(self): instance = {} init_config = {'tls_ignore_warning': False} http = RequestsWrapper(instance, init_config) with pytest.warns(InsecureRequestWarning): http.get('https://www.google.com', verify=False)
Example #10
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_init_ignore(self): instance = {} init_config = {'tls_ignore_warning': True} http = RequestsWrapper(instance, init_config) with pytest.warns(None) as record: http.get('https://www.google.com', verify=False) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #11
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ignore_session(self): instance = {'tls_ignore_warning': True, 'persist_connections': True} init_config = {} http = RequestsWrapper(instance, init_config) with pytest.warns(None) as record: http.get('https://www.google.com', verify=False) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #12
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_default_no_ignore_session(self): instance = {'persist_connections': True} init_config = {} http = RequestsWrapper(instance, init_config) with pytest.warns(InsecureRequestWarning): http.get('https://www.google.com', verify=False)
Example #13
Source File: test_http.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ignore(self): instance = {'tls_ignore_warning': True} init_config = {} http = RequestsWrapper(instance, init_config) with pytest.warns(None) as record: http.get('https://www.google.com', verify=False) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #14
Source File: test_warnings_util.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_disable_warnings_ctx_not_disabled(): with pytest.warns(InsecureRequestWarning): requests.get('https://www.example.com', verify=False) with pytest.warns(InsecureRequestWarning): with disable_warnings_ctx(InsecureRequestWarning, disable=False): requests.get('https://www.example.com', verify=False) with pytest.warns(InsecureRequestWarning): with disable_warnings_ctx(ConfigurationError): requests.get('https://www.example.com', verify=False)
Example #15
Source File: test_warnings_util.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_disable_warnings_ctx_disabled(): with pytest.warns(None) as record: with disable_warnings_ctx(InsecureRequestWarning): requests.get('https://www.example.com', verify=False) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record) with pytest.warns(None) as record: with disable_warnings_ctx(InsecureRequestWarning, disable=True): requests.get('https://www.example.com', verify=False) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #16
Source File: test_warnings_util.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_filters_count_append(): initial_count = len(warnings.filters) for _ in range(100): simplefilter('default', InsecureRequestWarning, append=1) final_count = len(warnings.filters) if PY2: assert final_count in (initial_count + 100, initial_count + 101) else: assert final_count in (initial_count, initial_count + 1)
Example #17
Source File: test_prometheus.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ssl_verify_not_raise_warning_cert_false(mocked_prometheus_check, text_data): check = mocked_prometheus_check check.ssl_ca_cert = False with pytest.warns(None) as record: resp = check.poll('https://httpbin.org/get') assert "httpbin.org" in resp.content.decode('utf-8') assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #18
Source File: test_prometheus.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_ssl_verify_not_raise_warning(mocked_prometheus_check, text_data): check = mocked_prometheus_check with pytest.warns(None) as record: resp = check.poll('https://httpbin.org/get') assert "httpbin.org" in resp.content.decode('utf-8') assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #19
Source File: conftest.py From openshift-restclient-python with Apache License 2.0 | 5 votes |
def openshift_container(request, port, pytestconfig): capmanager = pytestconfig.pluginmanager.getplugin('capturemanager') client = docker.from_env() openshift_version = request.config.getoption('--openshift-version') if openshift_version is None: yield None else: container = client.containers.run( 'openshift/origin:{}'.format(openshift_version), 'start master --listen=0.0.0.0:{}'.format(port), detach=True, ports={port: port} ) try: # Wait for the container to no longer be in the created state before # continuing while container.status == u'created': capmanager.suspend() print("\nWaiting for container...") capmanager.resume() time.sleep(5) container = client.containers.get(container.id) # Disable InsecureRequest warnings because we can't get the cert yet warnings.simplefilter('ignore', InsecureRequestWarning) # Wait for the api server to be ready before continuing for _ in range(10): try: requests.head("https://127.0.0.1:{}/healthz/ready".format(port), verify=False) except requests.RequestException: pass time.sleep(1) warnings.simplefilter('default', InsecureRequestWarning) time.sleep(1) yield container finally: # Always remove the container container.remove(force=True)
Example #20
Source File: test_kubelet.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_silent_tls_warning(monkeypatch, aggregator): check = KubeletCheck('kubelet', {}, [{}]) check.kube_health_url = "https://example.com/" check.kubelet_credentials = KubeletCredentials({'verify_tls': 'false'}) with pytest.warns(None) as record: check._perform_kubelet_check([]) assert all(not issubclass(warning.category, InsecureRequestWarning) for warning in record)
Example #21
Source File: kubelet.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def perform_kubelet_query(self, url, verbose=True, timeout=10, stream=False): """ Perform and return a GET request against kubelet. Support auth and TLS validation. """ with disable_warnings_ctx(InsecureRequestWarning, disable=not self.kubelet_credentials.verify()): return requests.get( url, timeout=timeout, verify=self.kubelet_credentials.verify(), cert=self.kubelet_credentials.cert_pair(), headers=self.kubelet_credentials.headers(url), params={'verbose': verbose}, stream=stream, )
Example #22
Source File: azkaban.py From azkaban-cli with MIT License | 5 votes |
def __init__(self): # Session ignoring SSL verify requests session = requests.Session() session.verify = False urllib3.disable_warnings(InsecureRequestWarning) self.__session = session self.__host = None self.__user = None self.__session_id = None
Example #23
Source File: ntlm_challenger.py From ntlm_challenger with MIT License | 5 votes |
def request_http(url): # setup request, insecurely headers = {'Authorization': 'NTLM TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA='} requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) request = requests.get(url, headers=headers, verify=False) if request.status_code not in [401, 302]: print('[!] Expecting response code 401 or 302, received: {}'.format(request.status_code)) return None # get auth header auth_header = request.headers.get('WWW-Authenticate') if not auth_header: print('[!] NTLM Challenge response not found (WWW-Authenticate header missing)') return None if not 'NTLM' in auth_header: print('[!] NTLM Challenge response not found (WWW-Authenticate does not contain "NTLM")') return None # get challenge message from header challenge_message = base64.b64decode(auth_header.split(' ')[1].replace(',', '')) return challenge_message
Example #24
Source File: ibmxforce_lookup.py From Cortex-Analyzers with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self): Analyzer.__init__(self) self.service = self.get_param( 'config.service', None, 'Service parameter is missing') self.url = self.get_param('config.url', None, 'Missing API url') if self.url: self.url = self.url.rstrip('/') self.key = self.get_param('config.key', None, 'Missing API key') self.pwd = self.get_param('config.pwd', None, 'Missing API password') self.verify = self.get_param('config.verify', True) if not self.verify: requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning) self.proxies = self.get_param('config.proxy', None)
Example #25
Source File: helpers.py From Varken with MIT License | 5 votes |
def connection_handler(session, request, verify, as_is_reply=False): air = as_is_reply s = session r = request v = verify return_json = False disable_warnings(InsecureRequestWarning) try: get = s.send(r, verify=v) if get.status_code == 401: if 'NoSiteContext' in str(get.content): logger.info('Your Site is incorrect for %s', r.url) elif 'LoginRequired' in str(get.content): logger.info('Your login credentials are incorrect for %s', r.url) else: logger.info('Your api key is incorrect for %s', r.url) elif get.status_code == 404: logger.info('This url doesnt even resolve: %s', r.url) elif get.status_code == 200: try: return_json = get.json() except JSONDecodeError: logger.error('No JSON response. Response is: %s', get.text) if air: return get except InvalidSchema: logger.error("You added http(s):// in the config file. Don't do that.") except SSLError as e: logger.error('Either your host is unreachable or you have an SSL issue. : %s', e) except ConnectionError as e: logger.error('Cannot resolve the url/ip/port. Check connectivity. Error: %s', e) except ChunkedEncodingError as e: logger.error('Broken connection during request... oops? Error: %s', e) return return_json
Example #26
Source File: test_ntlm.py From ntlm-auth with MIT License | 5 votes |
def _send_request(self, server, domain, username, password, port, ntlm_compatibility, legacy=True): """ Sends a request to the url with the credentials specified. Returns the final response """ # filter out warnings around older Python and unverified connections try: from requests.packages.urllib3.exceptions import \ InsecurePlatformWarning warnings.simplefilter('ignore', category=InsecurePlatformWarning) except ImportError: pass try: from requests.packages.urllib3.exceptions import SNIMissingWarning warnings.simplefilter('ignore', category=SNIMissingWarning) except ImportError: pass try: from urllib3.exceptions import InsecureRequestWarning warnings.simplefilter('ignore', category=InsecureRequestWarning) except ImportError: pass url = "%s://%s:%d/contents.txt" \ % ('http' if str(port).startswith('8') else 'https', server, port) session = requests.Session() session.verify = False session.auth = NtlmAuth(domain, username, password, ntlm_compatibility, legacy) request = requests.Request('GET', url) prepared_request = session.prepare_request(request) response = session.send(prepared_request) return response # used by the functional tests to auth with an NTLM endpoint
Example #27
Source File: http_code.py From PyFunceble with Apache License 2.0 | 4 votes |
def __init__(self, subject, subject_type): # pragma: no cover subject_type = subject_type.lower() if subject_type in ["url", "file_url"]: # We should work with full URL which actualy means that we have to get the # http status code from the URL we are currently testing. # We disable the urllib warning. disable_warnings(urllib3_exceptions.InsecureRequestWarning) # We initiate the element we have to get. self.subject = subject elif subject_type in ["domain", "file_domain"]: # We are working with domain/IPv4. # We construct the element we have to get. # Note: As we may work with IP, we explicitly set the port we are # working with. self.subject = "http://%s:80" % subject elif subject_type in ["ipv6"]: # We are working with an IPv6 # We construct the element we have to get. self.subject = "http://[%s]:80" % subject else: raise Exception("Unknow subject type.") # We share the subject type. self.subject_type = subject_type # We set the default status code. self.default = PyFunceble.HTTP_CODE.not_found_default user_agent = PyFunceble.engine.UserAgent().get() if user_agent: # The user-agent is given. # We append the user agent to the header we are going to parse with # the request. self.headers = {"User-Agent": user_agent} else: # The user-agent is not given or is empty. # We return an empty header. self.headers = {} PyFunceble.LOGGER.debug(f"Subject: {repr(self.subject)}") PyFunceble.LOGGER.debug(f"Headers:\n{self.headers}")
Example #28
Source File: base.py From machinae with MIT License | 4 votes |
def _req(self, conf, url=None): if url is None: url = conf.get("url", "") if url == "": return url = url.format(**self.kwargs) method = conf.get("method", "get").upper() kwargs = dict() headers = conf.get("headers", {}) if headers: kwargs["headers"] = headers verify_ssl = conf.get("verify_ssl", True) # GET params params = conf.get("params", {}).copy() for (k, v) in params.items(): if hasattr(v, "items"): conf = params.pop(k) if "relatime" in conf: dt = relatime.timeParser(conf["relatime"], timezone=str(get_localzone())) target_tz = pytz.timezone(conf.get("timezone", "UTC")) dt = dt.astimezone(target_tz) dt = dt.replace(tzinfo=None) time_format = conf.get("format", "%Y-%m-%dT%H:%M:%S.%fZ") if time_format.lower() == "as_epoch": params[k] = str(int(dt.timestamp())) else: params[k] = dt.strftime(time_format) else: params[k] = str(v).format(**self.kwargs) if params: kwargs["params"] = params # POST data data = conf.get("data", {}) for (k, v) in data.items(): data[k] = v.format(**self.kwargs) if data: kwargs["data"] = data # HTTP Basic Auth if conf.get("auth") and self.creds and self.creds.get(conf["auth"]): kwargs["auth"] = tuple(self.creds[conf["auth"]]) # Auto decompress if conf.get("decompress", False): kwargs["hooks"] = {"response": self.unzip_content} raw_req = requests.Request(method, url, **kwargs) req = self.session.prepare_request(raw_req) if self.kwargs.get("verbose", False): print("[.] Requesting {0} ({1})".format(req.url, req.method)) with warnings.catch_warnings(): if not verify_ssl: warnings.simplefilter("ignore", exceptions.InsecureRequestWarning) return self.session.send(req, verify=verify_ssl)