利用Python调用云Api监测轻量应用服务器流量使用情况

2022-04-20 10:03:57 浏览数 (1)

0.准备工作

使用本代码请先进行子用户创建并授权云API与轻量应用服务器全部权限

请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

前往创建子用户:https://console.cloud.tencent.com/cam

所需权限所需权限

1.SDK下载

请确保Python版本为3.6

查看Python版本

代码语言:javascript复制
python3 -V

安装腾讯云Python SDK

代码语言:javascript复制
pip3 install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python

2.代码部分

代码原理:通过调用云api获取轻量实例信息,并判断流量包使用情况是否达到预设值,若达到则输出实例信息(可选:并对实例进行关机),避免产生费用

超额流量定价超额流量定价

代码大部分含有注释 此代码仅需要修改SecretId 与 SecretKey

代码语言:javascript复制
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','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(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())
                                    execute_time = strftime('%Y-%m-%d %H:%M:%S', localtime())
                                    
                                    print('已对IP为:'   ip   ',实例id为:'   id   '进行关机处理','执行时间:' execute_time,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与&命令将代码挂起至后台

代码语言:javascript复制
nohup python3 <name>.py &

输出内容将保存在当前目录下的’nohup.out'中

可使用cat命令进行查看

代码语言:javascript复制
cat nohup.out

任何问题可在评论区进行留言

代码编写不易 点个赞与关注再走吧~

0 人点赞