问题描述
如何导出ECS实例资源列表
解决方案
- 通过调用OpenAPI DescribeInstances来获取实例元数据信息,再根据需求导出至csv格式文件。
示例代码
本文以Python作为示例代码说明
import sys, os, base64, datetime, hashlib, hmac
import requests # pip install requests
import datetime
import json
import csv, codecs
import math
from requests.models import codes
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, method, host, region, endpoint, payload):
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(payload.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
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()
signing_key = getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
headers = {'X-Date': current_date,
'Authorization':authorization_header,
'X-Content-Sha256': payload_hash,
'Content-Type': content_type
}
return headers, canonical_querystring
def writeRows(result, csv_writer):
# 格式化输出,包含实例id、实例名称、实例状态、可用区、实例类型、实例主网卡私网IP、实例主网卡公网IP、计费类型、停机计费类型
for instance in result['Result']['Instances']:
csvList = []
csvList.append(instance['Id'])
csvList.append(instance['InstanceName'])
csvList.append(instance['Status'])
csvList.append(instance['ZoneId'])
csvList.append(instance['InstanceType']['Id'])
csvList.append(instance['NetworkInterfaces'][0]['PrimaryIpAddress'])
csvList.append(instance['NetworkInterfaces'][0]['EipAddress'])
csvList.append(instance['InstanceChargeType'])
csvList.append(instance['StoppedMode'])
csv_writer.writerow(csvList)
def sendRequest(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload):
# 格式化参数顺序
formatted_parameters = formatParameters(apiParameters)
# signatureV4签名
headers,canonical_querystring = sigv4(volc_access_key, volc_secret_key, serviceName, formatted_parameters, method, host, region, endpoint, payload)
request_url = endpoint + '?' + canonical_querystring
if method == 'GET':
r = requests.get(request_url, headers=headers)
elif method == 'POST':
r = requests.post(request_url, data=payload,headers=headers)
else:
print("Wrong HTTP method")
result = json.loads(r.text)
return result
def createCSV(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload, fileName):
# 写入csv文件
# 1. 创建文件对象
f = codecs.open(fileName, 'wb', "gbk")
# 2. 基于文件对象构建csv写入对象
csv_writer = csv.writer(f)
# 3. 构建列表头
csv_writer.writerow(['实例id','实例名称','实例状态','可用区','实例类型','实例主网卡私网IP','实例主网卡公网IP','计费类型','停机计费类型'])
# 查看资源总数
r = sendRequest(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload)
totalCount = r['Result']['TotalCount']
if totalCount > 10 and totalCount <= 100:
pageSize = 100
apiParameters['PageSize'] = str(pageSize)
r = sendRequest(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload)
writeRows(r, csv_writer)
elif totalCount > 100:
pageSize = 100
apiParameters['PageSize'] = str(pageSize)
pageNumber = math.ceil(totalCount / 100) + 1
for index in range(1, pageNumber):
apiParameters['PageNumber'] = str(index)
r = sendRequest(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload)
writeRows(r, csv_writer)
else:
r = sendRequest(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload)
writeRows(r, csv_writer)
f.close()
if __name__=="__main__":
# 用户AKSK
volc_access_key = os.environ['VOLC_ACCESS_KEY']
volc_secret_key = os.environ['VOLC_SECRET_KEY']
region = os.environ['VOLC_REGION']
# 发送OpenAPI必要的参数
method = 'GET'
host = 'open.volcengineapi.com'
endpoint = 'https://open.volcengineapi.com'
serviceName = 'ecs'
#获取
apiParameters = {
'Action': 'DescribeInstances',
'Version': '2020-04-01'
}
payload = ''
fileName = 'describeInstances.csv'
createCSV(volc_access_key, volc_secret_key, serviceName, apiParameters, method, host, region, endpoint, payload, fileName)
执行方法
- 在执行代码之前,先执行下列命令,下载requests包
pip3 install requests
- Bash命令行(Linux和MacOS操作系统)中执行以下命令,设置执行参数VOLC_REGION为实例所在的地域,目前可使用cn-beijing或cn-nantong
export VOLC_ACCESS_KEY=AKLTZDA1NzI1YTg0NzFiNGU2MWIzZTNiZTBxxxxxx
export VOLC_SECRET_KEY=Wm1ObE5EaGhNak0xT0Raa05ESTFOV0U1T1daaU9EZGhNRGczxxxxxx
export VOLC_REGION=cn-beijing
Windows操作系统可在PowerShell中执行以下命令,设置执行参数VOLC_REGION为实例所在的地域,目前可使用cn-beijing或cn-nantong
$env:VOLC_SECRET_KEY="Wm1ObE5EaGhNak0xT0Raa05ESTFOV0U1T1daaU9EZGhNRGczTTJWa0xxxxxx"
$env:VOLC_ACCESS_KEY="AKLTZDA1NzI1YTg0NzFiNGU2MWIzZTNiZTBlZTQ2xxxxxx"
$env:VOLC_REGION="cn-beijing"
- 在python3.6及以上版本环境下执行下列命令,如需下载python环境,下载地址可参考:python
python3 fileName.py #请确保执行此命令时,该路径下有目标Python文件
执行结果
在当前工作目录生成csv格式的表格,可直接用Office Excel打开阅览。 文件头信息如下: