Exemple #1
0
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)
Exemple #2
0
 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)
Exemple #3
0
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
Exemple #4
0
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)
Exemple #5
0
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__(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 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))
Exemple #8
0
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)
Exemple #9
0
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 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))  
Exemple #12
0
 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 __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 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))  
Exemple #15
0
 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)
Exemple #16
0
 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')
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
Exemple #18
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
Exemple #19
0
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 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, [])
Exemple #21
0
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)
Exemple #22
0
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!')
Exemple #23
0
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)
Exemple #24
0
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)
Exemple #25
0
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)
Exemple #26
0
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
Exemple #27
0
    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
Exemple #28
0
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
Exemple #29
0
    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
Exemple #30
0
    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
### 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']:
Exemple #34
0
    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)