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, [])
示例#2
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)
示例#3
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)
示例#4
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)
示例#5
0
文件: run.py 项目: oways/AWP
def main():
    s = requests.Session()
    # Akamai auth
    s.auth = EdgeGridAuth.from_edgerc(edgerc, section)
    url = 'https://{}/siem/v1/configs/{}?offset={}&from={}&to={}&limit={}'.format(
        edgerc.get(section, 'host'), configIds, offset, firstTS, currentTS,
        limit)
    result = s.get(url)
    content = result.content.decode("utf-8")
    data = []
    lines = content.splitlines()
    lastLine = json.loads(lines[len(lines) - 1])
    for l in lines[:-1]:
        try:
            j = json.loads(l)
            tags = decoder(j['attackData']['ruleTags'])
            # Filtering logs for only builtin Akamai web attacks and polices (ex. sqli, xss & rce)
            if "WEB_ATTACK" in tags or "/POLICY/" in tags:
                data.append(decodeData(j))
        except Exception as e:
            print(e)

    with open(offsetPath, "w+") as f:
        f.write(lastLine['offset'])

    # Send data to syslog server
    sendSyslog(data)
    # Checking if every thing went will
    healthCheck()
示例#6
0
def papi_latest(account_key, cid, gid, pid, version_source, verbose):
    """ Not doing any checks because you should call this directly.  There is no value. """

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '?contractId=' + cid +
            '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, version_source])
    success_check(result.status_code, "200", list_dict, verbose)

    if version_source == "PRODUCTION":
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["productionVersion"])
    elif version_source == "STAGING":
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["stagingVersion"])
    else:
        source_json = json.dumps(
            list_dict["properties"]["items"][0]["latestVersion"])

    return source_json
示例#7
0
def papi_products(account_key, cid, verbose):
    """ Getting a list of products """

    if not cid:
        print(
            'Contract ID is required to get a list of Products.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(BASEURL, '/papi/v1/products?contractId=' + cid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [account_key, cid])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('contractId:', list_dict["contractId"])
    print('Products:')
    sorted_groups = sorted(list_dict["products"]["items"],
                           key=lambda x: x['productName'])
    print('\t', 'productName;', 'productId;')
    for items in sorted_groups:
        print('\t', items['productName'] + ';', items['productId'] + ';')
    print('\n')
示例#8
0
def papi_groups(account_key, verbose):
    """ Getting a list of groups """

    gssapi = ''
    if account_key:
        gssapi = '?accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(urljoin(BASEURL, '/papi/v1/groups' + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [account_key])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('accountName:', list_dict["accountName"])
    print('Groups:')
    sorted_groups = sorted(list_dict["groups"]["items"],
                           key=lambda x: x['groupName'])
    print('\t', 'groupName;', 'groupId;', 'parentGroupId;')
    for items in sorted_groups:
        parent_id = items[
            "parentGroupId"] if "parentGroupId" in items else "n/a"
        print('\t', items['groupName'] + ';', items['groupId'] + ';',
              parent_id + ';')
    print('\n')
    def test_get_header_versions(self):
        auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'headers')
        header = auth.get_header_versions()
        self.assertFalse('user-agent' in header)

        header = auth.get_header_versions({'User-Agent': 'testvalue'})
        self.assertTrue('User-Agent' in header)

        os.environ["AKAMAI_CLI"] = '1.0.0'
        os.environ["AKAMAI_CLI_VERSION"] = '1.0.0'

        header = auth.get_header_versions()
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], ' AkamaiCLI/1.0.0')

        os.environ["AKAMAI_CLI_COMMAND"] = '1.0.0'
        os.environ["AKAMAI_CLI_COMMAND_VERSION"] = '1.0.0'

        header = auth.get_header_versions()
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], ' AkamaiCLI/1.0.0 AkamaiCLI-1.0.0/1.0.0')

        header = auth.get_header_versions({'User-Agent': 'testvalue'})
        self.assertTrue('User-Agent' in header)
        self.assertEqual(header['User-Agent'], 'testvalue AkamaiCLI/1.0.0 AkamaiCLI-1.0.0/1.0.0')

        del os.environ['AKAMAI_CLI']
        del os.environ['AKAMAI_CLI_VERSION']
        del os.environ['AKAMAI_CLI_COMMAND']
        del os.environ['AKAMAI_CLI_COMMAND_VERSION']

        self.assertFalse('AKAMAI_CLI' in os.environ)
        self.assertFalse('AKAMAI_CLI_VERSION' in os.environ)
        self.assertFalse('AKAMAI_CLI_COMMAND' in os.environ)
        self.assertFalse('AKAMAI_CLI_COMMAND_VERSION' in os.environ)
