python调用阿里云ECS接口

这里以获取域名api为例:

官方文档地址

公共请求参数如下:

1、构建参数

import uuid

AccessKey=""
access_secret_id=""

params = {
    "AccessKeyId": AccessKey,
    "Action": "DescribeRegions",
    "Format": "json",
    "SignatureMethod": "HMAC-SHA1",
    "SignatureNonce": str(uuid.uuid4()),
    "SignatureVersion": "1.0",
    "Timestamp": utc_time,
    "Version": "2014-05-26",
}

参数含义如下
python调用阿里云ECS接口_第1张图片
其中AccessKey是阿里云账户中AccessKey
python调用阿里云ECS接口_第2张图片
2、获取Timestamp值

时间戳,符合IOS8601标准

import datetime
format_time = "%Y-%m-%dT%H:%M:%SZ"
now_time = datetime.datetime.now()
utc_time = now_time - datetime.timedelta(hours=8)  
# 获取时间戳
utc_time = utc_time.strftime(format_time)

3、构建请求字符串

import urllib.request as urllib2

# 使用urllib对参数进行url编码
def percentEncode(strs):
    res = urllib2.quote(strs.encode('utf8'), '')
    res = res.replace('+', '%20')
    res = res.replace('*', '%2A')
    res = res.replace('%7E', '~')
    return res

canstring = ""
# 对请求参数进行按键排序
sortedD = sorted(params.items(), key=lambda x: x[0])
for k, v in sortedD:
    canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
# 拼接请求字符串
StringToSign = 'GET&%2F&' + percentEncode(canstring[1:])

4、构建签名

import hmac
import base64
from hashlib import sha1
# access_secret_id是AccessKey的密钥,在个人中心查看

hmac_code = hmac.new(access_secret_id.encode(), StringToSign.encode(), sha1).digest()
Signature = base64.b64encode(hmac_code)
# 将签名添加到请求参数中
params['Signature']=Signature.decode()

5、访问:

import requests
url = "https://ecs.aliyuncs.com/"

res = requests.get(url=url, params=params)
print(res.text)

返回值如下:
python调用阿里云ECS接口_第3张图片
6、调用阿里云区域可用镜像api
阿里云获取区域可用镜像api
python调用阿里云ECS接口_第4张图片

# 需要把参数中的action换成DescribeImages
# 添加额外参数RegionId(以cn-hangzhou为例)
# 其他步骤和获取区域的步骤一样
params = {
    "AccessKeyId": AccessKey,
    "Action": "DescribeImages",
    "Format": "json",
    "SignatureMethod": "HMAC-SHA1",
    "SignatureNonce": str(uuid.uuid4()),
    "SignatureVersion": "1.0",
    "Timestamp": utc_time,
    "Version": "2014-05-26",
    "RegionId": "cn-hangzhou"
}

你可能感兴趣的:(python调用阿里云ECS接口)