Exemplo n.º 1
0
    def __init__(self):
        self.session = requests.Session()
        self.debug = False
        self.verbose = False
        self.section_name = "papi"

        # If all parameters are set already, use them.  Otherwise
        # use the config
        self.config = EdgeGridConfig({}, self.section_name)

        if hasattr(self.config, "debug") and self.config.debug:
            self.debug = True

        if hasattr(self.config, "verbose") and self.config.verbose:
            self.verbose = True

        # Set the config options
        self.session.auth = EdgeGridAuth(
            client_token=self.config.client_token,
            client_secret=self.config.client_secret,
            access_token=self.config.access_token)

        if hasattr(self.config, 'headers'):
            self.session.headers.update(self.config.headers)

        self.baseurl = '%s://%s/' % ('https', self.config.host)
        self.httpCaller = EdgeGridHttpCaller(self.session, self.debug,
                                             self.verbose, self.baseurl)
Exemplo n.º 2
0
def lambda_handler(event, context):
    invalidation_items = event['invalidation_items']
    if event['source'] == "Akamai":
        import requests, json
        from http_calls import EdgeGridHttpCaller
        from akamai.edgegrid import EdgeGridAuth
        creds = event['credentials']

        session = requests.Session()
        debug = False
        verbose = False
        section_name = "default"

        # Set the config options
        session.auth = EdgeGridAuth(client_token=creds['client_token'],
                                    client_secret=creds['client_secret'],
                                    access_token=creds['access_token'])

        baseurl = '%s://%s/' % ('https', creds['host'])
        httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

        purge_obj = {
            "objects": invalidation_items,
            "hostname": "",
            "action": "remove",
            "type": "arl",
            "domain": "production"
        }
        purge_post_result = httpCaller.postResult('/ccu/v3/invalidate/url',
                                                  json.dumps(purge_obj))
        return {"success": True, "message": purge_post_result}

    else:
        if "distribution_id" in event and "credentials" in event:
            distribution_id = event['distribution_id']
            quantity = event['quantity']

            creds = event['credentials']

            if distribution_id:
                client = boto3.client(
                    'cloudfront',
                    aws_access_key_id=creds["aws_access_key_id"],
                    aws_secret_access_key=creds['aws_secret_access_key'])
                invalidation = client.create_invalidation(
                    DistributionId=distribution_id,
                    InvalidationBatch={
                        'Paths': {
                            'Quantity': quantity,
                            'Items': invalidation_items
                        },
                        'CallerReference': str(time.time())
                    })
        return {"success": True, "message": invalidation}
def create_caller():
    # Set the config options
    session.auth = EdgeGridAuth(
        client_token=os.environ['ETP_CLIENT_TOKEN'].strip(),
        client_secret=os.environ['ETP_CLIENT_SECRET'].strip(),
        access_token=os.environ['ETP_ACCESS_TOKEN'].strip())

    baseurl = '%s://%s/' % ('https', args.server.strip())
    httpCaller = EdgeGridHttpCaller(session, baseurl, args.debug)
    return httpCaller
Exemplo n.º 4
0
    def __init__(self, logLevel=logging.INFO):

        ## initialize logging as well
        FORMAT = '%(asctime)-15s %(message)s'
        logging.basicConfig(format=FORMAT)
        # logging.basicConfig()
        self.logger = logging.getLogger('gtm_audit')
        self.logger.setLevel(logLevel)
        ## completed log initialization

        self.session = requests.Session()
        self.debug = False
        self.verbose = False
        self.section_name = "papi"

        # If all parameters are set already, use them.  Otherwise
        # use the config
        self.config = EdgeGridConfig({}, self.section_name)

        if hasattr(self.config, "debug") and self.config.debug:
            self.debug = True

        if hasattr(self.config, "verbose") and self.config.verbose:
            self.verbose = True

        # Set the config options
        self.session.auth = EdgeGridAuth(
            client_token=self.config.client_token,
            client_secret=self.config.client_secret,
            access_token=self.config.access_token)

        if hasattr(self.config, 'headers'):
            self.session.headers.update(self.config.headers)

        self.baseurl = '%s://%s/' % ('https', self.config.host)
        self.httpCaller = EdgeGridHttpCaller(self.session, self.debug,
                                             self.verbose, self.baseurl)
