腾讯云轻量无忧计划 新老用户同享优惠 低至 15 元 / 月起 终身续费同价 更赠送一年顶级域名, 并享长期续费优惠
活动链接: https://cloud.tencent.com/act/lighthouse
轻量无忧计划
0. 准备工作
使用本代码请先进行子用户创建并授权云 API 与轻量应用服务器全部权限
请注意 为了保障您的账户以及云上资产的安全 请谨慎保管 SecretId 与 SecretKey 并定期更新 删除无用权限
前往创建子用户: https://cloud.tencent.com/act/lighthouse https://console.cloud.tencent.com/cam
所需权限
1.SDK 下载
请确保 Python 版本为 3.6+
查看 Python 版本
python3 -V
安装腾讯云 Python SDK
pip3 install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
2. 代码部分
代码原理: 通过调用云 API 获取轻量实例信息, 并判断流量包使用情况是否达到预设值, 若达到则输出实例信息 (可选: 并对实例进行关机), 避免产生费用
代码大部分含有注释 此代码仅需要修改 SecretId 与 SecretKey
- import JSON
- from time import sleep,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
- while True:
- start = time()
- aria = ['ap-beijing', 'ap-chengdu', 'ap-guangzhou', 'ap-hongkong', 'ap-shanghai', 'ap-singapore', 'na-siliconvalley',
- 'eu-moscow', 'ap-tokyo', 'ap-nanjing']
- # 此处添加 SecretId 与 SecretKey
- cred = credential.Credential("SecretId", "SecretKey")
- httpProfile = HttpProfile()
- httpProfile.endpoint = "lighthouse.tencentcloudapi.com"
- clientProfile = ClientProfile()
- clientProfile.httpProfile = httpProfile
- for i in range(10):
- 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(response1)
- # 实例详细信息
- 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']
- ip = ii1['PublicAddresses'][0]
- 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')
- # 判断实例状态 若开机则关闭 (请根据实际情况考虑是否注释以下代码)
- if state == 'RUNNING':
- # 关闭实例
- try:
- req3 = models.StopInstancesRequest()
- params3 = {
- "InstanceIds": [id]
- }
- req3.from_json_string(JSON.dumps(params3))
- resp3 = client.StopInstances(req3)
- response3 = JSON.loads(resp3.to_json_string())
- print('已对 IP 为:' + ip + ', 实例 id 为:' + id + '进行关机处理','执行时间:'+strftime('%Y-%m-%d %H:%M:%S', localtime()),sep='\n')
- except TencentCloudSDKException as err:
- print(err)
- except TencentCloudSDKException as err:
- print(err)
- print('--------------------------------',
- 'id:' + id,
- '实例状态:' + state,
- 'ip:' + ip,
- '创建时间:' + 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')
- except TencentCloudSDKException as err:
- print(err)
- end = time()
- print('本次代码执行共耗时:', round(end - start, 2), 's')
- # 每分钟执行一次, 可自行修改
- sleep(60)
代码上传到 Linux 服务器可使用 nohup 与 & 命令将代码挂起至后台
nohup python3 <name>.py &
输出内容将保存在当前目录下的'nohup.out'中
可使用 cat 命令进行查看
cat nohup.out
任何问题可在评论区进行留言
代码编写不易 点个赞与关注再走吧~
来源: https://www.qcloud.com/developer/article/1894110