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 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_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 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 __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 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))
def __init__(self, edgedns_creds): logger.debug("creating _EdgeDNSClient") pathhost = "" if EDGEGRID_CREDS["edgerc_path"]: section = 'default' if EDGEGRID_CREDS["edgerc_section"]: section = EDGEGRID_CREDS["edgerc_section"] pathhost = EdgeRc(EDGEGRID_CREDS["edgerc_path"]).get(section, 'host') self.edgegrid_auth = EdgeGridAuth.from_edgerc(EDGEGRID_CREDS["edgerc_path"], section) else: pathhost = EDGEGRID_CREDS["host"] self.edgegrid_auth = EdgeGridAuth(client_token = EDGEGRID_CREDS["client_token"], client_secret = EDGEGRID_CREDS["client_secret"], access_token = EDGEGRID_CREDS["access_token"]) # Error checking the .edgerc file if pathhost.find('://') > 0: raise errors.PluginError('{0}: You have specified an invalid host entry ' 'Please remove the http(s):// at the beginning.' ) root_path = self.BASEURL.format(pathhost) self.EDGEDNSROOTURL = urljoin(root_path, "/config-dns/v2/") self.EDGEDNSZONESURL = self.EDGEDNSROOTURL + "zones/" self.EDGEDNSCHANGESURL = self.EDGEDNSROOTURL + "changelists" self.recordset_semaphore = threading.Semaphore() return
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 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__(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 test_edgerc_from_object(self): auth = EdgeGridAuth.from_edgerc( EdgeRc(os.path.join(mydir, 'sample_edgerc'))) self.assertEqual(auth.client_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx') self.assertEqual(auth.client_secret, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=') self.assertEqual(auth.access_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx') self.assertEqual(auth.max_body, 131072) self.assertEqual(auth.headers_to_sign, [])
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 __init__(self, config): from akamai.edgegrid import EdgeGridAuth, EdgeRc self.config = config self.log = logging.getLogger(__name__) self.edgerc = EdgeRc(os.path.expanduser('~/.edgerc')) self.section = 'default' if config.has_option('akamai', 'section'): self.section = config.get('akamai', 'section') self.contract_id = config.get('akamai', 'contract_id') self.baseurl = 'https://%s' % self.edgerc.get(self.section, 'host') self.session = requests.Session() self.session.auth = EdgeGridAuth.from_edgerc(self.edgerc, self.section) self.dry_run = True if config.has_option('akamai', 'dry_run'): self.dry_run = config.getboolean('akamai', 'dry_run')
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 _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
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 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_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 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 __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 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)
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 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
### Devloped by Ankit Kashyap ######## 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']
import logging 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']:
help= "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)
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)
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
#Importing the libraries import requests 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']
'--version', action='version', version='%(prog)s {}'.format(VERSION), help='Show the version of %(prog)s and exit') 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: ' +