示例#10
0
 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)
示例#11
0
def papi_hostnames(account_key, cid, gid, pid, vid, verbose):
    """ Not doing any checks because you should call this directly.  There is no value. """

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '/versions/' + vid +
            '/hostnames?contractId=' + cid + '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, vid])
    success_check(result.status_code, "200", list_dict, verbose)

    # etag is needed for authentication
    etag = list_dict['etag']
    hosts = list_dict['hostnames']['items']

    return (etag, hosts)
示例#12
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)
示例#13
0
    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))
示例#14
0
 def test_edgerc_unparseable(self):
     try:
         auth = EdgeGridAuth.from_edgerc(
             os.path.join(mydir, 'edgerc_test_doesnt_parse'))
         self.fail("should have thrown an exception")
     except:
         pass
示例#15
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]
示例#16
0
def papi_config(account_key, cid, gid, pid, vid, verbose):
    """ Getting a config detail in JSON format """

    if not cid or not gid or not pid or not vid:
        print(
            'Contract ID, Group ID, Property ID, and Version ID is required to get a the '
            'property config details.  This will be printed in JSON format.')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '/versions/' + vid +
            '/rules?contractId=' + cid + '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, vid])
    success_check(result.status_code, "200", list_dict, verbose)

    print(json.dumps(list_dict))
示例#17
0
    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
