腾讯轻量云自动开关机脚本

脚本说明:

迫于腾讯轻量云流量超标会扣费,而且不会自动停止,为了防止被反撸,特意写了一个自动停关机脚本,并部署到腾讯云函数。

推送测试图(推送到微信):

图片[1]-腾讯轻量云自动开关机脚本 – MJJ工作室-MJJ工作室

# -*- coding: utf8 -*-

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
import requests
import os

# 参数列表,详细内容请参照README
SecretId = os.environ.get("SecretId")
SecretKey = os.environ.get("SecretKey")
push_result = os.environ.get("push_result")
push_url = os.environ.get("push_url")
traffic_used = os.environ.get("traffic_used")
region = os.environ.get("region")
endpoint = os.environ.get("endpoint")


def main_handler():
    global SecretKey, SecretId, push_url, push_url, traffic_used, region, endpoint
    try:
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = endpoint

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

        req = models.DescribeInstancesTrafficPackagesRequest()

        # 默认监控某个地区所有实例(若只要监控某个单独实例,请在params内填入实例id,打开实例详细信息,网址最后就是实例id)
        """
        params = {
                    "InstanceIds": [InstanceId]
                }
        """
        params = {

        }
        req.from_json_string(json.dumps(params))

        resp = client.DescribeInstancesTrafficPackages(req)

        for i in json.loads(resp.to_json_string())['InstanceTrafficPackageSet']:
            if i['TrafficPackageSet'][0]['TrafficUsed'] / i['TrafficPackageSet'][0]['TrafficPackageTotal'] >= traffic_used:
                txt = "警告!流量已经快用尽!" + '\n' + "实例名称:" + i['InstanceId'] + '\n' + "已用流量:" + str(int(i['TrafficPackageSet'][0]['TrafficUsed'] / 1000000000)) + " GB" + "\n" + "总流量:" + str(int(i['TrafficPackageSet'][0]['TrafficPackageTotal'] / 1000000000)) + " GB" + "\n" + "截止日期:" + i['TrafficPackageSet'][0]['EndTime'].replace("T", "  ").replace("Z", "")
                # 推送通知
                # print(txt)
                # 关机程序
                InstanceId = i["InstanceId"]
                req = models.StopInstancesRequest()
                params = {
                    "InstanceIds": [InstanceId]
                }
                req.from_json_string(json.dumps(params))
                client.StopInstances(req)
                if push_result == 1:
                    requests.get(push_url + txt + '\n' + "流量到达上限已关机")
                else:
                    pass
                return "流量到达上限已关机"
            # 默认流量充足自动开机,并推送结果
            else:
                InstanceId = i["InstanceId"]
                req = models.StartInstancesRequest()
                params = {
                    "InstanceIds": [InstanceId]
                }
                req.from_json_string(json.dumps(params))
                client.StartInstances(req)
                txt = "实例" + InstanceId + "已自动开机" + '\n' + "实例名称:" + i['InstanceId'] + '\n' + "已用流量:" + str(int(i['TrafficPackageSet'][0]['TrafficUsed'] / 1000000000)) + " GB" + "\n" + "总流量:" + str(int(i['TrafficPackageSet'][0]['TrafficPackageTotal'] / 1000000000)) + " GB" + "\n" + "截止日期:" + i['TrafficPackageSet'][0]['EndTime'].replace("T", "  ").replace("Z", "")
                # print(txt)
                if push_result == 1:
                    requests.get(push_url + txt)
                else:
                    pass
                return "实例已开机"
    except TencentCloudSDKException as err:
        return err
使用说明

第一步: 登陆腾讯云账号,打开云函数, 选择新建云函数,Web 静态页面托管 + python,区域选择香港(务必选择香港,否则tg可能无法推送),然后自己设置好名字,等待初始化

图片[2]-腾讯轻量云自动开关机脚本 – MJJ工作室-MJJ工作室

第二步:设置定时参数和环境变量,打开云函数,选择触发管理,创建触发器, 选择半小时一次就行

打开函数管理 ——函数配置,执行超时时间设置为900(最大),然后环境变量自行设置

# api秘钥
 # 获得链接 https://console.cloud.tencent.com/cam/capi
 SecretId    **********
 SecretKey   **********
 # 是否推送,0不推送,1每次开机停机推送
 push_result   **********
 # 推送链接,支持tg和微信(详细请查看附加说明)
 push_url              **********
 # 流量使用额度,高于这个值自动关机,低于这个值自动开机,建议值0.95
 traffic_used            ****
 # 选择地区(香港为ap_hongkong)
 region         **********
 # endpoint,默认为轻量云服务器api地址:lighthouse.tencentcloudapi.com
 endpoint        **********
图片[3]-腾讯轻量云自动开关机脚本 – MJJ工作室-MJJ工作室

第三步:上传代码,打开函数管理——函数代码,直接复制代码替换index.py的代码,

这里腾讯有个bug,需要重新安装tencentcloud-sdk-python,安装到本地目录

代码区域下方,点击打开终端,

cd src
pip install tencentcloud-sdk-python -t .

然后点击部署,等待部署后,选择测试

查看底部运行结果:

 # 若运行成功则返回以下结果
 ​
 "出现错误,错误代码: [TencentCloudSDKException] code:UnsupportedOperation.InvalidInstanceState message:实例 `lhins-np1prqx4` 处于 `RUNNING` 状态中,不支持该操作。 requestId:51299f0d-6df0-49fb-8e32-3b26bf0f461e"

附加说明:

作为一名合格的mjj,必须要有一个属于自己的推送方式,很有用(个人推荐TG机器人,很方便,当然你要是不用tg,可以尝试试试微信推送。

  1. 微信推送链接获得,请参考该项目https://github.com/w2r/cfworker_WeCom,自行在网页端注册企业微信,并开通微信插件,然后用微信关注微信插件,就可以在微信上获得通知了(不用安装企业微信)
  2. TG推送链接获得方式如下:第一步:Telegram上关注botfather,申请一个bot(机器人)。关注之后发送/newbot创建新bot,起个好听的名字,之后会让你再起个username,最后你会得到bot api(类似981790366:AAHPBpLzVZXzvRiAV4jx7HHJ3Z*********0SI),然后记得关注这个机器人,给它发个信息  第二步:浏览器打开链接(https://api.telegram.org/bot981790366:AAHPBpLzVZXzvRiAV4jx7HHJ3Z*********0SI/getUpdates),其中bot api需要换成第一步获得的bot api,然后在网页寻找你的id,类似于561661***, 第三步:测试是否收到短信,把前面获得的bot api和id替换到下方链接中,格式一定要和链接中格式一样的  https://api.telegram.org/bot703106170:AAE2RJ57xjVsX6mRVqJiqZk_wil*******tg/sendMessage?chat_id=56166******&text=1234 第四部:浏览器输入上面链接,这时tg机器人会收到“1234”内容,若不出现内容,大概率是api和id不对

© 版权声明
THE END
喜欢就支持以下吧
点赞9 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容