Featured image of post 腾讯云轻量应用服务器根据流量包使用情况自动开关机

腾讯云轻量应用服务器根据流量包使用情况自动开关机

前言

腾讯云 API 平台 - 产品 API 文档/错误码 (tencent.com)

因为腾讯云的轻量应用服务器的流量包用完之后便是按量付费,一晚流量一套房,不是说说而已,于是便根据腾讯云的官方文档写了一个根据流量包使用情况自动开关轻量应用服务器的脚本,加入定时任务中即可。

环境配置

Tencent Cloud API 3.0 SDK for Python (github.com)

1
pip install --upgrade tencentcloud-sdk-python

实现代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import json
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

# 具有清凉应用服务器权限的角色的身份验证信息
SecretId = 'SecretId'
SecretKey = 'SecretKey'
# 准备进行管理的实例信息,可以同时对同一区域下的多个实例进行管理
Region = 'Region'
InstanceIds = ['InstanceId1', 'InstanceId2']
# 剩余流量阈值,单位GB
TrafficThreshold = 50


def lighthouseCommond(commond, instance):
    try:
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "lighthouse.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = lighthouse_client.LighthouseClient(cred, Region, clientProfile)

        if commond == 'start':
            req = models.StartInstancesRequest()
        elif commond == 'stop':
            req = models.StopInstancesRequest()
        elif commond == 'traffic':
            req = models.DescribeInstancesTrafficPackagesRequest()

        params = {
            "InstanceIds": [instance]
        }
        req.from_json_string(json.dumps(params))

        if commond == 'start':
            resp = client.StartInstances(req)
        elif commond == 'stop':
            resp = client.StopInstances(req)
        elif commond == 'traffic':
            resp = client.DescribeInstancesTrafficPackages(req)

        resp = json.loads(resp.to_json_string())
        return resp

    except TencentCloudSDKException as err:
        if 'UnsupportedOperation' not in str(err):
            print(err)

def getTrafficPackageRemaining(instance):
    traffic = lighthouseCommond('traffic', instance)
    traffic = dict(traffic["InstanceTrafficPackageSet"][0])
    traffic = dict(traffic["TrafficPackageSet"][0])
    # 单位为B
    traffic = traffic["TrafficPackageRemaining"]
    # 单位为B->KB->MB->GB
    traffic = traffic // (1024 ** 3)
    return traffic

def autoStopInstanceByTraffic(InstanceIds):
    for instance in InstanceIds:
        traffic = getTrafficPackageRemaining(instance)
        if traffic <= TrafficThreshold:
            lighthouseCommond('stop', instance)
            print("实例【{}】自动关闭,剩余流量仅有【{}】GB".format(instance, traffic))
        else:
            lighthouseCommond('start', instance)
            print("实例【{}】正常运行,剩余流量仍有【{}】GB".format(instance, traffic))

if __name__ == '__main__':
    autoStopInstanceByTraffic(InstanceIds)
  • SecretIdSecretKey:腾讯云 -> 访问管理 -> 新建用户 获取

访问方式:编程访问

用户权限:仅选择QcloudLighthouseFullAccess

  • Region:实例的区域,比如北京区域为ap-beijing
  • InstanceIds:实例的id,格式为lhins-xxxxxxxx,可填写同一区域下的多个实例进行批量管理
  • TrafficThreshold:剩余流量包低于此数值时自动关机,当下月流量包更新后,高于此数值时又可自动开机

使用方法

Linux:用crontab创建定时任务即可

Windows:在任务计划程序中添加定时启动的任务即可

comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计