示例#18
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)
示例#19
0
def papi_versions(account_key, cid, gid, pid, verbose):
    """ Getting a list of versions of a config """

    if not cid:
        print(
            'Contract ID is required to get a list of property versions.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit
    if not gid:
        print(
            'Group ID is required to get a list of property versions.  '
            'To get a list of groups, use "./' + os.path.basename(__file__) +
            ' groups"', '\n')
        raise SystemExit
    if not pid:
        print(
            'Property ID is required to get a list of property versions.  '
            'To get a list of properties, use "./' +
            os.path.basename(__file__) + ' properties"', '\n')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/properties/' + pid + '/versions?contractId=' +
            cid + '&groupId=' + gid + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('contractId:', list_dict["contractId"])
    print('groupId:', list_dict["groupId"])
    print('Versions:')
    sorted_groups = sorted(list_dict["versions"]["items"],
                           key=lambda x: x['propertyVersion'],
                           reverse=True)
    print('\t', 'propertyVersion;', 'updatedDate;', 'updatedByUser;',
          'productionStatus;', 'stagingStatus;', 'ruleFormat;', 'notes;')
    for items in sorted_groups[:10]:
        note = items['note'] if "note" in items else "n/a"
        print('\t',
              str(items['propertyVersion']) + ';', items['updatedDate'] + ';',
              items['updatedByUser'] + ';', items['productionStatus'] + ';',
              items['stagingStatus'] + ';', items['ruleFormat'] + ';',
              note + ';')
    print('\n')
示例#20
0
 def test_edgerc_broken(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'),
                                     'broken')
     self.assertEqual(auth.client_secret,
                      'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=')
     self.assertEqual(auth.access_token,
                      'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx')
     self.assertEqual(auth.max_body, 128 * 1024)
     self.assertEqual(auth.headers_to_sign, [])
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))  
示例#22
0
def papi_edgehostnames(account_key, cid, gid, verbose):
    """ Getting a list of edge Hostnames """

    if not cid:
        print(
            'Contract ID is required to get a list of Edge Hostnames.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit
    if not gid:
        print(
            'Group ID is required to get a list of Edge Hostnames.  '
            'To get a list of groups, use "./' + os.path.basename(__file__) +
            ' groups"', '\n')
        raise SystemExit

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(
        urljoin(
            BASEURL, '/papi/v1/edgehostnames?contractId=' + cid + '&groupId=' +
            gid + '&options=mapDetails' + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('contractId:', list_dict["contractId"])
    print('groupId:', list_dict["groupId"])
    print('Edge Hostnames:')
    sorted_groups = sorted(list_dict["edgeHostnames"]["items"],
                           key=lambda x: x['edgeHostnameDomain'])
    print('\t', 'edgeHostnameDomain;', 'edgeHostnameId;', 'productId;',
          'domainPrefix;', 'domainSuffix;', 'status;', 'secure;',
          'SerialNumber;', 'SlotNumber;', 'Map Domain;')
    for items in sorted_groups:
        product_id = items['productId'] if "productId" in items else "n/a"
        status = items['status'] if "status" in items else "n/a"
        slot_number = items[
            'mapDetails:slotNumber'] if "mapDetails:slotNumber" in items else "n/a"
        print('\t', items['edgeHostnameDomain'] + ';',
              items['edgeHostnameId'] + ';', product_id + ';',
              items['domainPrefix'] + ';', items['domainSuffix'] + ';',
              status + ';',
              str(items['secure']) + ';',
              str(items['mapDetails:serialNumber']) + ';',
              str(slot_number) + ';', items['mapDetails:mapDomain'] + ';')
    print('\n')
示例#23
0
 def test_edgerc_default(self):
     auth = EdgeGridAuth.from_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, [])
示例#24
0
def papi_newconfig(account_key, cid, gid, pid, version_source, verbose):
    """ Creating a new config from Latest, Staging, or Production """

    if not cid:
        print(
            'Contract ID is required to create a new property version.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit
    if not gid:
        print(
            'Group ID is required to create a new property version.  '
            'To get a list of groups, use "./' + os.path.basename(__file__) +
            ' groups"', '\n')
        raise SystemExit
    if not pid:
        print(
            'Property ID is required to create a new property version.  '
            'To get a list of properties, use "./' +
            os.path.basename(__file__) + ' properties"', '\n')
        raise SystemExit

    vid = papi_latest(account_key, cid, gid, pid, version_source, verbose)
    etag = papi_etag(account_key, cid, gid, pid, vid, verbose)

    data = '{"createFromVersion": ' + vid + ',"createFromVersionEtag": ' + etag + '}'
    headers = {'Content-Type': 'application/json'}

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.post(urljoin(
        BASEURL, '/papi/v1/properties/' + pid + '/versions?contractId=' + cid +
        '&groupId=' + gid + gssapi),
                          data=(data),
                          headers=headers)

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, version_source])
    success_check(result.status_code, "201", list_dict, verbose)

    if list_dict["versionLink"]:
        string = list_dict["versionLink"]
        paths = string.split('?')
        subpaths = paths[0].split('/')
        print("Your new version is: " + subpaths[6])
        papi_status(string, inspect.currentframe().f_code.co_name, verbose)
        print('\n')
示例#25
0
def papi_activate(account_key, cid, gid, pid, vid, network, email, verbose):
    """ activate a config to Staging or Production """

    if not pid or not gid or not pid or not vid:
        print('Contract ID, Group ID, Property ID, Version ID\
            are required to activate a config.')
        raise SystemExit
    if not network or not email:
        print('Akamai Network, and email address\
            are required to activate a config.')
        raise SystemExit

    data = '{"propertyVersion": ' + vid + ',"network": "' + network + '","note": "API activation","notifyEmails": ' + str(
        json.dumps(email)
    ) + ',"acknowledgeAllWarnings": true,"useFastFallback": false}'
    if verbose != 'False' and network == "PRODUCTION":
        # Akamai Employees need Compliance notes when pushing to prod
        data = '{"propertyVersion": ' + vid + ',"network": "' + network + '","note": "API activation","notifyEmails": ' + str(
            json.dumps(email)
        ) + ',"acknowledgeAllWarnings": true,"useFastFallback": false,"complianceRecord": {"noncomplianceReason": "NO_PRODUCTION_TRAFFIC"}}'
        print("You are brave sending a Verbose value of " + verbose)
        print(
            "I'll format a non-compliant request to bypass an Akamai employee Change\
            Management requirement, as you wish.")
        print(data)
        print(" ")
    headers = {'Content-Type': 'application/json'}

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.post(urljoin(
        BASEURL, '/papi/v1/properties/' + pid + '/activations?contractId=' +
        cid + '&groupId=' + gid + gssapi),
                          data=(data),
                          headers=headers)

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, pid, vid, network, email])
    success_check(result.status_code, "201", list_dict, verbose)

    if list_dict["activationLink"]:
        string = list_dict["activationLink"]
        print("Activation Request has been sent!  Checking on status...")
        papi_status(string, inspect.currentframe().f_code.co_name, verbose)

    print('\n')
