コード例 #1
0
                            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
    property_object["trafficTargets"][0]["weight"] = 1
    property_object["trafficTargets"][0]["name"] = "mediatemple"

    property_object["trafficTargets"][1]["weight"] = 1
    property_object["trafficTargets"][1]["name"] = "digitalocean"
    # Add a liveness test
    property_object["livenessTests"] = [{
        "responseString": None,
        "testObject": "/Resume.html",
コード例 #2
0
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()

# ===============================================================================
# The resulting JSON response is now stored in "groupsResult"
# We know the structure from the Developer Portal
# {"groups": { "items": [
# So let's loop through each Luna Group
# ===============================================================================
for each in groupsResult['groups']['items']:
    try:
        # DEBUG
        # print each['groupName'] + " : " + each['groupId'] + " : " + each['contractIds'][0]
コード例 #3
0
            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")

# Request the dig request the {OPEN} Developer Site IP informantion
dig_parameters = { "hostname":"developer.akamai.com", "location":location, "queryType":"A" }
dig_result = httpCaller.getResult("/diagnostic-tools/v1/dig",dig_parameters)

# Display the results from dig
print (dig_result['dig']['result'])
コード例 #4
0
    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"]

    subcats = subcategories_result["subCategory"]["subCategories"]
    for subcategory in subcats:
        displayName = subcategory["displayName"]
        subCategoryType = subcategory["subCategory"]["displayName"]
コード例 #5
0
ファイル: ver.py プロジェクト: kannakee/ccu
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("---")

    for scope in credential_scope['scope'].split(" "):
        o = parse.urlparse(scope)
コード例 #6
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)
コード例 #7
0
# 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",
    #		"lastName": "Hunter",
    #		"email": "*****@*****.**"
    #	}
    # sample_post_result = httpCaller.postResult('/user-admin/v1/users', json.dumps(user_obj))

    print "Waiting for some fabulous code here!"
コード例 #8
0
    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

for num in range(0, location_count):
    #for num in range(0, 4):
    running = True
    region = 'Unknown'
コード例 #9
0
ファイル: gtm-property.py プロジェクト: Didato/api-kickstart
            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
	property_object["trafficTargets"][0]["weight"] = 1
	property_object["trafficTargets"][0]["name"] = "mediatemple"

	property_object["trafficTargets"][1]["weight"] = .5 
	property_object["trafficTargets"][1]["name"] = "digitalocean"
	# Add a liveness test
	property_object["livenessTests"] = [ 
		{
     			  "responseString": None, 
コード例 #10
0
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":
        version_path = "/cloudlets/api/v2/policies/%s/versions" % policy
        version_result = httpCaller.getResult(version_path)
        version = version_result[0]["version"]

    # Now we know which version (and we've set the policy)

    # Open the JSON filename with mappings
    with open(filename) as data_file:
        data = json.load(data_file)

    for rule in data:
        rule_path = "/cloudlets/api/v2/policies/%s/versions/%s/rules" % (
            policy, version)
        rule_result = httpCaller.postResult(rule_path, json.dumps(rule))
        print rule_result

    # Activate the new version if you like
コード例 #11
0
# 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"
# Request the dig request the {OPEN} Developer Site IP informantion
print "Running dig from " + location
dig_parameters = {
    "hostname": "developer.akamai.com",
    "location": location,
    "queryType": "A"
コード例 #12
0
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]
        }

        # List Properties
        propResult = httpCaller.getResult("/papi/v0/properties/",
                                          requestParams)

        for each in propResult['properties']['items']:
            try:
コード例 #13
0
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":
		version_path = "/cloudlets/api/v2/policies/%s/versions" % policy
		version_result = httpCaller.getResult(version_path)
		version = version_result[0]["version"]

	# Now we know which version (and we've set the policy)

	# Open the JSON filename with mappings
	with open(filename) as data_file:
		data = json.load(data_file)

	for rule in data:
		rule_path = "/cloudlets/api/v2/policies/%s/versions/%s/rules" % (policy, version)
		rule_result = httpCaller.postResult(rule_path, json.dumps(rule))
		print rule_result

	# Activate the new version if you like
	activation_path = "/cloudlets/api/v2/policies/%s/versions/%s/activations" % (policy, version)
コード例 #14
0
ファイル: verify_creds.py プロジェクト: Didato/api-kickstart
            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 "---"

	for scope in credential_scope['scope'].split(" "):
		o = urlparse(scope)
		apis = o.path.split("/")
		print '{0:35} {1:10}'.format(apis[3], apis[5])
コード例 #15
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
コード例 #16
0
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", 
    	#		"lastName": "Hunter", 
    	#		"email": "*****@*****.**"
   	#	}
	# sample_post_result = httpCaller.postResult('/user-admin/v1/users', json.dumps(user_obj))

	print "Waiting for some fabulous code here!"
コード例 #17
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
コード例 #18
0
# 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"
	#}, 

	# Get the group ID for the cloudlet we're looking to create
	endpoint_result = httpCaller.getResult("/cloudlets/api/v2/group-info")

	# Result for group info:
 	#	 "groupName": "API Bootcamp", 
コード例 #19
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)

# 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"
    #},

    # Get the group ID for the cloudlet we're looking to create
    endpoint_result = httpCaller.getResult("/cloudlets/api/v2/group-info")

    # Result for group info:
    #	 "groupName": "API Bootcamp",
コード例 #20
0
        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")

# Request the dig request the {OPEN} Developer Site IP information
dig_parameters = { "hostName":"developer.akamai.com"}
dig_result = httpCaller.getResult("/diagnostic-tools/v2/ghost-locations/%s/dig-info" % location,dig_parameters)

# Display the results from dig
print (dig_result['digInfo']['result'])
コード例 #21
0
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)

# Display the results from dig
print(dig_result['digInfo'])

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

print cloudlet_result.json()