def listPackage(self): l_packages = [] pkg_file = None basic_auth = (API_USER, USER_PASS) try: request = get(URL_PKG, pkcs12_filename=CERT_P12, pkcs12_password=CERT_P12_PASS,\ verify=CA_CERT, auth=basic_auth) #request = urllib2.Request(URL_PKG) #response = urllib2.urlopen(request, context=ssl._create_unverified_context()) pkg_file = request.text except Exception as e: l.error(e) result_packages = e if not pkg_file: l_packages = result_packages else: result_packages = re.findall('Package.*', pkg_file) for package in result_packages: pkg = package.split() l_packages.append(pkg[1]) return l_packages
def get_systems(): url = urls["service_registry_url"] + \ "/mgmt/systems?direction=ASC&sort_field=id" return get(url, verify=False, pkcs12_filename=cert["pkcs12_filename"], pkcs12_password=cert["pkcs12_password"])
def start_orchestration_based_on_id(): consumer_id = find_system_ids(consumer_name, provider_name)[0] url = orchestration_url + "/orchestration/" + str(consumer_id) return get(url, verify=False, pkcs12_filename=pkcs12_filename, pkcs12_password=pkcs12_password)
def add_intracloud_authorization(): url = urls["authorization_url"] + "/mgmt/intracloud" authorization_json = create_authorization_json("consumer", "producer") return get( url, # , json=authorization_json verify=False, pkcs12_filename=cert["pkcs12_filename"], pkcs12_password=cert["pkcs12_password"])
def cert_get(url, **kwargs): """ Get request with certificate :param url: url to get :return: request response """ logger.info(f"GET {url}") kwargs = _add_cert_info(kwargs) response = get(url, **kwargs) logger.info(f"RESPONSE {response.status_code}, {response.reason}") return response
def check_certs(target_url, verify): from requests_pkcs12 import get for url_subfix in cert_url_subfixes: full_url = '{0}{1}'.format(target_url, url_subfix) for cert in certs: try: response = get(full_url, pkcs12_filename=os.path.join(sys.path[0], cert), pkcs12_password='******', verify=verify) except requests.exceptions.ConnectionError as e: continue if response.status_code < 400: for name, markers in sections.items(): for marker in markers: if marker in response.text.lower(): yield {"name": name, "url": full_url, "certificate": cert} break
def connect(server_url, vo_name, date_from, date_to, metric): ''' Connecting to the EGI Accounting Portal ''' request = "%s/vo_admin/cloud/%s/%s/UserDN/DATE/%s/%s/JSON" % ( server_url, vo_name, metric, date_from, date_to) print("[ Request ] = %s" % request) curl = get(request, pkcs12_filename="%s/.globus/YOUR_CERTIFICATE.p12" % os.environ['HOME'], pkcs12_password='******') data = curl.json() return data
from requests_pkcs12 import post,get import json from base64 import b64encode url = 'https://<HOST>/iot/gateway/rest/measures/<ALTERNATE ID>' certificate_location = '<Location to .P12 file>' password = '******' headers = {'Content-type': 'application/json'} json_data = { "capabilityAlternateId": "100", "sensorAlternateId": "1B", "measures": [{"temperature": "600"}]}; #sample payload data=json.dumps(json_data) # Sending data/timeseries data to the platform. r = post(url, pkcs12_filename=certificate_location, pkcs12_password=password,data=data,headers=headers) print(r.text) # Recieving Data/Timeseries user_name = "USERNAME" password = "******" user_pass = user_name+":"+password basicAuthToken = b64encode(user_pass.encode()).decode("ascii") headers = { 'Authorization' : 'Basic %s' % basicAuthToken } url2 = 'https://<HOST>/iot/core/api/v1/devices/<ID>/measures?skip=0&top=100' r = get(url2, headers=headers) print(r.text) #The recieved string is a son string that can be converted back to son obect and used......
def get(self, url: str) -> dict: return self._handle_response( get(url, headers=self._headers, **self._cert_args))
userDataJson = { "certificate_profile_name": "ENDUSER", "end_entity_profile_name": "TLS_EE", "username": inputUsername, "password": userPassword, "email": f"{inputUsername}[email protected]", "subject_dn":f"CN={inputUsername},O={inputOrganization}", "ca_name": "Issuing_CA", "token_type": "P12" } # If this triggers ssl error, try with no password protection on p12 as mentioned here: http://docs.python-requests.org/en/master/user/advanced/ # Get trusted Management CA for admin operations mgtCaUrl = "{}/ejbca/publicweb/webdist/certdist?cmd=cacert&issuer=CN%3DManagementCA%2COU%3DWP923%2CO%3DDRIVER+PROJECT&level=0".format(inputEjbcaPubBaseUrl) response = requests_pkcs12.get(mgtCaUrl, allow_redirects=False) mgtCaCertPath = os.path.join(tmpDir, 'mgt-ca-crt.pem') open(mgtCaCertPath, 'w').write(response.text) response = requests_pkcs12.post(eesApiUrl, headers=headers, json=userDataJson, verify=mgtCaCertPath, pkcs12_filename=superadminP12Path, pkcs12_password=superadminPass) if response.status_code != 200: raise RuntimeError(f"User registration failed. Server response: {response.text}") # Request certificate certEnrollApiUrl = '%s/ejbca/ejbca-rest-api/v1/certificate/enrollkeystore' % inputEjbcaAdminBaseUrl certReqJson = { "username":inputUsername, "password":userPassword, "key_alg":"RSA", "key_spec":"2048" }
ce_mercante = sys.argv[1] if len(sys.argv) > 2: usuario = sys.argv[2] senha = sys.argv[3] # Login por usuario e senha print('Fazendo login com usuário e senha') payload = {'username': usuario, 'password': senha} print(payload) r = requests.post(BASE_URL + '/api/login', json=payload, verify=False) else: # Login por Certificado print('Fazendo login com certificado') r = requests.get(BASE_URL + '/api/login_certificado', pkcs12_filename='ivan.p12', pkcs12_password='******', verify=False) print(r.status_code) print(r.text) jwt_token = r.json().get('access_token') my_headers = {'Authorization': 'Bearer %s' % jwt_token} # Pesquisar um conhecimento, retornar lista de contêineres e de imagens payload = { 'query': { 'metadata.carga.conhecimento.conhecimento': ce_mercante }, 'projection': { 'metadata.carga.container.container': 1, '_id': 1
def get_orchestration(): url = urls["orchestration_url"] + "/mgmt/store" return get(url, verify=False, pkcs12_filename=cert["pkcs12_filename"], pkcs12_password=cert["pkcs12_password"])
def get_systems(): url = service_regisrty_url + "/mgmt/systems?direction=ASC&sort_field=id" return get(url, verify=False, pkcs12_filename=pkcs12_filename, pkcs12_password=pkcs12_password )
def get_services(): url = service_regisrty_url + "/mgmt?direction=ASC" return get(url, verify=False, pkcs12_filename=pkcs12_filename, pkcs12_password=pkcs12_password )
def match_key(ignorelist, value): for element in ignorelist: if element == value: return True return False while conditions[MODE](): try: for AURL in API_URL: for ENDPOINT in ENDPOINT_LIST: r = requests.get( url=AURL + ENDPOINT) if SECURE == False else get( url=AURL + ENDPOINT, headers={'Content-Type': 'application/json'}, verify=False, pkcs12_filename=CERT_FILE, pkcs12_password=CERT_PASS) received_response = r.json() flat_response = flattening(received_response, "", []) current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') points = [{ "measurement": ENDPOINT, "tags": { 'APIURL': AURL }, "time": current_time, "fields": flat_response }] logger.info(ENDPOINT, extra=received_response) iclient.write_points(points)
def raw_get(self, url: str) -> Response: return get(url, headers=self._headers, **self._cert_args)
def get_token(type_cert, _env, _proxyurl): # This is courtesy of James Owen c. April 2019 # open token file and check expiry basePath = 'C:/Tools/scripts/' token_filename = "" token_uri = "" cert = "" cert_pass = "" if _env == 'proda': instance = 'proda.bce' if type_cert == 'OSS': cert = basePath + 'credentials/ossbssTools-proda-sts.pfx' elif type_cert == 'DVRPROXY': cert = basePath + 'credentials/ndvrTools-proda-sts.pfx' cert_pass = '******' token_uri = 'https://appgw-operatorstsssl.' + instance + '.tv3cloud.com/certactive' token_filename = './' + instance + '_token.json' elif _env == 'prodc': instance = 'prodc.bce' cert = basePath + 'credentials/ucpusher-ssl.pfx' cert_pass = '' token_uri = 'https://appgw-operatorstsssl.' + instance + '.tv3cloud.com/certactive' token_filename = './' + instance + '_token.json' elif _env == 'prodb': instance = 'prodb.bce' if type_cert == 'OSS': cert = basePath + 'credentials/ossbssTools-prodb-sts.pfx' elif type_cert == 'DVRPROXY': cert = basePath + 'credentials/ndvrTools-prodb-sts.pfx' cert_pass = '******' token_uri = 'https://appgw-operatorstsssl.' + instance + '.tv3cloud.com/certactive' token_filename = './' + instance + '_token.json' token_valid = 0 try: with open(token_filename, 'r') as token_file_in: try: token = json.load(token_file_in) if ((datetime.datetime.timestamp(dateutil.parser.parse(token['RefreshTime'])) - time.time()) > 0): token_valid = 1 # print(bcolors.OKGREEN + 'token loaded ok. proceeding...\n' + bcolors.ENDC) else: print('token expired. getting new token...\n') except: pass except OSError: print('no token file. getting new token...\n') if (token_valid): pass else: response = get(token_uri, headers={'Content-Type': 'application/json'}, verify=True, pkcs12_filename=cert, pkcs12_password=cert_pass, proxies=_proxyurl) if (response.status_code == 200): token = response.json() # load token from repsonse.get() with open(token_filename, 'w', encoding="utf-8", newline='\n') as token_file: try: json.dump(response.json(), token_file, indent=4, sort_keys=True, ensure_ascii=False) token_file.write('\n') token_file.close() # print (bcolors.OKGREEN + 'token saved ok. proceeding...\n' + bcolors.ENDC) except OSError: print(bcolors.WARNING + 'can\'t create files. bailing...' + bcolors.ENDC + '\n') sys.exit('barf!') else: print('token request response: ', response.json()['ErrorDescription'], '\n') sys.exit('invalid cert or wrong password\n') try: auth_header = {'Authorization': 'OAUTH2 access_token="' + (token['AccessToken']) + '"', 'Content-Type': 'application/json'} return auth_header except: return None
def get_services(): url = urls["service_registry_url"] + "/mgmt?direction=ASC" return get(url, verify=False, pkcs12_filename=cert["pkcs12_filename"], pkcs12_password=cert["pkcs12_password"])