· 9 years ago · Nov 03, 2016, 03:58 AM
1# coding=utf-8
2import os
3import re
4import sys
5import time
6import json
7import base64
8import hashlib
9import hmac
10import logging
11import requests
12import datetime
13from urllib import quote
14
15def sign(key, msg):
16 return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
17
18def getSignatureKey(key, date_stamp, regionName, serviceName):
19 kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
20 kRegion = sign(kDate, regionName)
21 kService = sign(kRegion, serviceName)
22 kSigning = sign(kService, 'aws4_request')
23 return kSigning
24
25def getCanonicalQuerystring(querystring):
26 if(querystring):
27 key_val_pairs = []
28 for pair in querystring.split('&'):
29 key, _, value = pair.partition('=')
30 key_val_pairs.append((key, value))
31 sorted_key_vals = []
32 for key, value in sorted(key_val_pairs):
33 sorted_key_vals.append('%s=%s' % (quote(key), quote(value)))
34 return '&'.join(sorted_key_vals)
35 else:
36 return ''
37
38def get_authorization_header(t, content_type, canonical_uri, request_parameters):
39 algorithm = 'AWS4-HMAC-SHA256'
40 access_key = ''
41 secret_key = ''
42 host = 'cdn.api.ksyun.com'
43 #
44 date_stamp = t.strftime('%Y%m%d')
45 region = 'cn-shanghai-1'
46 service = 'cdn'
47 credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
48 #
49 signed_headers = 'content-type;host;x-amz-date'
50 #
51 amz_date = t.strftime('%Y%m%dT%H%M%SZ')
52 signing_key = getSignatureKey(secret_key, date_stamp, region, service)
53 method = 'POST'
54 temp_canonical_uri = quote(quote(canonical_uri))
55 canonical_querystring = ''
56 canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
57 payload_hash = hashlib.sha256(request_parameters).hexdigest()
58 canonical_request = method + '\n' + temp_canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
59 string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest()
60 signature = signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
61
62t = datetime.datetime.utcnow()
63amz_date = t.strftime('%Y%m%dT%H%M%SZ')
64content_type = 'application/json'
65endpoint = 'http://cdn.api.ksyun.com'
66canonical_uri = '/2016-11-2/distribution/bandwidth'
67request_parameters = {'Urls':[], 'Type': 'bandwidthPeakValue', 'OutType': '2', 'StartTime': None, 'EndTime': None, 'Accetype': 'download'}
68authorization_header = get_authorization_header(t, content_type, canonical_uri, request_parameters)
69
70headers = {'content-type': content_type,
71 'x-amz-date': amz_date,
72 'authorization': authorization_header,
73 'x-action': 'CreateInvalidation',
74 'x-version': '2016-11-2'}
75
76r = requests.post(endpoint+canonical_uri, data=request_parameters, headers=headers)