以下是一个用于获取阿里云服务器状态的简单的API编程实例:
import requests
def get_server_status(access_key, secret_key, region, instance_id):
url = f'https://ecs.aliyuncs.com/?Action=DescribeInstanceStatus&AccessKeyId={access_key}&SecretAccessKey={secret_key}&RegionId={region}&InstanceId={instance_id}'
response = requests.get(url)
data = response.json()
if 'InstanceStatuses' in data:
status = data['InstanceStatuses']['InstanceStatus'][0]['Status']
print(f'Server status: {status}')
else:
print('Unable to retrieve server status')
# 替换以下变量为您的实际值
access_key = '您的Access Key'
secret_key = '您的Secret Key'
region = '实例所在地域ID'
instance_id = '实例ID'
get_server_status(access_key, secret_key, region, instance_id)
请确保您已安装了requests
库并替换代码中的access_key
,secret_key
,region
和instance_id
变量为您的实际值。
以下是一个简单的API编程实例,使用阿里云API来创建一个ECS实例。
import requests
import urllib
import hmac
import base64
from hashlib import sha1
# 阿里云API key和secret,需要替换成自己的
access_key = 'your-access-key'
access_secret = 'your-access-secret'
# 构造请求参数
params = {
'AccessKeyId': access_key,
'Format': 'json',
'Version': '2014-05-26',
'SignatureMethod': 'HMAC-SHA1',
'SignatureVersion': '1.0',
}
# 设置请求的Action和具体参数
params['Action'] = 'CreateInstance'
params['RegionId'] = 'cn-hangzhou'
params['InstanceType'] = 'ecs.t5-lc1m2.small'
params['ImageId'] = 'ubuntu_18_04_64_20G_alibase_20200220.vhd'
# 生成签名
sorted_params = sorted(params.items(), key=lambda x: x[0])
canonicalized_query = '&'.join(['%s=%s' % (k, urllib.parse.quote(str(v))) for k, v in sorted_params])
string_to_sign = 'GET&%2F&' + urllib.parse.quote(canonicalized_query, safe='')
hmac_key = access_secret + '&'
sign = hmac.new(hmac_key.encode('utf-8'), string_to_sign.encode('utf-8'), sha1).digest()
signature = base64.b64encode(sign).decode()
# 发起请求
url = 'https://ecs.aliyuncs.com/?' + canonicalized_query + '&Signature=' + urllib.parse.quote(signature)
response = requests.get(url)
# 处理请求结果
result = response.json()
if 'InstanceId' in result:
instance_id = result['InstanceId']
print(f"创建实例成功,实例ID为: {instance_id}")
else:
print(f"创建实例失败: {result['Message']}")
请注意替换access_key
和access_secret
为您自己的阿里云API凭证。此示例中使用的是阿里云ECS API的CreateInstance
操作,具体操作和参数可以根据您的需求进行调整。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/135424.html