示例#26
0
def papi_newcpcode(account_key, cid, gid, prd, cpname, verbose):
    """ Requesting a new CPCode """

    if not cid:
        print(
            'Contract ID is required to make a new CPCode.  '
            'To get a list of contracts, use "./' +
            os.path.basename(__file__) + ' contracts"', '\n')
        raise SystemExit
    if not gid:
        print(
            'Group ID is required to make a new CPCode.  '
            'To get a list of groups, use "./' + os.path.basename(__file__) +
            ' groups"', '\n')
        raise SystemExit
    if not prd:
        print(
            'Product ID is required to make a new CPCode.  '
            'To get a list of products, use "./' + os.path.basename(__file__) +
            ' products"', '\n')
        raise SystemExit
    if not cpname:
        print('A CPCode Name is required to make a new CPCode', '\n')
        raise SystemExit

    data = '{"productId": "' + prd + '","cpcodeName": "' + cpname + '"}'
    headers = {'Content-Type': 'application/json'}

    gssapi = ''
    if account_key:
        gssapi = '&accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.post(urljoin(
        BASEURL,
        '/papi/v1/cpcodes?contractId=' + cid + '&groupId=' + gid + gssapi),
                          data=(data),
                          headers=headers)

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name,
                  [account_key, cid, gid, prd, cpname])
    success_check(result.status_code, "201", list_dict, verbose)

    if list_dict["cpcodeLink"]:
        string = list_dict["cpcodeLink"]
        paths = string.split('?')
        subpaths = paths[0].split('/')
        print("Your new CPCode is: " + subpaths[4].replace("cpc_", ""))
        papi_status(string, inspect.currentframe().f_code.co_name, verbose)
示例#27
0
    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))  
示例#29
0
文件: iscbrf.py 项目: loofjj/bonk
 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')
示例#30
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
示例#31
0
def papi_status(path, stype, verbose):
    """ Not doing any checks because you should call this directly.  There is no value. """

    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(urljoin(BASEURL, path))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [path, stype])
    success_check(result.status_code, "200", list_dict, verbose)

    if stype == "papi_activate":
        list_parse(list_dict["activations"]["items"], verbose)
    elif stype == "papi_newconfig":
        list_parse(list_dict["versions"]["items"], verbose)
    elif stype == "papi_newcpcode":
        list_parse(list_dict["cpcodes"]["items"], verbose)
示例#32
0
def papi_contracts(account_key, verbose):
    """ Getting a list of contracts """

    gssapi = ''
    if account_key:
        gssapi = '?accountSwitchKey=' + account_key
    session = requests.Session()
    session.auth = EdgeGridAuth.from_edgerc(EDGERC, SECTION)
    result = session.get(urljoin(BASEURL, '/papi/v1/contracts' + gssapi))

    # Get result of dictionaries and put them into a list
    list_dict = result.json()

    verbose_check(verbose, list_dict,
                  inspect.currentframe().f_code.co_name, [account_key])
    success_check(result.status_code, "200", list_dict, verbose)

    print('accountId:', list_dict["accountId"])
    print('Contracts:')
    list_parse(list_dict["contracts"]["items"], verbose)
    print('\n')
示例#33
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)
示例#34
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!')
示例#35
0
文件: common.py 项目: akamai/cli-eaa
    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 test_edgerc_dashes(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'dashes')
     self.assertEqual(auth.max_body, 128*1024)
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

httpCaller = EdgeGridHttpCaller(session, debug,verbose, baseurl)
 def test_edgerc_broken(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'broken')
     self.assertEqual(auth.client_secret, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=')
     self.assertEqual(auth.access_token, 'xxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx')
     self.assertEqual(auth.max_body, 128*1024)
     self.assertEqual(auth.headers_to_sign, [])
 def test_edgerc_unparseable(self):
     try:
         auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'edgerc_that_doesnt_parse'))
         self.fail("should have thrown an exception")
     except:
         pass
 def test_edgerc_headers(self):
     auth = EdgeGridAuth.from_edgerc(os.path.join(mydir, 'sample_edgerc'), 'headers')
     self.assertEqual(auth.headers_to_sign, ['x-mything1', 'x-mything2'])