if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token,
                            max_body=131072)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # This section demonstrates how to parse the output for categories
    # First, let's get a list of the categories available for case management
    categories_result = httpCaller.getResult("/case-management/v2/categories")
    # This will return several different categories_result
    for category in categories_result:
        if category["categoryType"] == "Technical":
            print "Information about the Technical category:"
            print json.dumps(category, indent=2)

    subcategories_result = httpCaller.getResult(
        "/case-management/v2/categories/%s/sub-categories" % "Technical")
    # This is where you get the subCategoryType that you actually want to use for your calls
    mainType = subcategories_result["subCategory"]["subCategoryType"]
Exemplo n.º 6
0
config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # Get the list of cloudlets to pick the one we want to use

    endpoint_result = httpCaller.getResult("/cloudlets/api/v2/cloudlet-info")

    # Result for edge redirector:
    # {
    #    "location": "/cloudlets/api/v2/cloudlet-info/2",
    #    "cloudletId": 2,
    #    "cloudletCode": "SA",
    #    "apiVersion": "2.0",
    #    "cloudletName": "SAASACCESS"
    #},
Exemplo n.º 7
0
if hasattr(config, "verbose") and config.verbose:
  verbose = True


# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

if hasattr(config, 'headers'):
  session.headers.update(config.headers)

baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug,verbose, baseurl)

# Request locations that support the diagnostic-tools
print
print ("Requesting locations that support the diagnostic-tools API.\n")

location_result = httpCaller.getResult('/diagnostic-tools/v1/locations')

# Select a random location to host our request
location_count = len(location_result['locations'])

print("There are {} locations that can run dig in the Akamai Network".format(location_count))
rand_location = randint(0, location_count-1)
location = location_result['locations'][rand_location]
print ("We will make our call from " + location + "\n")
# 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)

# Request a list of locations that support the diagnostic-tools
print "Requesting locations that support the diagnostic-tools API.\n"
location_result = httpCaller.getResult(
    '/diagnostic-tools/v2/ghost-locations/available')
location_count = len(location_result['locations'])
print "Testing from {} Akamai Network locations".format(location_count)

results = {}
results['Unknown'] = 0
newCurl = {}
newCurl['url'] = args.url

attempts = 0
retries = 0
Exemplo n.º 9
0
verbose = False
section_name = "default"

config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

# Set options
targetProperty = "sa2017api_bangalore_47.edgesuite.net"
newOrigin = "neworigin.domain.tld"

# List Groups
groupsResult = httpCaller.getResult("/papi/v0/groups/")

for each in groupsResult['groups']['items']:
    try:
        # For each group
        requestParams = {
            "groupId": each['groupId'],
            "contractId": each['contractIds'][0]
        }
Exemplo n.º 10
0
section_name = "default"
targetPropertyId = False

config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

#Set Name of target property
targetProperty = "sa2017api_bangalore_47.edgesuite.net"

# ===============================================================================
# Our first API Call
# We need to know what groups exist in the account
# Reference: https://developer.akamai.com/api/luna/papi/resources.html#listgroups
# ===============================================================================

groupsResult = httpCaller.getResult("/papi/v0/groups/")

# DEBUG
# print groupsResult
# quit()
Exemplo n.º 11
0
	verbose = False

# Set the EdgeGrid credentials
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# If include any special headers (used for debugging)
if hasattr(config, 'headers'):
  session.headers.update(config.headers)

# Set up the base URL
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

# main code
if __name__ == "__main__":
	# Request the entitlement scope for the credentials
	credential_scope = httpCaller.getResult('/-/client-api/active-grants/implicit')

	if verbose: print json.dumps(credential_scope, indent=2)

	print "Credential Name: %s" % credential_scope['name']
	print "---"
	print "Created: %s by %s" % (credential_scope['created'], credential_scope['createdBy'])
	print "Updated: %s by %s" % (credential_scope['updated'], credential_scope['updatedBy'])
	print "Activated: %s by %s" % (credential_scope['activated'], credential_scope['activatedBy'])
	print "---"
Exemplo n.º 12
0
from urlparse import urljoin
import urllib
session = requests.Session()
debug = False
verbose = False
section_name = "mediareports"

