Python编程:RunInstances接口的使用示例

计算弹性计算技术服务知识库

前提描述:

该文章向大家介绍的是如何利用Python进行编程向RunInstances接口发送GET请求以此来创建实例。

示例代码:

import sys, os, base64, datetime, hashlib, hmac 
import requests # pip install requests
# ************* REQUEST VALUES *************
method = 'GET'
host = 'open.volcengineapi.com'
region = 'cn-beijing'
endpoint = 'https://open.volcengineapi.com'

def sign(key, msg):
     return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(key.encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'request')
    return kSigning

def formatParameters(parameters):
    request_parameters_init = ''
    for key in sorted(parameters):
         request_parameters_init += key + '=' + parameters[key] + '&'
    request_parameters = request_parameters_init[:-1]
    return request_parameters

def sigv4(access_key, secret_key, service, request_parameters):
    if access_key is None or secret_key is None:
         print('No access key is available.')
         sys.exit()

    t = datetime.datetime.utcnow()
    current_date = t.strftime('%Y%m%dT%H%M%SZ')
    # current_date = '20210818T095729Z'
    datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
    canonical_uri = '/' 

    canonical_querystring = request_parameters

    signed_headers = 'content-type;host;x-content-sha256;x-date'
    payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

    content_type = 'application/x-www-form-urlencoded; charset=utf-8'

    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-content-sha256:' + payload_hash + '\n' + 'x-date:' + current_date + '\n'
    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
    print(canonical_request)
    algorithm = 'HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'request'
    string_to_sign = algorithm + '\n' + current_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
    print(string_to_sign)
    signing_key = getSignatureKey(secret_key, datestamp, region, service)
    print(signing_key)
    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
    print(signature)

    authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
    print(authorization_header)
    headers = {'X-Date': current_date, 
            'Authorization':authorization_header,
            'X-Content-Sha256': payload_hash,
            'Content-Type': content_type
            }
    print(headers)

# ************* SEND THE REQUEST *************
    request_url = endpoint + '?' + canonical_querystring

    print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
    print('Request URL = ' + request_url)
    r = requests.get(request_url, headers=headers)

    print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
    print('Response code: %d\n' % r.status_code)
    print(r.text)

if __name__=="__main__":
    access_key = 'Your AK'
    secret_key = 'Your SK'
    service = 'ecs'
    run_instance_parameters = {
        'Action': 'RunInstances',#调用的接口
         'ImageId': '',#镜像ID
         'InstanceName': '',#您创建的实例的名称
         'InstanceType': '',#实例的规格
         'NetworkInterfaces.1.SecurityGroupIds.1': '',#安全组Id
         'NetworkInterfaces.1.SubnetId': '',#;连接的私有网络子网的ID
         'ZoneId': '',#地域ID
         'Password': '',#使用的密码或KeyPairName值
         'ProjectName': '',
         'Version': '2020-04-01',#版本号,这是一个固定值,不能随意修改否则会出现报错
         'Volumes.1.Size': '',#云盘大小
         'Volumes.1.VolumeType': ''#云盘类型
         }

    formatted_parameters = formatParameters(run_instance_parameters)
    sigv4(access_key, secret_key, service, formatted_parameters)

大家可以根据自己的需求,对相应参数的规格等进行适当改变。将此代码保存为后缀为.py类型的文件。

运行结果:

  1. 执行命令python Runisntance.py,执行完成后,回显信息如下:

图片

  1. 登录控制台查看是否创建成功:

图片 如果您有其他问题,欢迎您联系火山引擎技术支持服务

0
0
0
0
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论