上一次我们学到了如何批量创建密钥 这次我们来进行批量绑定密钥 上集回顾:利用Python调用云Api实现多地域同步创建轻量应用服务器密钥并保存到本地
0.准备工作
使用本代码请先进行子用户创建并授权云API与轻量应用服务器全部权限
请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限
前往创建子用户:https://console.cloud.tencent.com/cam
1.SDK下载
请确保Python版本为3.6
查看Python版本
代码语言:javascript复制python3 -V
安装腾讯云Python SDK
代码语言:javascript复制pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
2.代码部分
代码语言: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
keyname = input('keyname=')
for i in range(12):
client = lighthouse_client.LighthouseClient(cred, aria[i], clientProfile)
# 获取密钥id
try:
req0 = models.DescribeKeyPairsRequest()
params0 = {
"Filters": [
{
"Name": "key-name",
"Values": [keyname]
}
]
}
req0.from_json_string(json.dumps(params0))
resp0 = client.DescribeKeyPairs(req0)
response0 = json.loads(resp0.to_json_string())
# print(response0)
keyid = response0['KeyPairSet'][0]['KeyId']
print('获取密钥ID成功:' keyid,'该密钥所属地域:' aria[i],'--------------------------------',sep='n')
except TencentCloudSDKException as err:
print(err)
# 获取实例信息
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']
login = ii1['LoginSettings']['KeyIds']
if len(login) == 0:
login_staus = '否'
else:
login_staus = '是'
# 查看流量包
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) '%)',
'该实例是否绑定密钥:' login_staus,
'请求发送时间:' strftime('%Y-%m-%d %H:%M:%S', localtime()),
'--------------------------------',
sep='n')
# 绑定密钥
associate_key = input('输入y绑定密钥(其他则不绑定):')
if associate_key == 'y':
try:
req2 = models.AssociateInstancesKeyPairsRequest()
params2 = {
"KeyIds": [keyid],
"InstanceIds": [id]
}
req2.from_json_string(json.dumps(params2))
resp2 = client.AssociateInstancesKeyPairs(req2)
response2 = json.loads(resp2.to_json_string())
print('绑定成功!')
except TencentCloudSDKException as err:
print(err)
else:
continue
except TencentCloudSDKException as err:
print(err)
end = time()
print('本次代码执行共耗时:', round(end - start, 2), 's')