def test_private_plot_response_with_and_without_share_key(self): # The json file of the private plot should be 404 and once # share_key is added it should be 200 kwargs = { 'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'world_readable': False, 'sharing': 'private' } private_plot_url = py._send_to_plotly(self.simple_figure, **kwargs)['url'] private_plot_response = http_requests.get(private_plot_url + ".json") # The json file of the private plot should be 404 self.assertEqual(private_plot_response.status_code, 404) secret_plot_url = py.add_share_key_to_url(private_plot_url) urlsplit = six.moves.urllib.parse.urlparse(secret_plot_url) secret_plot_json_file = six.moves.urllib.parse.urljoin( urlsplit.geturl(), "?.json" + urlsplit.query) secret_plot_response = http_requests.get(secret_plot_json_file) # The json file of the secret plot should be 200 self.assertTrue(secret_plot_response.status_code, 200)
def test_private_plot_response_with_and_without_share_key(self): # The json file of the private plot should be 404 and once # share_key is added it should be 200 kwargs = {'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'world_readable': False, 'sharing': 'private'} private_plot_url = py._send_to_plotly(self.simple_figure, **kwargs)['url'] private_plot_response = http_requests.get(private_plot_url + ".json") # The json file of the private plot should be 404 self.assertEqual(private_plot_response.status_code, 404) secret_plot_url = py.add_share_key_to_url(private_plot_url) urlsplit = six.moves.urllib.parse.urlparse(secret_plot_url) secret_plot_json_file = six.moves.urllib.parse.urljoin( urlsplit.geturl(), "?.json" + urlsplit.query) secret_plot_response = http_requests.get(secret_plot_json_file) # The json file of the secret plot should be 200 self.assertTrue(secret_plot_response.status_code, 200)
def call(cls, source_currency: str = None, target_currency: str = None) -> "ExchangeRate": if source_currency is not None and target_currency is not None: response: Response = http_requests.get(cls.endpoint + f"?source={source_currency}&target={target_currency}", headers=constants.HEADERS) else: response = http_requests.get(cls.endpoint, headers=constants.HEADERS) return common.get_model_from_response(response, cls)[0] # type: ignore
def call(cls, profile_id: int) -> List["Account"]: from wise.models import AccountType response: Response = http_requests.get(cls.endpoint.replace("{profile_id}", str(profile_id)).replace("{account_type}", AccountType.CashAccount.value), headers=constants.HEADERS) all_accounts_list: List[Account] = common.get_model_from_response(response, cls) # type: ignore response = http_requests.get(cls.endpoint.replace("{profile_id}", str(profile_id)).replace("{account_type}", AccountType.ReserveAccount.value), headers=constants.HEADERS) all_accounts_list.extend(common.get_model_from_response(response, cls)) # type: ignore return all_accounts_list
def test5_not_enough_deposits(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username1'] = self.username[0] response = http_requests.post(url_http() + "username", headers=None, data=username) assert response.json()["is_successful"], response.json() """ First answer if enterprise or platinum""" response = http_requests.post(url_http(), data=PlatinumClientChoice) assert response.status_code == 200 """ Next answer yes to the checking account question""" response = http_requests.post(url_http(), data=CheckingAcctYES) assert response.status_code == 200 """ Next question is if the customer has $200, 000 or more in deposits, for this test answer NO """ response = http_requests.post(url_http(), data=DepositsNO) assert response.json()["Free Overdraft Protection Denied."], response.json()
def upload_file_url(self, filename): try: if os.path.exists(filename): data = public.ExecShell( '/usr/local/curl/bin/curl https://scanner.baidu.com/enqueue -F archive=@%s' % filename) data = json.loads(data[0]) time.sleep(3) import http_requests default_headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } data_list = http_requests.get(url=data['url'], headers=default_headers, verify=False) data2 = data_list.json() if 'data' in data2[0]: if len(data2[0]['data']) >= 1: if 'descr' in data2[0]['data'][0]: if 'WebShell' in data2[0]['data'][0]['descr']: print('%s文件为木马' % filename) self.send_baota2(filename) return True return False else: return False except: return False
def get_identifier_authorization(self, client, url): headers = {"User-Agent": client.User_Agent} get_identifier_authorization_response = requests.get( url, timeout=client.ACME_REQUEST_TIMEOUT, headers=headers, verify=False) if get_identifier_authorization_response.status_code not in [200, 201]: raise ValueError( "Error getting identifier authorization: status_code={status_code}" .format(status_code=get_identifier_authorization_response. status_code)) res = get_identifier_authorization_response.json() domain = res["identifier"]["value"] wildcard = res.get("wildcard") if wildcard: domain = "*." + domain for i in res["challenges"]: if i["type"] == "http-01": http_challenge = i http_token = http_challenge["token"] http_challenge_url = http_challenge["url"] identifier_auth = { "domain": domain, "url": url, "wildcard": wildcard, "http_token": http_token, "http_challenge_url": http_challenge_url, } return identifier_auth
def CheckDomain(self, get): try: #创建目录 spath = get.path + '/.well-known/pki-validation' if not os.path.exists(spath): public.ExecShell("mkdir -p '" + spath + "'") #生成并写入检测内容 epass = public.GetRandomString(32) public.writeFile(spath + '/fileauth.txt', epass) #检测目标域名访问结果 if get.domain[:4] == 'www.': #申请二级域名为www时检测主域名 get.domain = get.domain[4:] import http_requests self._check_url = 'http://127.0.0.1/.well-known/pki-validation/fileauth.txt' result = http_requests.get(self._check_url, s_type='curl', timeout=6, headers={ "host": get.domain }).text self.__test = result if result == epass: return True self._check_url = self._check_url.replace('127.0.0.1', get.domain) return False except: self._check_url = self._check_url.replace('127.0.0.1', get.domain) return False
def test_wrong_api_key(): # TODO: does this test the right thing? username = '******' api_key = 'invalid-apikey' file_owner = 'get_test_user' file_id = 0 hd = copy.copy(default_headers) hd['plotly-username'] = username hd['plotly-apikey'] = api_key resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id) response = http_requests.get(server + resource, headers=hd) assert response.status_code == 401
def get_nonce(self): """ https://tools.ietf.org/html/draft-ietf-acme-acme#section-6.4 Each request to an ACME server must include a fresh unused nonce in order to protect against replay attacks. """ headers = {"User-Agent": self.User_Agent} response = requests.get( self.ACME_GET_NONCE_URL, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers,verify=False ) nonce = response.headers["Replay-Nonce"] return nonce
def test8_name_with_max_stringlength128_plus_one(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username8'] = self.username[7] response = http_requests.post(url_http() + "username", headers=None, data=username) assert_equal(response.json()['error']['user_help'], 'Invalid username')
def test10_name_with_alphanumeric(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username10'] = self.username[9] response = http_requests.post(url_http() + "username", headers=None, data=username) assert_equal(response.json()['error']['user_help'], 'Invalid username')
def test4_name_with_ext_char(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username4'] = self.username[3] response = http_requests.post(url_http() + "username", headers=None, data=username) assert response.json()["is_successful"], response.json()
def get_acme_endpoints(self): headers = {"User-Agent": self.User_Agent} get_acme_endpoints = requests.get( self.ACME_DIRECTORY_URL, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers,verify=False ) if get_acme_endpoints.status_code not in [200, 201]: raise ValueError( "Error while getting Acme endpoints: status_code={status_code} response={response}".format( status_code=get_acme_endpoints.status_code, response=self.log_response(get_acme_endpoints), ) ) return get_acme_endpoints
def test_missing_headers(): file_owner = 'get_test_user' file_id = 0 resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id) headers = list(default_headers.keys()) for header in headers: hd = copy.copy(default_headers) del hd[header] response = http_requests.get(server + resource, headers=hd) if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) print(response.status_code) print(content) assert response.status_code == 422
def test_private_permission_defined(): username = '******' api_key = '786r5mecv0' file_owner = 'get_test_user' file_id = 1 # 1 is a private file hd = copy.copy(default_headers) hd['plotly-username'] = username hd['plotly-apikey'] = api_key resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id) response = http_requests.get(server + resource, headers=hd) if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) print(response.status_code) print(content) assert response.status_code == 403
def test_plot_url_response_given_sharing_key(self): # Given share_key is requested, get request of the url should # be 200 kwargs = {'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'auto_open': False, 'world_readable': False, 'sharing': 'secret'} plot_url = py.plot(self.simple_figure, **kwargs) # shareplot basically always gives a 200 if even if permission denied # embedplot returns an actual 404 embed_url = plot_url.split('?')[0] + '.embed?' + plot_url.split('?')[1] response = http_requests.get(embed_url) self.assertEqual(response.status_code, 200)
def get_graph_reference(): """ Attempts to load local copy of graph reference or makes GET request if DNE. :return: (dict) The graph reference. :raises: (PlotlyError) When graph reference DNE and GET request fails. """ default_config = files.FILE_CONTENT[files.CONFIG_FILE] if files.check_file_permissions(): graph_reference = utils.load_json_dict(files.GRAPH_REFERENCE_FILE) config = utils.load_json_dict(files.CONFIG_FILE) # TODO: https://github.com/plotly/python-api/issues/293 plotly_api_domain = config.get('plotly_api_domain', default_config['plotly_api_domain']) else: graph_reference = {} plotly_api_domain = default_config['plotly_api_domain'] sha1 = hashlib.sha1(six.b(str(graph_reference))).hexdigest() graph_reference_url = '{}{}?sha1={}'.format(plotly_api_domain, GRAPH_REFERENCE_PATH, sha1) try: response = http_requests.get(graph_reference_url, timeout=GRAPH_REFERENCE_DOWNLOAD_TIMEOUT) response.raise_for_status() except http_requests.exceptions.RequestException: if not graph_reference: path = os.path.join('graph_reference', 'default-schema.json') s = resource_string('plotly', path).decode('utf-8') graph_reference = json.loads(s) else: if six.PY3: content = str(response.content, encoding='utf-8') else: content = response.content data = json.loads(content) if data['modified']: graph_reference = data['schema'] return utils.decode_unicode(graph_reference)
def get_identifier_authorization(self, url): """ https://tools.ietf.org/html/draft-ietf-acme-acme#section-7.5 When a client receives an order from the server it downloads the authorization resources by sending GET requests to the indicated URLs. If the client initiates authorization using a request to the new authorization resource, it will have already received the pending authorization object in the response to that request. This is also where we get the challenges/tokens. """ headers = {"User-Agent": self.User_Agent} get_identifier_authorization_response = requests.get( url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers,verify=False ) if get_identifier_authorization_response.status_code not in [200, 201]: raise ValueError( "Error getting identifier authorization: status_code={status_code} response={response}".format( status_code=get_identifier_authorization_response.status_code, response=self.log_response(get_identifier_authorization_response), ) ) res = get_identifier_authorization_response.json() domain = res["identifier"]["value"] wildcard = res.get("wildcard") if wildcard: domain = "*." + domain for i in res["challenges"]: if i["type"] == "dns-01": dns_challenge = i dns_token = dns_challenge["token"] dns_challenge_url = dns_challenge["url"] identifier_auth = { "domain": domain, "url": url, "wildcard": wildcard, "dns_token": dns_token, "dns_challenge_url": dns_challenge_url, } return identifier_auth
def test_file_does_not_exist(): username = '******' api_key = '786r5mecv0' file_owner = 'get_test_user' file_id = 1000 hd = copy.copy(default_headers) hd['plotly-username'] = username hd['plotly-apikey'] = api_key resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id) response = http_requests.get(server + resource, headers=hd) if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) print(response.status_code) print(content) assert response.status_code == 404 assert (content['error'] == "Aw, snap! It looks like this file does not " "exist. Want to try again?")
def make_signed_acme_request(self, url, payload): headers = {"User-Agent": self.User_Agent} payload = self.stringfy_items(payload) if payload in ["GET_Z_CHALLENGE", "DOWNLOAD_Z_CERTIFICATE"]: response = requests.get(url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers,verify=False) else: payload64 = self.calculate_safe_base64(json.dumps(payload)) protected = self.get_acme_header(url) protected64 = self.calculate_safe_base64(json.dumps(protected)) signature = self.sign_message(message="{0}.{1}".format(protected64, payload64)) # bytes signature64 = self.calculate_safe_base64(signature) # str data = json.dumps( {"protected": protected64, "payload": payload64, "signature": signature64} ) headers.update({"Content-Type": "application/jose+json"}) response = requests.post( url, data=data.encode("utf8"), timeout=self.ACME_REQUEST_TIMEOUT, headers=headers ,verify=False ) return response
def test_plot_url_response_given_sharing_key(self): # Given share_key is requested, get request of the url should # be 200 kwargs = { 'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'auto_open': False, 'world_readable': False, 'sharing': 'secret' } plot_url = py.plot(self.simple_figure, **kwargs) # shareplot basically always gives a 200 if even if permission denied # embedplot returns an actual 404 embed_url = plot_url.split('?')[0] + '.embed?' + plot_url.split('?')[1] response = http_requests.get(embed_url) self.assertEqual(response.status_code, 200)
def test_default_schema_is_up_to_date(self): api_domain = files.FILE_CONTENT[files.CONFIG_FILE]['plotly_api_domain'] graph_reference_url = '{}{}?sha1'.format(api_domain, gr.GRAPH_REFERENCE_PATH) response = http_requests.get(graph_reference_url) if six.PY3: content = str(response.content, encoding='utf-8') else: content = response.content schema = json.loads(content)['schema'] path = os.path.join('graph_reference', 'default-schema.json') s = resource_string('plotly', path).decode('utf-8') default_schema = json.loads(s) msg = ( 'The default, hard-coded plot schema we ship with pip is out of ' 'sync with the prod plot schema!\n' 'Run `make update_default_schema` to fix it!') self.assertEqual(schema, default_schema, msg=msg)
def test_user_does_not_exist(): username = '******' api_key = 'invalid-apikey' file_owner = 'get_test_user' file_id = 0 hd = copy.copy(default_headers) hd['plotly-username'] = username hd['plotly-apikey'] = api_key resource = "/apigetfile/{0}/{1}/".format(file_owner, file_id) response = http_requests.get(server + resource, headers=hd) if six.PY3: content = json.loads(response.content.decode('unicode_escape')) else: content = json.loads(response.content) print(response.status_code) print(content) assert response.status_code == 404 assert (content['error'] == "Aw, snap! We don't have an account for {0}. " "Want to try again? Sign in is not case " "sensitive.".format(username))
def test2_end_to_end_successful_platinum_client(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username1'] = self.username[0] response = http_requests.post(url_http() + "username", headers=None, data=username) assert response.json()["is_successful"], response.json() """ First answer if enterprise or platinum""" response = http_requests.post(url_http(), data=PlatinumClientChoice) assert response.status_code == 200 """ Next answer yes to the checking account question""" response = http_requests.post(url_http(), data=CheckingAcctYES) assert response.status_code == 200 """ Next question is if the customer has $200, 000 or more in deposits """ response = http_requests.post(url_http(), data=DepositsYES) assert response.status_code == 200 """ Next question is - does the customer already have overdraft protection? """ """ For this test answer NO""" response = http_requests.post(url_http(), data=OverdraftProtectionNO) assert response.status_code == 200 """ and final question is - does the customer have fewer than five overdrafts in the last 12 months? """ response = http_requests.post(url_http(), data=OverdraftFewerYES) assert response.status_code == 200 """ Post a submit and verify success message""" response = http_requests.post(url_http(), data=submit) assert response.json()["You have been approved for Free Overdraft Protection."], response.json()
def test4_no_checking(self): """ Navigate to a web page """ response = http_requests.get(url_http(), allow_redirects=True) expect_ok(response) assert "Welcome to FOP" in response.text username['username1'] = self.username[0] response = http_requests.post(url_http() + "username", headers=None, data=username) assert response.json()["is_successful"], response.json() """ First answer if enterprise or platinum""" response = http_requests.post(url_http(), data=EntClientChoice) assert response.status_code == 200 """ Next answer NO to the checking account question for this test""" response = http_requests.post(url_http(), data=CheckingAcctNO) assert response.json()["Free Overdraft Protection Denied."], response.json()
def test_default_schema_is_up_to_date(self): api_domain = files.FILE_CONTENT[files.CONFIG_FILE]['plotly_api_domain'] graph_reference_url = '{}{}?sha1'.format(api_domain, gr.GRAPH_REFERENCE_PATH) response = http_requests.get(graph_reference_url) if six.PY3: content = str(response.content, encoding='utf-8') else: content = response.content schema = json.loads(content)['schema'] path = os.path.join('graph_reference', 'default-schema.json') s = resource_string('plotly', path).decode('utf-8') default_schema = json.loads(s) msg = ( 'The default, hard-coded plot schema we ship with pip is out of ' 'sync with the prod plot schema!\n' 'Run `make update_default_schema` to fix it!' ) self.assertEqual(schema, default_schema, msg=msg)
def check_url_txt(self, args): url = args.url content = args.content import http_requests res = http_requests.get(url, s_type='curl', timeout=6) result = res.text if not result: return 0 if result.find('11001') != -1 or result.find('curl: (6)') != -1: return -1 if result.find('curl: (7)') != -1 or res.status_code in [403, 401]: return -5 if result.find('Not Found') != -1 or result.find( 'not found') != -1 or res.status_code in [404]: return -2 if result.find('timed out') != -1: return -3 if result.find('301') != -1 or result.find('302') != -1 or result.find( 'Redirecting...') != -1 or res.status_code in [301, 302]: return -4 if result == content: return 1 return 0
def HttpGet(url, timeout=6, headers={}): """ 发送GET请求 @url 被请求的URL地址(必需) @timeout 超时时间默认60秒 return string """ if is_local(): return False home = 'www.bt.cn' host_home = 'data/home_host.pl' old_url = url if url.find(home) != -1: if os.path.exists(host_home): headers['host'] = home url = url.replace(home, readFile(host_home)) import http_requests res = http_requests.get(url, timeout=timeout, headers=headers) if res.status_code == 0: if old_url.find(home) != -1: return http_get_home(old_url, timeout, res.text) if headers: return False return res.text return res.text
def call(cls, profile_id: int) -> List["Recipient"]: response: Response = http_requests.get(cls.endpoint.replace("{profile_id}", str(profile_id)), headers=constants.HEADERS) return common.get_model_from_response(response, cls) # type: ignore
def call(cls) -> List["UserProfiles"]: response: Response = http_requests.get(cls.endpoint, headers=constants.HEADERS) return common.get_model_from_response(response, cls) # type: ignore
def check_authorization_status(self, authorization_url, desired_status=None): """ https://tools.ietf.org/html/draft-ietf-acme-acme#section-7.5.1 To check on the status of an authorization, the client sends a GET(polling) request to the authorization URL, and the server responds with the current authorization object. https://tools.ietf.org/html/draft-ietf-acme-acme#section-8.2 Clients SHOULD NOT respond to challenges until they believe that the server's queries will succeed. If a server's initial validation query fails, the server SHOULD retry[intended to address things like propagation delays in HTTP/DNS provisioning] the query after some time. The server MUST provide information about its retry state to the client via the "errors" field in the challenge and the Retry-After """ desired_status = desired_status or ["pending", "valid","invalid"] number_of_checks = 0 while True: headers = {"User-Agent": self.User_Agent} check_authorization_status_response = requests.get( authorization_url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers,verify=False ) a_auth = check_authorization_status_response.json() authorization_status = a_auth["status"] number_of_checks = number_of_checks + 1 if number_of_checks == self.ACME_AUTH_STATUS_MAX_CHECKS: raise StopIteration( "Checks done={0}. Max checks allowed={1}. Interval between checks={2}seconds. >>>> {3}".format( number_of_checks, self.ACME_AUTH_STATUS_MAX_CHECKS, self.ACME_AUTH_STATUS_WAIT_PERIOD, json.dumps(a_auth) ) ) if authorization_status in desired_status: if authorization_status == "invalid": try: import panelLets if 'error' in a_auth['challenges'][0]: ret_title = a_auth['challenges'][0]['error']['detail'] elif 'error' in a_auth['challenges'][1]: ret_title = a_auth['challenges'][1]['error']['detail'] elif 'error' in a_auth['challenges'][2]: ret_title = a_auth['challenges'][2]['error']['detail'] else: ret_title = str(a_auth) ret_title = panelLets.panelLets().get_error(ret_title) except: ret_title = str(a_auth) raise StopIteration( "{0} >>>> {1}".format( ret_title, json.dumps(a_auth) ) ) break else: # for any other status, sleep then retry time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) return check_authorization_status_response