最近更新时间:2024-08-12 10:30:24
python3 签名DEMO如下:
import hmac
import hashlib
import urllib.parse
import requests
import time
# 签名函数,使用HMAC-SHA256算法
def sign(params, secret_key):
# 对参数键进行排序
keys = sorted(params.keys())
# 构建待签名字符串
str_encode = '&'.join(f"{urllib.parse.quote(k)}={urllib.parse.quote(params[k])}" for k in keys)
# 生成HMAC-SHA256签名
h = hmac.new(secret_key.encode(), str_encode.encode(), hashlib.sha256)
return h.hexdigest()
def main():
ak = "Your AK" # 请替换为您的AccessKey
sk = "Your SK" # 请替换为您的SecretKey
service = "iam" # 访问的服务
region = "cn-beijing-6" # 访问的区域
params = {
# 固定参数
"Accesskey": ak,
"Service": service,
"Region": region,
"Action": "ListUsers", # 接口名
"Version": "2015-11-01", # 版本号
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"SignatureVersion": "1.0",
"SignatureMethod": "HMAC-SHA256",
# 接口参数
"Marker": "1",
"MaxItems": "100",
}
signature = sign(params, sk)
request_url = f"http://{service}.api.ksyun.com/?" + "&".join(
f"{k}={v}" for k, v in params.items()) + f"&Signature={signature}"
headers = {
"Accept": "application/json",
"Host": f"{service}.api.ksyun.com",
}
response = requests.get(request_url, headers=headers)
print("Response Status:", response.status_code)
print("Response Body:", response.text)
if __name__ == "__main__":
main()
纯净模式