config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":

    endpoint = "/media-reports/v1/download-delivery/metrics"
    # First, get the existing property
    property_object = httpCaller.getResult(endpoint)
    print json.dumps(property_object, indent=2)
Exemplo n.º 13
0
config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # If you're just doing a simple GET the call is very simple
    # endpoint_result = httpCaller.getResult("ENDPOINT")
    # result_value = endpoint_result["VARIABLE")

    # Add parameters
    request_parameters = {"value1": "foo", "value2": "bar"}
    endpoint_result = httpCaller.getResult("ENDPOINT", request_parameters)
    # result_value = endpoint_result["VARIABLE")

    # POST example
    #     	sample_obj = { "roleAssignments": [ { "roleId": 14, "groupId": 41241 } ],
    #		"firstName": "Kirsten",
    #		"phone": "8315887563",
Exemplo n.º 14
0
config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # Get the list of cloudlets to pick the one we want to use

    if version == "CREATE":
        new_version_info = {
            "description": "Adding a new version for match rules",
            "matchRuleFormat": "1.0",
            "matchRules": []
        }
        create_path = "/cloudlets/api/v2/policies/%s/versions" % policy
        create_result = httpCaller.postResult(create_path,
                                              json.dumps(new_version_info))

    if version == "CREATE" or version == "LATEST":
Exemplo n.º 15
0
 def __init__(self, config):
     self.http_caller = EdgeGridHttpCaller(config, False, False)
Exemplo n.º 16
0
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True


# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
	# Set these two to the appropriate values for your system
	domainname = "akamaiapibootcamp.com.akadns.net"
	propertyname = "origin"

	endpoint = "/config-gtm/v1/domains/%s/properties/%s" % (domainname, propertyname)
	# First, get the existing property
	property_object = httpCaller.getResult(endpoint)

	# Remove the pieces that aren't settable
	del property_object["links"]
	del property_object["lastModified"]

	# Change the weight for first and second datacenters
Exemplo n.º 17
0
#config = EdgeGridConfig({"verbose":False},section_name)
#baseurl = '%s://%s/' % ('https', config.host)
baseurl = 'https://%s' % edgerc.get(section_name, 'host')

s = requests.Session()
t = requests.Session()
#s.auth = EdgeGridAuth(
#            client_token=config.client_token,
#            client_secret=config.client_secret,
#            access_token=config.access_token
#)

s.auth = EdgeGridAuth.from_edgerc(edgerc, section_name)

httpCaller = EdgeGridHttpCaller(s, debug, verbose, baseurl)

result = httpCaller.getResult(
    urljoin(baseurl, '/diagnostic-tools/v2/ghost-locations/available'))

location_list = []
for item in result['locations']:
    location_list.append(item['id'])

print location_list

print "[*] There are %s places that we could resolve from" % (
    len(location_list))

location = random.choice(location_list)
Exemplo n.º 18
0
if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

if hasattr(config, 'headers'):
    session.headers.update(config.headers)

baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

# Request locations that support the diagnostic-tools
print
print "Requesting locations that support the diagnostic-tools API.\n"

location_result = httpCaller.getResult('/diagnostic-tools/v1/locations')

# Select a random location to host our request
location_count = len(location_result['locations'])

print "There are %s locations that can run dig in the Akamai Network" % location_count
rand_location = randint(0, location_count - 1)
location = location_result['locations'][rand_location]
print "We will make our call from " + location + "\n"
location = "Seoul, South Korea"
Exemplo n.º 19
0
config = EdgeGridConfig({"verbose": debug}, section_name)

if hasattr(config, "debug") and config.debug:
    debug = True

if hasattr(config, "verbose") and config.verbose:
    verbose = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # Set these two to the appropriate values for your system
    domainname = "akamaiapibootcamp.com.akadns.net"
    propertyname = "origin"

    endpoint = "/config-gtm/v1/domains/%s/properties/%s" % (domainname,
                                                            propertyname)
    # First, get the existing property
    property_object = httpCaller.getResult(endpoint)

    # Remove the pieces that aren't settable
    del property_object["links"]
    del property_object["lastModified"]
