Created
October 12, 2012 01:12
-
-
Save bigkraig/3876785 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/ usr/bin/env python | |
# By: Kelcey Damage, 2012 & Kraig Amador, 2012 | |
api_url = 'your_stuff_here' | |
apiKey = 'your_stuff_here' | |
secret = 'your_stuff_here' | |
import hashlib, hmac, string, base64, urllib | |
import json, urllib | |
class SignedAPICall(object): | |
def __init__(self, api_url, apiKey, secret): | |
self.api_url = api_url | |
self.apiKey = apiKey | |
self.secret = secret | |
def request(self, args): | |
args['apiKey'] = self.apiKey | |
self.params = [] | |
self._sort_request(args) | |
self._create_signature() | |
self._build_post_request() | |
def _sort_request(self, args): | |
keys = sorted(args.keys()) | |
for key in keys: | |
self.params.append(key + '=' + urllib.quote_plus(args[key])) | |
def _create_signature(self): | |
self.query = '&'.join(self.params) | |
digest = hmac.new( | |
self.secret, | |
msg=self.query.lower(), | |
digestmod=hashlib.sha1).digest() | |
self.signature = base64.b64encode(digest) | |
def _build_post_request(self): | |
self.query += '&signature=' + urllib.quote_plus(self.signature) | |
self.value = self.api_url + '?' + self.query | |
class CloudStack(SignedAPICall): | |
def __getattr__(self, name): | |
def handlerFunction(*args, **kwargs): | |
if kwargs: | |
return self._make_request(name, kwargs) | |
return self._make_request(name, args[0]) | |
return handlerFunction | |
def _http_get(self, url): | |
response = urllib.urlopen(url) | |
return response.read() | |
def _make_request(self, command, args): | |
args['response'] = 'json' | |
args['command'] = command | |
self.request(args) | |
data = self._http_get(self.value) | |
# The response is of the format {commandresponse: actual-data} | |
key = command.lower() + "response" | |
return json.loads(data)[key] | |
api = CloudStack(api_url, apiKey, secret) | |
request = {'listall': 'true'} | |
result = api.listVirtualMachines(request) | |
print "count", result['count'] | |
print "api url", api.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment