class Session(requests.Session): def __init__(self, edgerc, section, switch_key=None, **kwargs): try: super(Session, self).__init__(**kwargs) self.edgerc = EdgeRc(edgerc) self.section = section self.switch_key = switch_key self.auth = EdgeGridAuth( client_token=self.edgerc.get(section, "client_token"), client_secret=self.edgerc.get(section, "client_secret"), access_token=self.edgerc.get(section, "access_token"), ) except NoSectionError as e: raise EdgegridError(e.message) except NoOptionError as e: raise EdgegridError(e.message) def request(self, method, url, params=None, **kwargs): if self.switch_key: params = params if params else {} params.update(accountSwitchKey=self.switch_key) baseUrl = "https://{host}".format( host=self.edgerc.get(self.section, "host")) url = parse.urljoin(baseUrl, url) response = super(Session, self).request(method, url, params=params, **kwargs) if response.status_code in (401, 403, *range(500, 600)): raise EdgegridError(response.json()) return response
def from_edgerc( edgerc_path=os.path.join(os.path.expanduser("~"), ".edgerc"), section='default'): edgerc = EdgeRc(edgerc_path) return OpenClient(edgerc.get(section, 'host'), edgerc.get(section, 'access_token'), edgerc.get(section, 'client_token'), edgerc.get(section, 'client_secret'))
def init_config(edgerc_file, section): if not edgerc_file: if not os.getenv("AKAMAI_EDGERC"): edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc') else: edgerc_file = os.getenv("AKAMAI_EDGERC") if not os.access(edgerc_file, os.R_OK): root_logger.error("Unable to read edgerc file \"%s\"" % edgerc_file) exit(1) if not section: if not os.getenv("AKAMAI_EDGERC_SECTION"): section = "papi" else: section = os.getenv("AKAMAI_EDGERC_SECTION") try: edgerc = EdgeRc(edgerc_file) base_url = edgerc.get(section, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) return base_url, session except configparser.NoSectionError: root_logger.error("Edgerc section \"%s\" not found" % section) exit(1) except Exception: root_logger.info( "Unknown error occurred trying to read edgerc file (%s)" % edgerc_file) exit(1)
def load(self, edgerc_file, section, account_key): if not edgerc_file: if not os.getenv("AKAMAI_EDGERC"): edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc') else: edgerc_file = os.getenv("AKAMAI_EDGERC") if not os.access(edgerc_file, os.R_OK): raise ValueError( "Unable to read edgerc file {}".format(edgerc_file)) if not section: if not os.getenv("AKAMAI_EDGERC_SECTION"): section = "default" else: section = os.getenv("AKAMAI_EDGERC_SECTION") try: edgerc = EdgeRc(edgerc_file) base_url = edgerc.get(section, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) context = self.buildContext(base_url, account_key, session) return context except configparser.NoSectionError: raise ValueError("Edgerc section {} not found".format(section)) except Exception: raise ValueError( "Unknown error occurred trying to read edgerc file {}".format( edgerc_file))
class AkamaiBase: ''' Support class to somewhat easily use the Akamai API's ''' def __init__(self, config, section, account=None): self._config = config self._section = section self._account = account self.edgerc = EdgeRc(os.path.expanduser(os.path.expandvars(config))) self.auth = EdgeGridAuth.from_edgerc(self.edgerc, section=section) self.baseurl = 'https://{}'.format(self.edgerc.get(section, 'host')) self.adapter = HTTPAdapter(max_retries=retry_strategy) self.session = requests.Session() self.session.auth = self.auth self.session.mount("https://", self.adapter) def _apipath(self, endpoint, parameters=None): if self._account: if not parameters: parameters = {} parameters['accountSwitchKey'] = self._account ttpath = endpoint if parameters and len(parameters) > 0 and '?' not in ttpath: ttpath += '?' + urlencode(parameters) thepath = urljoin(self.baseurl, ttpath) LOG.info('path: %s', thepath) return thepath
def get_property_hostnames(latestVersion, propertyId, contractId, groupId, path, section, switchkey): # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python property_hostnames_list = [] edgerc = EdgeRc(path) baseurl = 'https://%s' % edgerc.get(section, "host") http_request = requests.Session() http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section) # setting up request headers headers = {} headers['PAPI-Use-Prefixes'] = "true" http_request.headers = headers # getting the list of groups and contracts associated to groups: https://developer.akamai.com/api/core_features/property_manager/v1.html#getgroups http_response = http_request.get( urljoin( baseurl, '/papi/v1/properties/' + propertyId + '/versions/' + str(latestVersion) + '/hostnames?contractId=' + contractId + '&groupId=' + groupId + '&validateHostnames=false&accountSwitchKey=' + switchkey)) http_status_code = http_response.status_code http_content = json.loads(http_response.text) try: test = http_content['hostnames']['items'] except KeyError: pass else: for item in http_content['hostnames']['items']: property_hostnames_list = property_hostnames_list + [ item['cnameFrom'] ] return (property_hostnames_list)
def init_config(edgerc_file, section): global baseurl, session # Check if the edgerc_file variable or the AKAMAI_EDGERC env var exist then use a default value if they don't exist. if not edgerc_file: if not os.getenv("AKAMAI_EDGERC"): edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc') else: edgerc_file = os.getenv("AKAMAI_EDGERC") if not os.access(edgerc_file, os.R_OK): print("Unable to read edgerc file \"%s\"" % edgerc_file) exit(1) if not section: if not os.getenv("AKAMAI_EDGERC_SECTION"): section = "default" else: section = os.getenv("AKAMAI_EDGERC_SECTION") try: edgerc = EdgeRc(edgerc_file) baseurl = 'https://%s' % edgerc.get(section, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) return (baseurl, session) except configparser.NoSectionError: print("Edgerc section \"%s\" not found" % section) exit(1) except Exception: print("Unknown error occurred trying to read edgerc file (%s)" % edgerc_file) exit(1)
def get_properties(contractId, groupId, path, section, switchkey): # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python dict_list = [] edgerc = EdgeRc(path) baseurl = 'https://%s' % edgerc.get(section, "host") http_request = requests.Session() http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section) # setting up request headers headers = {} headers['PAPI-Use-Prefixes'] = "true" http_request.headers = headers # getting the latest property version: https://developer.akamai.com/api/core_features/property_manager/v1.html#getproperties http_response = http_request.get( urljoin( baseurl, '/papi/v1/properties?contractId=' + contractId + '&groupId=' + groupId + '&accountSwitchKey=' + switchkey)) http_status_code = http_response.status_code http_content = json.loads(http_response.text) for item in http_content['properties']['items']: dict_list = dict_list + [{ "latestVersion": item['latestVersion'], "propertyId": item['propertyId'], "contractId": contractId, "groupId": groupId }] return (dict_list)
def api_session(): edgerc = EdgeRc(os.path.expanduser('~/.edgerc')) section = 'default' baseurl = 'https://%s' % edgerc.get(section, 'host') s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section) return [s, baseurl]
def papi_get(edgerc_path, path): edgerc = EdgeRc(edgerc_path) section = 'default' s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section) baseurl = 'https://%s' % edgerc.get(section, 'host') return s.get(urlparse.urljoin(baseurl, path))
def _parse_edgerc(file, section): if not os.path.isfile(file): return None edgerc = EdgeRc(file) config = { "access_token": edgerc.get(section, 'access_token'), "client_token": edgerc.get(section, 'client_token'), "host": edgerc.get(section, 'host'), "max-body": edgerc.getint(section, 'max-body'), "secret": edgerc.get(section, 'client_secret'), "signed-header": edgerc.get(section, 'headers_to_sign') } # The EdgeRc library ensures the whole file must be valid. If host is empty then there's no config found. if config['host'] is None: return None return config
class akamai_api(object): def __init__(self, credfile='.edgerc', section='default'): self.credfile = credfile self.section = section self.edgerc = EdgeRc(self.credfile) self.baseurl = 'https://{}'.format(self.edgerc.get(section, 'host')) self.s = requests.Session() self.s.auth = EdgeGridAuth.from_edgerc(self.edgerc, self.section) def request(self, method, path, **kwargs): url = urljoin(self.baseurl, path) return self.s.request(method, url, **kwargs)
def get_auth(self, username: str = None, password: str = None): rc_path = os.path.expanduser(RC_PATH or os.getenv("RC_PATH") or '~/.edgerc') if not os.path.exists(rc_path): err_msg = "\nERROR: The provided %s file does not exist\n" % rc_path err_msg += "ERROR: Please generate credentials for the script functionality\n" err_msg += "ERROR: and run 'python gen_edgerc.py %s' to generate the credential file\n" sys.stderr.write(err_msg) sys.exit(1) try: rc = EdgeRc(rc_path) except (configparser.DuplicateSectionError, configparser.MissingSectionHeaderError, UnicodeDecodeError): err_msg = ''' ERROR: {0} is not a valid .edgerc file ERROR: Please generate credentials for the script functionality ERROR: and run 'python gen_edgerc.py %s' to generate the credential file '''.format(rc_path) sys.stderr.write(err_msg) sys.exit(2) if not rc.has_section(username): err_msg = "\nERROR: No section named '%s' was found in your .edgerc file\n" % username err_msg += "ERROR: Please generate credentials for the script functionality\n" err_msg += "ERROR: and run 'python gen_edgerc.py %s' to generate the credential file\n" sys.stderr.write(err_msg) sys.exit(3) host = rc.get(username, 'host') host = host.replace("https://", "") host = host.replace("/", "") host += "/" auth = HTTPieEdgeGridAuth( hostname=host, client_token=rc.get(username, 'client_token'), client_secret=rc.get(username, 'client_secret'), access_token=rc.get(username, 'access_token'), max_body=rc.getint(username, 'max_body') ) return auth
def __init__(self, config=None, api=API_Version.Legacy): self._config = config edgerc = EdgeRc(config.edgerc) section = config.section self.extra_qs = {} if api == self.API_Version.Legacy: # Prior to {OPEN} API self._api_ver = api self._content_type_json = {'content-type': 'application/json'} self._content_type_form = \ {'content-type': 'application/x-www-form-urlencoded'} self._headers = None # self._baseurl = 'https://%s' % edgerc.get(section, 'host') self._baseurl = 'https://%s/api/v1/' % edgerc.get( section, 'eaa_api_host') self._session = requests.Session() self._session.auth = EAALegacyAuth( edgerc.get(section, 'eaa_api_key'), edgerc.get(section, 'eaa_api_secret')) else: # EAA {OPEN} API # TODO handle ambiguity when multiple contract ID are in use self._baseurl = 'https://%s/crux/v1/' % edgerc.get(section, 'host') self._session = requests.Session() self._session.auth = EdgeGridAuth.from_edgerc(edgerc, section) # Handle extra querystring to send to all REST requests scanned_extra_qs = edgerc.get(section, 'extra_qs', fallback=None) if scanned_extra_qs: self.extra_qs.update(parse_qs(scanned_extra_qs)) if self._session: self._session.headers.update( {'User-Agent': "cli-eaa/%s" % __version__}) if config.proxy: logging.info("Set proxy to %s" % config.proxy) self._session.proxies['https'] = 'http://%s' % config.proxy logging.info("Initialized with base_url %s" % self._baseurl)
def get_auth(self, username, password): home = os.environ['HOME'] rc = EdgeRc("%s/.edgerc" % home) if not rc.has_section(username): err_msg = "\nERROR: No section named '%s' was found in your .edgerc file\n" % username err_msg += "ERROR: Please generate credentials for the script functionality\n" err_msg += "ERROR: and run 'python gen_edgerc.py %s' to generate the credential file\n" sys.stderr.write(err_msg) sys.exit(1) host=rc.get(username, 'host') host=host.replace("https://", "") host= host.replace ("/","") host += "/" auth = HTTPieEdgeGridAuth( hostname = host, client_token=rc.get(username, 'client_token'), client_secret=rc.get(username, 'client_secret'), access_token=rc.get(username, 'access_token'), max_body=rc.getint(username, 'max_body') ) return auth
class Session(requests.Session): def __init__(self, edgerc, section, switch_key=None, **kwargs): super(Session, self).__init__(**kwargs) self.edgerc = EdgeRc(edgerc) self.section = section self.switch_key = switch_key self.auth = EdgeGridAuth( client_token=self.edgerc.get(section, "client_token"), client_secret=self.edgerc.get(section, "client_secret"), access_token=self.edgerc.get(section, "access_token"), ) def request(self, method, url, params=None, **kwargs): if self.switch_key: params = params if params else {} params.update(accountSwitchKey=self.switch_key) baseUrl = "https://{host}".format( host=self.edgerc.get(self.section, "host")) url = parse.urljoin(baseUrl, url) return super(Session, self).request(method, url, params=params, **kwargs)
def papi_get(edgerc_path, path): edgerc = EdgeRc(edgerc_path) section = 'default' s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section) baseurl = 'https://%s' % edgerc.get(section, 'host') body = s.get(urlparse.urljoin(baseurl, path)) if body.status_code > 200: print "Error, got HTTP status code %s" % body.status_code print body.content exit(1) if body.status_code == 200: return s.get(urlparse.urljoin(baseurl, path))
def get_auth(self, username, password): rc_path = os.path.expanduser("~/.edgerc") rc = EdgeRc(rc_path) if not rc.has_section(username): err_msg = "\nERROR: No section named '%s' was found in your .edgerc file\n" % username err_msg += "ERROR: Please generate credentials for the script functionality\n" err_msg += "ERROR: and run 'python gen_edgerc.py %s' to generate the credential file\n" sys.stderr.write(err_msg) sys.exit(1) host = rc.get(username, 'host') host = host.replace("https://", "") host = host.replace("/", "") host += "/" auth = HTTPieEdgeGridAuth(hostname=host, client_token=rc.get(username, 'client_token'), client_secret=rc.get(username, 'client_secret'), access_token=rc.get(username, 'access_token'), max_body=rc.getint(username, 'max_body')) return auth
def authenticate(params): # get home location home = expanduser("~") filename = "%s/.edgerc" % home # extract edgerc properties edgerc = EdgeRc(filename) # values from ansible endpoint = params["endpoint"] section = params["section"] # creates baseurl for akamai baseurl = 'https://%s' % edgerc.get(section, 'host') s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section) if params["method"] == "GET": response = s.get(urljoin(baseurl, endpoint)) if response.status_code != 400 and response.status_code != 404: return False, False, response.json() else: return True, False, response.json() elif params["method"] == "POST": body = get_request_file(params["body"]) headers = {'content-type': 'application/json'} response = s.post(urljoin(baseurl, endpoint), json=body, headers=headers) if response.status_code != 400 and response.status_code != 404: return False, True, response.json() else: return True, False, response.json() elif params["method"] == "PUT": body = get_request_file(params["body"]) headers = {'content-type': 'application/json'} response = s.put(urljoin(baseurl, endpoint), json=body, headers=headers) if response.status_code != 400 and response.status_code != 404: return False, True, response.json() else: return True, False, response.json() else: # error pass
def get_latest_property_version(propertyId, contractId, groupId, path, section, switchkey): # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python edgerc = EdgeRc(path) baseurl = 'https://%s' % edgerc.get(section, "host") http_request = requests.Session() http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section) # setting up request headers headers = {} headers['PAPI-Use-Prefixes'] = "true" http_request.headers = headers # getting the latest property version: https://developer.akamai.com/api/core_features/property_manager/v1.html#getlatestversion http_response = http_request.get( urljoin( baseurl, '/papi/v1/properties/' + propertyId + '/versions/latest?activatedOn=PRODUCTION&contractId=' + contractId + '&groupId=' + groupId + '&accountSwitchKey=' + switchkey)) http_status_code = http_response.status_code http_content = json.loads(http_response.text) version = re.search('(.*)\/versions\/(\d*)?(.*)', http_content).group(2) return (version)
def load_edgegrid_client_settings(): '''Load Akamai EdgeGrid configuration returns a (hostname, EdgeGridAuth) tuple from the following locations: 1. Values specified directly in the Django settings:: AKAMAI_CCU_CLIENT_SECRET AKAMAI_CCU_HOST AKAMAI_CCU_ACCESS_TOKEN AKAMAI_CCU_CLIENT_TOKEN 2. An edgerc file specified in the AKAMAI_EDGERC_FILENAME settings 3. The default ~/.edgerc file Both edgerc file load options will return the values from the “CCU” section by default. This may be customized using the AKAMAI_EDGERC_CCU_SECTION setting. ''' if getattr(settings, 'AKAMAI_CCU_CLIENT_SECRET', None): # If the settings module has the values directly and they are not empty # we'll use them without checking for an edgerc file: host = settings.AKAMAI_CCU_HOST auth = EdgeGridAuth(access_token=settings.AKAMAI_CCU_ACCESS_TOKEN, client_token=settings.AKAMAI_CCU_CLIENT_TOKEN, client_secret=settings.AKAMAI_CCU_CLIENT_SECRET) return host, auth else: edgerc_section = getattr(settings, 'AKAMAI_EDGERC_CCU_SECTION', 'CCU') edgerc_path = getattr(settings, 'AKAMAI_EDGERC_FILENAME', '~/.edgerc') edgerc_path = os.path.expanduser(edgerc_path) if os.path.isfile(edgerc_path): edgerc = EdgeRc(edgerc_path) host = edgerc.get(edgerc_section, 'host') auth = EdgeGridAuth.from_edgerc(edgerc, section=edgerc_section) return host, auth raise InvalidAkamaiConfiguration('Cannot find Akamai client configuration!')
def create_openapi_request(edgercFile): """Create http request object and signs it with Akamai EdgeGridAuth. Keyword Arguments: edgercFile -- .edgerc file on disk containing Akamai API credentials returns dictionary """ openapiObj = {} if not os.path.isfile(edgercFile): raise FileNotFoundError(edgercFile) edgerc = EdgeRc(edgercFile) section = 'Default' baseurl = 'https://{0}'.format(edgerc.get(section, 'host')) s = requests.Session() try: s.auth = EdgeGridAuth.from_edgerc(edgerc, section) except configparser.NoSectionError: raise ValueError('EdgeRC file missing section: {0}'.format(section)) openapiObj.setdefault('baseurl', baseurl) openapiObj.setdefault('request', s) return openapiObj
def main(): # The script execution should be: python3 add_papi_cli_comments.py <section> <property name> <version notes or comments> section_name = str(sys.argv[1]) pipeline_name = str(sys.argv[2]) pipeline_environment = str(sys.argv[3]) property_comments = str(sys.argv[4]) property_name = pipeline_environment + '.' + pipeline_name global baseurl, session # Define the autorization parameters related to the .edgerc file rc_path = os.path.expanduser('~/.edgerc') edgerc = EdgeRc(rc_path) baseurl = 'https://%s' % edgerc.get(section_name, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section_name) property_id, property_version, property_group_id, property_contract_id = property_cli_get_version_and_id(section_name, property_name) new_rule_tree = edit_rule_tree(property_comments, pipeline_name, pipeline_environment) update_rule_tree(property_id, property_version, property_group_id, property_contract_id, new_rule_tree)
import requests, sys import argparse from akamai.edgegrid import EdgeGridAuth, EdgeRc from urlparse import urljoin import json ################# #################################################### ###### Variable ####### section_name = "dns" domain = "payugur.com" ###################### Authentication & Authorization ############### edgerc = EdgeRc('.edgerc') baseurl = 'https://%s' % edgerc.get(section_name, 'host') ##################################################################### ################# s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section_name) result = s.get(urljoin(baseurl, '/config-dns/v1/zones/%s' % domain)) ##################################################################### #################################### def aws_to_nm(): res = json.loads(result.text) print "Actual Response\n\n" print res # serial = res['zone']['soa']['serial'] # serial = int(serial) + 1
"The section of the edgerc file with the proper {OPEN} API credentials.") args = parser.parse_args() if pipelineUtil.checkPipelineDir(args.pipeline) is not False: log.error('The provided pipeline directory location: ' + args.pipeline + ' is either invalid, or not a Akamai pipeline project') sys.exit(1) stageDict = pipelineUtil.pipelineStages(args.pipeline) log.info('Identified ' + str(len(stageDict.keys())) + ' pipeline stages in pipeline project: ' + args.pipeline) # Initialize EdgeGrid client try: edgerc = EdgeRc(args.config) baseurl = 'https://%s' % edgerc.get(args.section, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, args.section) except Exception as e: log.error('Error authenticating Akamai {OPEN} API client.') log.error(e) for stage in stageDict: propertyId = 'prp_' + str(stageDict[stage]['propertyId']) version = str(stageDict[stage]['propertyVersion']) log.info('Identified propertyId: ' + propertyId + '. Latest Version (pipeline): ' + version) # Get latest version from Luna
section_name="default" debug = False verbose = False session = requests.Session() logger = logging.getLogger(__name__) parser = argparse.ArgumentParser(description='Process command line options.') parser.add_argument('--verbose', '-v', default=False, action='count') parser.add_argument('--debug', '-d', default=False, action='count') args = parser.parse_args() arguments = vars(args) rc_path = os.path.expanduser("~/.edgerc") edgerc = EdgeRc(rc_path) baseurl = 'https://%s' % edgerc.get(section_name, 'host') # Set the config options session.auth = EdgeGridAuth.from_edgerc(edgerc, section_name) if hasattr(edgerc, "debug") or arguments['debug']: client.HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True debug = True if hasattr(edgerc, "verbose") or arguments['verbose']: verbose = True
def main(): pass_int = 1 fail_counter = 0 counter = 0 # defining inputs & argparse parser = argparse.ArgumentParser(prog="dns_lookup_comparison.py v2.0", description="The dns_lookup_comparison.py script compares DNS outputs for a given list of domains.\nDomains are retrieved by an API Call during the execution of the script.\nFor each and every domain, the script issues two DNS requests, one with a specified custom DNS server.\nContributors:\nMiko (mswider) as Chief Programmer") parser.add_argument("zone", default=None, type=str, help="DNS Zone to be tested") parser.add_argument("custom_server_IP", default=None, type=str, help="Custom DNS Server IP address") env_edgerc = os.getenv("AKAMAI_EDGERC") default_edgerc = env_edgerc if env_edgerc else os.path.join(os.path.expanduser("~"), ".edgerc") parser.add_argument("--edgerc_path", help="Full Path to .edgerc File including the filename", default=default_edgerc) env_edgerc_section = os.getenv("AKAMAI_EDGERC_SECTION") default_edgerc_section = env_edgerc_section if env_edgerc_section else "default" parser.add_argument("--section", help="Section Name in .edgerc File", required=False, default=default_edgerc_section) parser.add_argument("--switchkey", default="", required=False, help="Account SwitchKey") parser.add_argument("--enable_logs", default='False', required=False, help="Enable Logs", choices=['True', 'False'],) args = parser.parse_args() enable_logs = args.enable_logs dns_server = args.custom_server_IP section = args.section edgerc_path = args.edgerc_path switchkey = args.switchkey zone = args.zone # defining custom resolver custom_resolver = dns.resolver.Resolver() custom_resolver.nameservers = [dns_server] # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python try: edgerc = EdgeRc(edgerc_path) baseurl = 'https://%s' % edgerc.get(section, "host") except configparser.NoSectionError: print("\nThe path to the .edgerc File or the Section Name provided is not correct. Please review your inuputs.\n") else: http_request = requests.Session() http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section) # setting up request headers headers = {} headers['PAPI-Use-Prefixes'] = "true" http_request.headers = headers http_response = http_request.get(urljoin(baseurl, "/config-dns/v2/zones/"+zone+"/recordsets?showAll=true&accountSwitchKey="+switchkey)) http_status_code= http_response.status_code http_content= json.loads(http_response.text) # Checking the first API call response code to avoid any exceptions further on ... if http_status_code == 200: record_list = http_content["recordsets"] #print(record_list) for record in record_list: time.sleep(1) #print(record) counter =counter + 1 try: output1 = (dns.resolver.resolve(record["name"],record["type"], raise_on_no_answer=False)) output2 = (custom_resolver.resolve(record["name"],record["type"], raise_on_no_answer=False)) except dns.exception.Timeout: print("\nTest FAILED for " + str(record["name"]) + " domain, " + str(record["type"]) + " record type, because of DNS Timeout.") pass_int = pass_int*0 fail_counter = fail_counter + 1 except dns.rdatatype.UnknownRdatatype: print("\nTest FAILED for " + str(record["name"]) + " domain, " + str(record["type"]) + " record type, because of non standard DNS record type.") pass_int = pass_int*0 fail_counter = fail_counter + 1 except dns.resolver.NoNameservers: print("\nTest FAILED for " + str(record["name"]) + " domain, " + str(record["type"]) + " record type, because all nameservers failed to answer the query.") pass_int = pass_int*0 fail_counter = fail_counter + 1 except dns.resolver.NXDOMAIN: print("\nTest FAILED for " + str(record["name"]) + " domain, " + str(record["type"]) + " record type, because of non existent domain.") pass_int = pass_int*0 fail_counter = fail_counter + 1 else: if output1.rrset != output2.rrset: pass_int = pass_int*0 fail_counter = fail_counter + 1 print("\nTest FAILED for " + str(record["name"]) + " domain, " + str(record["type"]) + " record type, while using " + str(dns_server) + " custom DNS server.\n \nRegular Lookup: \n" + str(output1.rrset) + "\nCustom Lookup: \n" + str(output2.rrset)) else: if enable_logs == "True": print("\nTest PASSED for "+ str(record["name"]) + " domain, " + str(record["type"]) + " record type. Both DNS servers returned: \n"+ str(output1.rrset)) print("\nProcessed all " + str(counter) + " domains.") if pass_int == 1: print("\nTest PASSED for all domains while using " + str(dns_server) + " custom DNS server. \n") else: print("\nTest FAILED for " + str(fail_counter) + " domains while using " + str(dns_server) + " custom DNS server. \n") else: print("\nAPI Call Failure") print(http_response.text)
import requests from akamai.edgegrid import EdgeGridAuth, EdgeRc from urlparse import urljoin #Credential authentication edgerc = EdgeRc('/home/witadmin/.edgerc') section = 'default' a = edgerc.get(section, 'host') baseurl = 'https://%s' % edgerc.get(section, 'host') s = requests.Session() s.auth = EdgeGridAuth.from_edgerc(edgerc, section) path = '/network-list/v2/network-lists?' #networklist name. search = input('Networklist name:') #true or false. iE = input('includeElement:') #true or false. extend = input('Extended:') #IP or GEO. listType = input('ListType:') w = '&search=' + search x = 'includeElements=' + iE y = '&extended=' + extend z = '&listType=' + listType #Get information from Akamai server. full_path = path + x + w + y + z url = urljoin(baseurl, full_path) a = s.get(url) print(a)
def main(): # defining variables dict_list = [] # list of all property hostnames within the account property_hostnames_list = [] # list of all property hostnames within the account that are cnamed to the input edge hostname answer_list = [] nb_groups = 0 nb_contracts = 0 nb_properties = 0 nb_hostnames = 0 warning = False nx_domain_list = [] unknown_list = [] timeout_list = [] no_name_list = [] # defining inputs & argparse parser = argparse.ArgumentParser( prog="edge_hostname_cname_checker.py v2.0", description= "The edge_hostname_cname_checker.py script finds all property hostnames CNAMEd to an input Edge Hostname, within a Customer Account. The script uses edgegrid for python, dnspython and argparse libraries. Contributors: Miko (mswider) as Chief Programmer" ) parser.add_argument("edge_hostname", default=None, type=str, help="Edge Hostname to be tested") env_edgerc = os.getenv("AKAMAI_EDGERC") default_edgerc = env_edgerc if env_edgerc else os.path.join( os.path.expanduser("~"), ".edgerc") parser.add_argument( "--edgerc_path", help="Full Path to .edgerc File including the filename", default=default_edgerc) env_edgerc_section = os.getenv("AKAMAI_EDGERC_SECTION") default_edgerc_section = env_edgerc_section if env_edgerc_section else "default" parser.add_argument("--section", help="Section Name in .edgerc File", required=False, default=default_edgerc_section) parser.add_argument("--switchkey", default="", required=False, help="Account SwitchKey") args = parser.parse_args() # Adjusting argpare variables with variables already used in previous version of script edge_hostname = args.edge_hostname path = args.edgerc_path section = args.section switchkey = args.switchkey # setting up authentication as in https://github.com/akamai/AkamaiOPEN-edgegrid-python try: edgerc = EdgeRc(path) baseurl = 'https://%s' % edgerc.get(section, "host") except configparser.NoSectionError: print( "\nThe path to the .edgerc File or the Section Name provided is not correct. Please review your inuputs.\n" ) else: http_request = requests.Session() http_request.auth = EdgeGridAuth.from_edgerc(edgerc, section) # setting up request headers headers = {} headers['PAPI-Use-Prefixes'] = "true" http_request.headers = headers print( '\nGetting the list of all groups and all associated contracts...') #https://developer.akamai.com/api/core_features/property_manager/v1.html#getgroups http_response = http_request.get( urljoin(baseurl, '/papi/v1/groups?accountSwitchKey=' + switchkey)) http_status_code = http_response.status_code http_content = json.loads(http_response.text) # Checking the first API call response code to avoid any exceptions further on ... if http_status_code == 200: print('Getting the list of all properties...') for item in http_content['groups']['items']: nb_groups = nb_groups + 1 for contractId in item['contractIds']: nb_contracts = nb_contracts + 1 dict_list = dict_list + get_properties( contractId, item['groupId'], path, section, switchkey) nb_properties = len(dict_list) print('There are ' + str(nb_groups) + ' groups, ' + str(nb_contracts) + ' contracts and ' + str(nb_properties) + ' properties in the ' + switchkey + ' account.') print('\nGetting the list of all property hostnames...') for bloc in dict_list: property_hostnames_list = property_hostnames_list + get_property_hostnames( bloc['latestVersion'], bloc['propertyId'], bloc['contractId'], bloc['groupId'], path, section, switchkey) nb_hostnames = len(property_hostnames_list) print('There are ' + str(nb_hostnames) + ' property hostnames in the ' + switchkey + ' account.') print( '\nProceeding with DNS (CNAME record) resolution of all property hostnames...' ) for hostname in property_hostnames_list: try: output = (dns.resolver.resolve(hostname, 'CNAME', raise_on_no_answer=False)) except dns.exception.Timeout: warning = True timeout_list = timeout_list + [hostname] except dns.rdatatype.UnknownRdatatype: warning = True unknown_list = unknown_list + [hostname] except dns.resolver.NXDOMAIN: warning = True nx_domain_list = nx_domain_list + [hostname] except dns.resolver.NoNameservers: warning = True no_name_list = no_name_list + [hostname] else: if (" " + edge_hostname) in str(output.rrset): answer_list = answer_list + [hostname] # Displaying hostnames for which DNS resolution failed if timeout_list != []: print( 'The DNS resolution failed with the exception dns.exception.Timeout for:' ) print(*timeout_list, sep="\n") if unknown_list != []: print( 'The DNS resolution failed with the exception dns.rdatatype.UnknownRdatatype for:' ) print(*unknown_list, sep="\n") if nx_domain_list != []: print( 'The DNS resolution failed with the exception dns.resolver.NXDOMAIN for:' ) print(*nx_domain_list, sep="\n") if no_name_list != []: print( 'The DNS resolution failed with the exception dns.resolver.NoNameservers for:' ) print(*no_name_list, sep="\n") # Displaying final answers if warning: if answer_list == []: print( "\nThe DNS (CNAME record) resolution was not successfull for the records printed above. Appart from these, there are no property hostnames CNAMEd to " + str(edge_hostname) + ".") print("\n") else: print( "\nThe DNS (CNAME record) resolution was not successfull for the records printed above. Appart from these, the following property hostname(s) is/are CNAMEd to " + str(edge_hostname) + ":") print(*answer_list, sep="\n") print("\n") else: if answer_list == []: print("There are no property hostnames CNAMEd to " + str(edge_hostname) + ".") print("\n") else: print( "The following property hostname(s) is/are CNAMEd to " + str(edge_hostname) + ":") print(*answer_list, sep="\n") print("\n") else: print("\nAPI call not successful!") print(http_response.text)
import json from akamai.edgegrid import EdgeGridAuth, EdgeRc from urllib.parse import urljoin from openpyxl import load_workbook import re import openpyxl, pprint import sys import argparse from datetime import datetime import calendar import os #AUTH SECTION edgerc_file = os.path.join(os.path.expanduser("~"), '.edgerc') edgerc = EdgeRc(edgerc_file) section = "dns" base_url = edgerc.get(section, 'host') baseurl = str('https://') + str(base_url) client_token = edgerc.get(section, 'client_token') client_secret = edgerc.get(section, 'client_secret') access_token = edgerc.get(section, 'access_token') s = requests.Session() s.auth = EdgeGridAuth(client_token=client_token, client_secret=client_secret, access_token=access_token) if __name__ == '__main__': accountSwitchKey = "ACCT_SWITCH_KEY" wb = load_workbook('input.xlsx') sheet = wb['Sheet1'] sheet2 = wb['Sheet2'] print("Number of entries is:", sheet.max_row - 1, "hostnames") i = 2
log.error('Ensure the file is properly pathed and exists, with read permissions.') sys.exit(1) fileFormat = apiGwHelper.determineDefinitionType(swaggerFile) log.info('Using + ' + fileFormat + ' file: ' + swaggerFile) ''' Edgegrid authentication Section Session and baseurl objects will be passed to helper methods. ''' log.debug('Initializing Akamai {OPEN} client authentication. Edgerc: ' + edgeRcLoc + ' Section: ' + edgeRcSection) try: edgerc = EdgeRc(edgeRcLoc) baseurl = 'https://%s' % edgerc.get(edgeRcSection, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, edgeRcSection) log.debug('API Base URL: ' + baseurl) except Exception as e: log.error('Error authenticating Akamai {OPEN} API client.') log.error(e) result = apiGwHelper.getApiGwID(session, baseurl, name) if result is None: log.error('No API definition could be found with the name: \'' + name + '\'') log.error('Please make sure the correct name is specified, or it exists on the contract tied to your Edgegrid API authorizations.') sys.exit(1) else:
### 3.1 Setting Up the Environment import requests import json from akamai.edgegrid import EdgeGridAuth, EdgeRc from urllib.parse import urljoin edgerc = EdgeRc('.edgerc') section = 'idm' baseurl = 'https://{}'.format(edgerc.get(section, 'host')) session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) # print(baseurl) client_id = 'e4zlatds7ky33his' ### 3.2 Getting Credential ID path = '/identity-management/v1/open-identities/{}/credentials'.format( client_id) # print(path) url = urljoin(baseurl, path) # print(url) ret = session.get(url) ret_json = json.dumps(ret.json(), indent=2) print(ret_json)
def propertyManagerAPI(action:str,config:str=None,p:list=None): try: home = str(Path.home()) edgerc = EdgeRc(home+"/.edgerc") if args['section']: section = args['section'] else: section = 'papi' host = edgerc.get(section,'host') except Exception as e: logger.debug("Error Autehticating Edgerc {}.".format(home+edgerc)) http = requests.Session() http.auth= EdgeGridAuth.from_edgerc(edgerc,section) validActions = ["ListGroups","ListContracts","ListProperties","GetRuleTree","SearchProperty"] if action not in validActions: parser.error("Error: PAPI Unknown Action") #ListGroups elif action == validActions[0]: if args['verbose']: logger.debug("Listing account groups with PAPI.") if args['account_key']: endpoint='/papi/v1/groups?accountSwitchKey={}'.format(args['account_key']) else: endpoint= '/papi/v1/groups' result = http.get(urljoin("https://" + host + "/", endpoint)) response = json.loads(json.dumps(result.json())) http.close() return response #ListProperties elif action == validActions[2]: gps = propertyManagerAPI("ListGroups") if gps is None: logger.warning("No Groups were found in account!") return None # elif gps['incidentId']: # logger.error('{}'.format(gps['title'])) # return None for gp in gps['groups']['items']: for contract in gp['contractIds']: if args['verbose']: logger.debug("Listing properties in '{}'/'{}' with PAPI.".format(gp['groupId'],contract)) if args['account_key']: endpoint= '/papi/v1/properties?contractId={}&groupId={}&accountSwitchKey={}'.format(contract,gp['groupId'],args['account_key']) else: endpoint= '/papi/v1/properties?contractId={}&groupId={}'.format(contract,gp['groupId']) result = http.get(urljoin("https://" + host + "/", endpoint)) http.close() response = json.loads(json.dumps(result.json())) for p in response['properties']['items']: if p['productionVersion'] is None or p is None: item={} er=[] er.append("The configuration has no active version in production.") if args['verbose']: logger.warning("The configuration '{}' has no active version in production.".format(p['propertyName'])) item['propertyName']=p['propertyName'] item['errors']=er item_list.append(item) else: p['propertyVersion']=p['productionVersion'] del p['productionVersion'] propertyManagerAPI("GetRuleTree","",p) elif action == validActions[3]: if args['verbose']: logger.debug("Getting rule tree for the '{}' property with PAPI.".format(p['propertyName'])) if args['account_key']: endpoint= "/papi/v1/properties/{}/versions/{}/rules?contractId={}&groupId={}&validateRules=true&validateMode=fast&accountSwitchKey={}".format( p['propertyId'], p['propertyVersion'], p['contractId'], p['groupId'], args['account_key'] ) else: endpoint= "/papi/v1/properties/{}/versions/{}/rules?contractId={}&groupId={}&validateRules=true&validateMode=fast".format( p['propertyId'], p['propertyVersion'], p['contractId'], p['groupId'] ) result = http.get(urljoin("https://" + host + "/", endpoint)) http.close() readObject(json.loads(json.dumps(result.json())) ,"API",p['propertyName']) elif action == validActions[4]: if args['verbose']: logger.debug("Looking for the configuration '{}'.".format(config)) if args['account_key']: endpoint='/papi/v1/search/find-by-value?accountSwitchKey={}'.format(args['account_key']) else: endpoint='/papi/v1/search/find-by-value' postbody = {} postbody['propertyName'] = config result = http.post(urljoin("https://" + host + "/", endpoint),json.dumps(postbody), headers={"Content-Type": "application/json"}) http.close() if result.json()['versions']['items'] == []: item={} er=[] item['propertyName']=config if args['verbose']: logger.warning("The configuration '{}' was not found.".format(config)) er.append("The configuration was not found.") item['errors']=er item_list.append(item) return else: if args['verbose']: logger.debug("The configuration '{}' was found.".format(config)) prodversion = None for i in result.json()['versions']['items']: if i['productionStatus'] == "ACTIVE": prodversion = True propertyManagerAPI("GetRuleTree","",i) if prodversion is None: item={} er=[] if args['verbose']: logger.warning("The configuration '{}' has no active version in production.".format(config)) er.append("The configuration has no active version in production.") item['propertyName']=config item['errors']=er item_list.append(item) return json.loads(json.dumps(result.json())) return None
class Akamai: response = {} http_status = 0 # .................................................................................................. def __init__(self, **credentials): self.user = credentials.get('user', config_user) self.password = credentials.get('password', config_password) self.use_arl = credentials.get('use_arl', False) self.edgerc_location = credentials.get('edgerc', edgerc_location) self.edgerc_section = credentials.get('edgerc_section', edgerc_section) assert self.password, "Error: missing API password" assert self.user, "Error: missing API user" assert self.edgerc_location, "Error: missing edgerc file" assert self.edgerc_section, "Error: missing edgerc section" self.edgerc = EdgeRc(self.edgerc_location) section = self.edgerc_section self.baseurl = 'https://%s' % self.edgerc.get(section, 'host') return None # .................................................................................................. def purge(self, url_list, **kwargs): # if no parameters passed, initialize to an empty set. kwargs = kwargs if kwargs is not None else {} # retrieve dynamic parameters and set defaults platform = kwargs.get('platform', 'production') queue = kwargs.get('queue', 'default') action = kwargs.get('action', 'remove') list_type = kwargs.get('list_type', 'arl') assert type(url_list) is list, "Error: expecting a list of assets" assert platform in [ 'production', 'staging' ], "Error: %r is wrong platform, must be production or staging" % ( platform) assert queue in [ 'default', 'emergency' ], "Error: %r is wrong queue, must be default or emergency" % (queue) assert action in [ 'delete', 'invalidate' ], "Error: %r is wrong action, must be delete or invalidate" % (action) assert list_type in [ 'arl', 'cpcode' ], "Error: %r is wrong list type, must be arl or cpcode" % (list_type) if self.use_arl: url_list = [self.get_arl(url) for url in url_list] payload = {"objects": url_list} command = "/ccu/v3/%s/url/%s" % (action, platform) query = {} result = self.executeAPI(command, payload, query, verb='POST') return json.loads(result) # .................................................................................................. def get_arl(self, url, **kwargs): # if no parameters passed, initialize to an empty set. kwargs = kwargs if kwargs is not None else {} request_headers = { "Pragma": "akamai-x-cache-on,akamai-x-cache-remote-on,akamai-x-check-cacheable,akamai-x-get-cache-key,akamai-x-get-true-cache-key,akamai-x-serial-no,akamai-x-get-request-id,akamai-x-get-client-ip,akamai-x-feo-trace" } r = requests.request('HEAD', url, headers=request_headers, json={}, params={}) response_headers = dict(r.headers) x_cache_key = response_headers.get("X-Cache-Key", "") # typical response looks like # 'L1/=/16382/705116/1d/castplus-usw2-prod-served-episodes.s3-us-west-2.amazonaws.com/1.html' self.http_status = r.status_code self.http_content = r.content if x_cache_key: arl = x_cache_key return arl else: return url # .................................................................................................. def executeAPI(self, api_command, api_payload, query, verb='GET', headers={}): api_base_url = self.baseurl action = api_command url = urljoin(self.baseurl, action) request_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } request_headers.update(headers) session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(self.edgerc, self.edgerc_section) r = session.request(verb, url, headers=request_headers, json=api_payload, params=query) self.http_status = r.status_code self.http_content = r.content content = r.content return (content) # .................................................................................................. def construct_url(self, base, bucket, key, vendor=None): # ignore vendor and bucket at the moment return 'http://{}/{}'.format(base, key)
ARGS = PARSER.parse_args() # PICK AN EDGERC FILE if ARGS.edgerc: # If --edgerc option flag is declared, use that vs. the default EDGERC_PATH = (ARGS.edgerc) else: # Default .edgerc file is located in the users home directory EDGERC_PATH = (os.path.expanduser('~') + '/.edgerc') EDGERC = EdgeRc(EDGERC_PATH) SECTION = str(ARGS.section) # Error checking the .edgerc file if (EDGERC.get(SECTION, 'host').find('://')) > 0: print('You have an invalid entry on your --edgerc ' + EDGERC_PATH + ' file '\ 'under your --section ' + SECTION + '. '\ 'Please remove the http(s):// at the beginning.', '\n') raise SystemExit BASEURL = 'https://%s' % EDGERC.get(SECTION, 'host') if str(ARGS.verbose) != 'False' and str(ARGS.verbose) >= '2': print("Command variables") print('\t', 'command: ' + str(ARGS.command), '\n', '\t', '--cid: ' + str(ARGS.cid), '\n', '\t', '--gid: ' + str(ARGS.gid), '\n', '\t', '--pid: ' + str(ARGS.pid), '\n', '\t', '--vid: ' + str(ARGS.vid), '\n', '\t', '--VERSION: ' + str(ARGS.version_source), '\n', '\t', '--prd: ' + str(ARGS.prd), '\n', '\t',