Exemplo n.º 20
0
class Wrapper:
    """
	A simple wrapper for the PAPI calls. Each call maps to a PAPI URL and no tampering of the results is done within the class.
	"""
    def __init__(self):
        self.session = requests.Session()
        self.debug = False
        self.verbose = False
        self.section_name = "papi"

        # If all parameters are set already, use them.  Otherwise
        # use the config
        self.config = EdgeGridConfig({}, self.section_name)

        if hasattr(self.config, "debug") and self.config.debug:
            self.debug = True

        if hasattr(self.config, "verbose") and self.config.verbose:
            self.verbose = True

        # Set the config options
        self.session.auth = EdgeGridAuth(
            client_token=self.config.client_token,
            client_secret=self.config.client_secret,
            access_token=self.config.access_token)

        if hasattr(self.config, 'headers'):
            self.session.headers.update(self.config.headers)

        self.baseurl = '%s://%s/' % ('https', self.config.host)
        self.httpCaller = EdgeGridHttpCaller(self.session, self.debug,
                                             self.verbose, self.baseurl)

    def getGroups(self):
        """Return the group and contract details based on PAPI credentials.

			Keyword arguments:
				None

			Return type:
				List of groups
		"""
        return self.httpCaller.getResult('/papi/v0/groups/')

    def getContractNames(self):
        """
		Returns the contract id and contract name for a given contract Id

			Keyword arguments:
				None

			Return parameter:
				Hash of contractId and contract name. Same as the output from the raw API call to "/papi/v0/groups/"
		"""
        return self.httpCaller.getResult('/papi/v1/contracts/')

    def getProducts(self, contractId):
        """
		Returns the contract information for the contractId

			Keyword arguments:
				contractId 

			Return parameter:
				Contract details
		"""
        return self.httpCaller.getResult('/papi/v0/products/?contractId=' +
                                         contractId)

    def getCPCodes(self, groupId, contractId):
        """
		Return the CP Code details for a groupId-contractId combination

			Keyword arguments:
				groupId
				contractId
				
			Return parameter:
				List of CP Codes
		"""
        return self.httpCaller.getResult('/papi/v0/cpcodes/?groupId=' +
                                         groupId + '&contractId=' + contractId)

    def getEdgeHostNames(self, groupId, contractId):
        """
		Returns the edgehostnames by groupId. If all groups for an account are passed to this function, it will return all the Edge host names associated with the account.

			Keyword arguments:
				groupId
				contractId

			Return parameter:
				List of edge hostnames
		"""
        return self.httpCaller.getResult('/papi/v0/edgehostnames/?groupId=' +
                                         groupId + '&contractId=' + contractId)

    def getProperties(self, groupId, contractId):
        """
		Returns the names of properties associated with a group. If all groups for an account are passed to this function, it will return all the properties associated with the account.

			Keyword arguments:
				groupId
				contractId

			Return parameter:
				List of properties
		"""
        return self.httpCaller.getResult('/papi/v0/properties/?groupId=' +
                                         groupId + '&contractId=' + contractId)

    def getPropertyVersions(self, propertyId, groupId, contractId):
        """
		Returns the property versions. This can be used to find the audit trail details for a configuration

			Keyword arguments:
				propertId
				groupId
				contractId

			Return parameters:
				List of property versions
		"""
        return self.httpCaller.getResult('/papi/v0/properties/' + propertyId +
                                         '/versions/?groupId=' + groupId +
                                         '&contractId=' + contractId)

    def getavailableBehavior(self, propertyId, propertyVersion, contractId,
                             groupId):
        return self.httpCaller.getResult('/papi/v1/properties/' + propertyId +
                                         '/versions/' + propertyVersion +
                                         '/available-behaviors?contractId=' +
                                         contractId + '&groupId=' + groupId)

    def getVersionDetails(self,
                          propertyId,
                          groupId,
                          contractId,
                          propertyVersion=1):
        """
		Returns information about a specific property version

			Keyword arguments:
				propertyVersion: Default version is 1, the first version.
				propertId
				groupId
				contractId

			Return parameters:
				Details on a specific property version
		"""
        return self.httpCaller.getResult('/papi/v0/properties/' + propertyId +
                                         '/versions/' + propertyVersion +
                                         '?groupId=' + groupId +
                                         '&contractId=' + contractId)

    def getLatestVersionDetails(self, propertyId, groupId, contractId):
        """
		Returns information about a specific property version

			Keyword arguments:
				propertyVersion: Default version is 1, the first version.
				propertId
				groupId
				contractId

			Return parameters:
				Details on a specific property version
		"""
        return self.httpCaller.getResult(
            '/papi/v0/properties/latest/versions/' + propertyVersion +
            '?groupId=' + groupId + '&contractId=' + contractId)

    def getConfigRuleTree(self, propertyId, versionNumber, groupId,
                          contractId):
        """
		Returns all the Property Manager rule details. It will not retrieve advanced code.

			Keyword arguments:
				propertyId
				versionNumber - Specific version for which we need the rules
				groupId
				contractId

			Return parameters:
				Configuration tree rule for a given configuration
		"""
        return self.httpCaller.getResult('/papi/v0/properties/' + propertyId +
                                         '/versions/' + versionNumber +
                                         '/rules/?groupId=' + groupId +
                                         '&contractId=' + contractId)

    def getPropertyHostNames(self, propertyId, versionNumber, groupId,
                             contractId):
        """
		Returns the host names associated with a configuration.

			Keyword arguments:
				propertyId
				versionNumber - Specific version for which we need the rules
				groupId
				contractId

			Return parameters:
				List of host names belonging to the configuration			
		"""
        return self.httpCaller.getResult('/papi/v0/properties/' + propertyId +
                                         '/versions/' + versionNumber +
                                         '/hostnames/?groupId=' + groupId +
                                         '&contractId=' + contractId)

    def getEnrollements(self, contractId):
        """
		Returns the enrollements associated with a contractId.

			Keyword arguments:
				contractId
				
			Return parameters:
				List of enrollments associated with a contractId			
		"""
        return self.httpCaller.getResult('/cps/v2/enrollments?contractId=' +
                                         contractId,
                                         headers='cps')

    def getCNAME(self, hostname):
        """
		Runs a dig command to find the CNAME for a given host name.
		If a CNAME is found, it returns it. Else returns a None.

			Keyword arguments:
				hostname: The host name for which we need the CNAME
		"""

        resp = subprocess.check_output(['dig', '+short', hostname, 'CNAME'])
        if resp is None or len(resp) == 0:
            resp = None
        else:
            resp = resp.decode().strip().strip('.')
        return resp

    def checkIfCdnIP(self, ipaddress):
        """
		Returns if an IP address blongs to Akamai or if it is not an Akamai IP. It uses the OS command "host" on systems
		that supports it. Else, it uses the command nslookup.

			Keyword arguments:
				ipaddress

			Return parameters:
				A boolean flag based on whether the call returns a true or a false.
		"""
        result = False
        # don't use the Akamai service. It is impossibly slow.
        #replaced it with simple reverse lookup
        #resp = self.httpCaller.getResult('/diagnostic-tools/v2/ip-addresses/'+ipaddress+'/is-cdn-ip')
        #if 'isCdnIp' in resp and resp['isCdnIp']==True:
        #	result = True

        try:
            if os.name == "nt":
                resp = str(subprocess.check_output(['nslookup', ipaddress]))
                if resp.find('akamai'):
                    result = True
            else:
                resp = str(subprocess.check_output(['host', ipaddress]))
                #print (resp)
                resp = resp.split(' ')
                if len(resp) >= 5:
                    if resp[4].find('akamai') > -1:
                        result = True
        except subprocess.CalledProcessError:
            pass
        return result

    def getIpAddress(self, hostname):
        result = "0.0.0.0"
        try:
            result = socket.gethostbyname(hostname)
        except Exception:
            pass
        return result
