Skip to content

Instantly share code, notes, and snippets.

@Yxnt
Last active August 1, 2018 02:28
Show Gist options
  • Save Yxnt/493c99b270b4cccf162a5f3735577c10 to your computer and use it in GitHub Desktop.
Save Yxnt/493c99b270b4cccf162a5f3735577c10 to your computer and use it in GitHub Desktop.
Aliyun Signature Python
import base64
import hmac
import time
from hashlib import sha1
from urllib.parse import quote
import random
class Sign(object):
FORMAT_ISO_8601 = "%Y-%m-%dT%H:%M:%SZ"
def __init__(self, ak: str, secret: str, params: dict, method: str, region: str = "cn-hangzhou"):
'''
:param ak: Access id
:param secret: Access secret
:param params: request params
:param method: http method
:param region: aliyun region https://help.aliyun.com/document_detail/40654.html
'''
self._ak = ak
self._secret = "{secret}&".format(secret=secret)
self._method = method
self.params = {
"Format": "JSON",
"Version": "2014-05-26", # replace
"AccessKeyId": self._ak,
"SignatureMethod": "HMAC-SHA1",
"Timestamp": self.__get_iso_8061_date(),
"SignatureVersion": "1.0",
"SignatureNonce": random.random(),
"RegionId": region
}
self.params.update(params)
self.__sign()
def __get_iso_8061_date(self):
# from Aliyun Core Sdk utils parameter_helper.py
return time.strftime(self.FORMAT_ISO_8601, time.gmtime())
@staticmethod
def __percent_encode(string):
# from Aliyun Core Sdk utils parameter_helper.py
res = quote(string.encode('utf8'), '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
def __str_to_sign(self):
'''
https://yq.aliyun.com/articles/79060
https://help.aliyun.com/document_detail/25492.html
:return:
'''
params_s = sorted(self.params.items(), key=lambda x: x[0])
args_list = []
for i in params_s:
key, value = i
if key == "Timestamp":
value = self.__percent_encode(value)
args_list.append("{key}={value}".format(key=key, value=value))
stand_str = "&".join(args_list)
uri_encode = self.__percent_encode("/")
args_encode = self.__percent_encode(stand_str)
url_encode = "{method}&{uri}&{args}".format(method=self._method, uri=uri_encode, args=args_encode)
return url_encode
def __sign(self):
'''
sha1hmac encrypt
:return:
'''
signstr = hmac.new(bytearray(self._secret, 'utf8'), bytearray(self.__str_to_sign(), 'utf8'),
sha1).digest()
signbase64 = base64.b64encode(signstr).decode().strip()
self.params['Signature'] = signbase64
return self.params
import requests
from signature import Sign
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest # import from aliyunsdkecs
if __name__ == '__main__':
   request = DescribeInstancesRequest() # get instance info
   request.set_PageSize(20) # set request query params
   params = {"Action": request.get_action_name()}
params.update(request.get_query_params())
s = Sign(ak="", secret="",
params=params,
method=request.get_method()) # replace ak and secret
print(requests.get("https://ecs.aliyuncs.com", params=s.params).json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment