0.准备工作
使用本代码请先进行子用户创建并授权云API与轻量应用服务器全部权限
请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限
前往创建子用户:https://console.cloud.tencent.com/cam
1.SDK下载
请确保Python版本为3.6
查看Python版本
代码语言:javascript复制python3 -V
升级一下pip,安装腾讯云Python SDK
代码语言:javascript复制python -m pip install --upgrade pip
pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
2.代码部分
调用的api为:DescribeInstances、DescribeInstancesTraf、ModifyInstancesAttribu
详见https://console.cloud.tencent.com/api/explorer?Product=lighthouse&Version=2020-03-24&Action=DescribeInstances
代码语言:javascript复制import json
from time import strftime, localtime, time
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.lighthouse.v20200324 import lighthouse_client, models
start = time()
aria = ['ap-beijing', 'ap-chengdu', 'ap-guangzhou', 'ap-hongkong', 'ap-shanghai', 'ap-singapore',
'na-siliconvalley',
'eu-moscow', 'ap-tokyo', 'ap-nanjing', 'ap-mumbai', 'eu-frankfurt']
# 此处添加SecretId 与 SecretKey
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "lighthouse.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
for i in range(12):
client = lighthouse_client.LighthouseClient(cred, aria[i], clientProfile)
try:
# 查看所有实例
req = models.DescribeInstancesRequest()
params = {
}
req.from_json_string(json.dumps(params))
resp = client.DescribeInstances(req)
response = json.loads(resp.to_json_string())
# print(response)
# 实例详细信息
basic = response['InstanceSet']
# 判断地域是否含有实例
if response['TotalCount'] > 0:
print(aria[i] '实例数为' str(response['TotalCount']))
# 提取返回的json信息
for ii in range(response['TotalCount']):
ii1 = basic[ii]
id = ii1['InstanceId']
name = ii1['InstanceName']
ip = ii1['PublicAddresses'][0]
zone = ii1['Zone']
ct = ii1['CreatedTime']
et = ii1['ExpiredTime']
os = ii1['OsName']
state = ii1['InstanceState']
# 查看流量包
try:
req1 = models.DescribeInstancesTrafficPackagesRequest()
params1 = {
"InstanceIds": [id]
}
req1.from_json_string(json.dumps(params1))
resp1 = client.DescribeInstancesTrafficPackages(req1)
response1 = json.loads(resp1.to_json_string())
tf = response1['InstanceTrafficPackageSet'][0]['TrafficPackageSet'][0]
# 总流量
tft = str(round(tf['TrafficPackageTotal'] / 1073741824, 2))
# 已用流量
tfu = str(round(tf['TrafficUsed'] / 1073741824, 2))
# 剩余流量
tfr = str(round(tf['TrafficPackageRemaining'] / 1073741824, 2))
# 已用流量%
percent_tfu = round(
round(tf['TrafficUsed'] / 1073741824, 2) / round(tf['TrafficPackageTotal'] / 1073741824,
2) * 100, 3)
# 剩余流量%
percent_tfr = 100 - percent_tfu
# 判断实例已用流量是否达到预设值(1即为1%)
if percent_tfu > 1.000:
print('IP为:' ip '实例Id为: ' id '的流量已达到预设值',
'时间:' strftime('%Y-%m-%d %H:%M:%S', localtime()), sep='n')
except TencentCloudSDKException as err:
print(err)
print('--------------------------------',
'id: ' id,
'实例名称:' name,
'实例状态: ' state,
'ip: ' ip,
'实例大区:' zone,
'创建时间: ' ct,
'到期时间: ' et,
'操作系统: ' os,
'总流量:' tft 'GB',
'已用流量(%): ' tfu 'GB' ' (' str(percent_tfu) '%)',
'剩余流量: ' tfr 'GB' ' (' str(percent_tfr) '%)',
'请求发送时间:' strftime('%Y-%m-%d %H:%M:%S', localtime()),
'--------------------------------',
sep='n')
# 修改实例名称
change_name = input('请输入你想更改的名字(不想更改按回车):')
if change_name == "":
continue
else:
try:
req2 = models.ModifyInstancesAttributeRequest()
params2 = {
"InstanceIds": [id],
"InstanceName": change_name
}
req2.from_json_string(json.dumps(params2))
resp2 = client.ModifyInstancesAttribute(req2)
response2 = json.loads(resp2.to_json_string())
# print(response2)
print('更改成功!')
except TencentCloudSDKException as err:
print(err)
except TencentCloudSDKException as err:
print(err)
end = time()
print('本次代码执行共耗时:', round(end - start, 2), 's')
有问题欢迎在评论区留言
本文章首次发布时间为2022.1.26 20:30
本文章为云 社区首发
未经同意禁止转载
本文将同步发布于csdn 知乎 哔哩哔哩专栏