debug = False
verbose = False
s.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

if hasattr(config, "debug") and config.debug:
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True

baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(s, debug, verbose, baseurl)

#query_result=s.post(urljoin(baseurl,'%s' % delete_rule_path))
ct_headers = {"content-type": "application/json"}
luna_apitoken_header_source = {"Luna-Token": "images_menswearhouse_com_pm-10816058"}
luna_apitoken_header_dest = {"Luna-Token": "images_menswearhouse_com_pm-10816058", "content-type": "application/json"}
with open("im_policy_list_file", "r") as im_policy_list_file:
  for policy_name_ in im_policy_list_file:
      policy_name = policy_name_.rstrip()
      apiurl = '/imaging/v2/policies/'+policy_name
      print("\n")
      print("getting policy from source:" + policy_name)
      query_result_get=s.get(urljoin(baseurl,'%s' % apiurl ), headers=luna_apitoken_header_source)
      if (query_result_get.status_code == 200):
          add_unsharp_mask = "yes"
          add_perceptualQuality = "no"
Exemplo n.º 22
0
Arquivo: ver.py Projeto: kannakee/ccu
    verbose = True
else:
    verbose = False

# Set the EdgeGrid credentials
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

# If include any special headers (used for debugging)
if hasattr(config, 'headers'):
    session.headers.update(config.headers)

# Set up the base URL
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

# main code
if __name__ == "__main__":
    # Request the entitlement scope for the credentials
    credential_scope = httpCaller.getResult(
        '/-/client-api/active-grants/implicit')

    if verbose: print(json.dumps(credential_scope, indent=2))

    print("Credential Name: %s" % credential_scope['name'])
    print("---")
    print("Created: %s by %s" %
          (credential_scope['created'], credential_scope['createdBy']))
    print("Updated: %s by %s" %
          (credential_scope['updated'], credential_scope['updatedBy']))
Exemplo n.º 23
0
class Cloudlet(object):
    def __init__(self, config):
        self.http_caller = EdgeGridHttpCaller(config, False, False)


    def list_cloudlet_groups(self):
        """
        Returns information about the Cloudlet types associated with the groups you have edit privileges for.

        Parameters
        -----------
            None

        Returns
        -------
            (result) Object with cloudlet types associated with the groups
        """
        endpoint = '/cloudlets/api/v2/group-info'
        result = self.http_caller.getResult(endpoint)
        return (result)


    def list_policies(
            self,
            group_id = None,
            cloudlet_id = None):
        """
        Returns cloudlet policies associated with group_id

        Parameters
        -----------
            group Id,
            cloudlet Id
        Returns
        -------
            (result) Policies of cloudlet Id
        """
        endpoint = '/cloudlets/api/v2/policies'
        result = self.http_caller.getResult(endpoint, {"gid": group_id, "cloudletId": cloudlet_id})
        return (result)


    def get_cloudlet_policy(self, policy_id, version = None):
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id)
        if version:
            endpoint += '/versions/' + version
        
        result = self.http_caller.getResult(endpoint, {})
        return (result)

        # if version == 'optional':
        #     cloudlet_policy_url = 'https://' + self.access_hostname + \
        #                           '/cloudlets/api/v2/policies/' + str(policy_id)
        # else:
        #     cloudlet_policy_url = 'https://' + self.access_hostname + '/cloudlets/api/v2/policies/' + \
        #                           str(policy_id) + '/versions/' + str(version) + '?omitRules=false'
        # cloudlet_policy_response = session.get(cloudlet_policy_url)
        
        return result


    def create_policy_version(
            self,
            policy_id,
            clone_version = None,
            policy_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions'
        result = self.http_caller.postResult(endpoint, policy_data, {'includeRules': 'true', 'cloneVersion': clone_version})
        return (result)


    def update_policy_version(
            self,
            policy_id,
            policy_details,
            version):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/' + str(version) + '?omitRules=false'
        # refactoring not finished
        cloudlet_policy_update_response = session.put(
            cloudlet_policy_update_url, data=policy_details, headers=headers)
        return cloudlet_policy_update_response


    def activate_policy_version(
            self,
            policy_id,
            version,
            network='staging'):
        """
        Function to activate a policy version
        """

        data = """{
            "network" : "%s"
        }""" % network

        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/' + str(version) + '/activations'
        result = self.http_caller.postResult(endpoint, data, {})
        return (result)
        

    def add_rule(
            self,
            policy_id,
            version,
            index = None,
            rule_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/'+ str(version) +'/rules'
        result = self.http_caller.postResult(endpoint, rule_data, {'index': index})
        return (result)

    def modify_rule(
            self,
            policy_id,
            version,
            rule_id,
            # index = None,
            rule_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/'+ str(version) +'/rules/' + str(rule_id)
        result = self.http_caller.putResult(endpoint, rule_data, {})
        return (result)
Exemplo n.º 24
0
    "ccu_paths": "store"
})

if config.debug or config.verbose:
    debug = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

if hasattr(config, 'headers'):
    session.headers.update(config.headers)

baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, baseurl)


def postPurgeRequest(host, paths):
    purge_obj = {"hostname": host, "objects": [p for p in paths]}
    print "Invadating  %s" % json.dumps(purge_obj)
    purge_post_result = httpCaller.postResult('/ccu/v3/invalidate/url',
                                              json.dumps(purge_obj))
    return purge_post_result


if __name__ == "__main__":
    if not config.ccu_host or not config.ccu_paths:
        print "The arguments --ccu_host and --ccu_paths must be specified"
        print "where "
        print "   --ccu_host is the hostname to invalidate and"
Exemplo n.º 25
0
if hasattr(config, "debug") and config.debug:
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True

# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
	# If you're just doing a simple GET the call is very simple
	# endpoint_result = httpCaller.getResult("ENDPOINT")
	# result_value = endpoint_result["VARIABLE")

	# Add parameters
	request_parameters = { "value1":"foo","value2":"bar" }
	endpoint_result = httpCaller.getResult("ENDPOINT",request_parameters)
	# result_value = endpoint_result["VARIABLE")

	# POST example
	#     	sample_obj = { "roleAssignments": [ { "roleId": 14, "groupId": 41241 } ], 
    	#		"firstName": "Kirsten", 
    	#		"phone": "8315887563", 
Exemplo n.º 26
0
from http_calls import EdgeGridHttpCaller
debug = True
verbose = False

section_name = "default"

config = EdgeGridConfig({"verbose": False}, section_name)
baseurl = '%s://%s/' % ('https', config.host)

s = requests.Session()

s.auth = EdgeGridAuth(client_token=config.client_token,
                      client_secret=config.client_secret,
                      access_token=config.access_token)

httpCaller = EdgeGridHttpCaller(s, debug, verbose, baseurl)

#result = httpCaller.getResult('/diagnostic-tools/v2/ghost-locations/available')
#result = s.get(urljoin(baseurl, '/diagnostic-tools/v1/locations'))

result = s.get(urljoin(baseurl, '/diagnostic-tools/v1/locations'))

print result.status_code

location = result.json()['locations'][0]['id']

dig_parameters = {"hostName": "junchen.sandbox.akamaideveloper.com"}

dig_result = httpCaller.getResult(
    "/diagnostic-tools/v2/ghost-locations/%s/dig-info" % location,
    dig_parameters)
if hasattr(config, "debug") and config.debug:
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True

# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
	# Get the list of cloudlets to pick the one we want to use

	endpoint_result = httpCaller.getResult("/cloudlets/api/v2/cloudlet-info")
	
	# Result for edge redirector:
	# {
	#    "location": "/cloudlets/api/v2/cloudlet-info/2", 
	#    "cloudletId": 2, 
	#    "cloudletCode": "SA", 
	#    "apiVersion": "2.0", 
	#    "cloudletName": "SAASACCESS"
	#}, 
Exemplo n.º 28
0
if hasattr(config, "debug") and config.debug:
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True

# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
	# Get the list of cloudlets to pick the one we want to use

	if version == "CREATE":
		new_version_info = {
				"description":"Adding a new version for match rules",
				"matchRuleFormat":"1.0",
				"matchRules": []
		}
		create_path = "/cloudlets/api/v2/policies/%s/versions" % policy
		create_result = httpCaller.postResult(create_path, 
							json.dumps(new_version_info))

	if version == "CREATE" or version == "LATEST":
Exemplo n.º 29
0
if hasattr(config, "cache") and config.cache:
    cache = True

# Set the config options
session.auth = EdgeGridAuth(client_token=config.client_token,
                            client_secret=config.client_secret,
                            access_token=config.access_token)

if hasattr(config, 'headers'):
    session.headers.update(config.headers)

session.headers.update({'User-Agent': "AkamaiCLI"})

baseurl_prd = '%s://%s/' % ('https', config.host)
prdHttpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl_prd)


def listblocklist(accountSwitchKey=None):
    """ List the blocklist in the account """

    listblocklistEndpoint = '/taas/v2/revocation-lists'
    if accountSwitchKey:
        params = {'accountSwitchKey': accountSwitchKey}
        blocklistId = prdHttpCaller.getResult(listblocklistEndpoint, params)
    else:
        blocklistId = prdHttpCaller.getResult(listblocklistEndpoint)
    return (blocklistId)


def listidentifiers(blocklistId, accountSwitchKey=None):
Exemplo n.º 30
0
class GtmWrapper:
    """
	A simple wrapper for the PAPI calls. Each call maps to a PAPI URL and no tampering of the results is done within the class.
	"""
    def __init__(self, logLevel=logging.INFO):

        ## initialize logging as well
        FORMAT = '%(asctime)-15s %(message)s'
        logging.basicConfig(format=FORMAT)
        # logging.basicConfig()
        self.logger = logging.getLogger('gtm_audit')
        self.logger.setLevel(logLevel)
        ## completed log initialization

        self.session = requests.Session()
        self.debug = False
        self.verbose = False
        self.section_name = "papi"

        # If all parameters are set already, use them.  Otherwise
        # use the config
        self.config = EdgeGridConfig({}, self.section_name)

        if hasattr(self.config, "debug") and self.config.debug:
            self.debug = True

        if hasattr(self.config, "verbose") and self.config.verbose:
            self.verbose = True

        # Set the config options
        self.session.auth = EdgeGridAuth(
            client_token=self.config.client_token,
            client_secret=self.config.client_secret,
            access_token=self.config.access_token)

        if hasattr(self.config, 'headers'):
            self.session.headers.update(self.config.headers)

        self.baseurl = '%s://%s/' % ('https', self.config.host)
        self.httpCaller = EdgeGridHttpCaller(self.session, self.debug,
                                             self.verbose, self.baseurl)

    def getDomains(self):
        return self.httpCaller.getResult('/config-gtm/v1/domains/')

    def getSingleDomain(self, domainName):
        return self.httpCaller.getResult('/config-gtm/v1/domains/' +
                                         domainName)

    def getDomainDataCenters(self, domainName):
        self.logger.debug('Fetching data center details using URL: ' +
                          '/config-gtm/v1/domains/' + domainName +
                          '/datacenters')
        return self.httpCaller.getResult('/config-gtm/v1/domains/' +
                                         domainName + '/datacenters')

    def getDomainProperties(self, domainName):
        return self.httpCaller.getResult('/config-gtm/v1/domains/' +
                                         domainName + '/properties')

    def extractDomainName(self, url):
        return url.rsplit('/', 1)[1]

    def getTargetDetails(self, domain):
        result = {}
        result['name'] = domain['name']
        result['trafficTargets'] = []
        for target in domain['trafficTargets']:
            result['trafficTargets'].append({\
              'servers': target['servers'],\
              'handoutCName': target['handoutCName'],\
              'weight': target['weight'],\
              'enabled': target['enabled']
             })
        self.trafficTargets = result
        if 'livenessTests' in domain and len(domain['livenessTests']) >= 1:
            self.livenessTests = domain['livenessTests'][0]
        else:
            self.livenessTests = None

    def getTrafficTargets(self):
        return self.trafficTargets

    def getLivenessTests(self):
        return self.livenessTests
Exemplo n.º 31
0
# 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)

# Request locations that support the diagnostic-tools
print
print ("Requesting locations that support the diagnostic-tools API.\n")

location_result = httpCaller.getResult('/diagnostic-tools/v2/ghost-locations/available')

# Select a random location to host our request
location_count = len(location_result['locations'])

print("There are {} locations that can run dig in the Akamai Network".format(location_count))
rand_location = randint(0, location_count-1)
location = location_result['locations'][rand_location]['id']
print ("We will make our call from " + location + "\n")
Exemplo n.º 32
0
debug = False
verbose = False
section_name = "mediareports"

config = EdgeGridConfig({"verbose":debug},section_name)

if hasattr(config, "debug") and config.debug:
  debug = True

if hasattr(config, "verbose") and config.verbose:
  verbose = True


# Set the config options
session.auth = EdgeGridAuth(
            client_token=config.client_token,
            client_secret=config.client_secret,
            access_token=config.access_token
)

# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":

	endpoint = "/media-reports/v1/download-delivery/metrics"
	# First, get the existing property
	property_object = httpCaller.getResult(endpoint)
	print json.dumps(property_object, indent=2)