阿里云国际版监控流量自动关机

参数说明:

1、账号id

2、账号密钥

3、服务器地区

4、服务器ID

5、剩余流量关机值(单位Bytes)


成品下载地址:

https://webqwe.com/resource/image/article/2024/01/27/39729/aliyun_limit_traffic_go-webqwe.rar

解压密码:webqwe.com


使用方法:

配合linux定时任务使用

//编辑定时任务
crontab  -e
//隔10分钟
*/10 * * * * /root/aliyun_limit_traffic_go-webqwe.com "账号id" "账号密钥" "服务器地区" "服务器ID" "剩余流量关机值(单位Bytes)"

//隔一个小时执行一次
1 */1 * * * /root/aliyun_limit_traffic_go-webqwe.com "账号id" "账号密钥" "服务器地区" "服务器ID" "剩余流量关机值(单位Bytes)"


golang代码:

// This file is auto-generated, don't edit it. Thanks.
package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gogf/gf/v2/util/gconv"
)

/**
 * Initialize the Client with the AccessKey of the account
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *openapi.Client, _err error) {
	config := &openapi.Config{
		// Required, your AccessKey ID
		AccessKeyId: accessKeyId,
		// Required, your AccessKey secret
		AccessKeySecret: accessKeySecret,
	}
	// See https://api.alibabacloud.com/product/SWAS-OPEN.
	config.Endpoint = tea.String("swas.cn-hongkong.aliyuncs.com")
	_result = &openapi.Client{}
	_result, _err = openapi.NewClient(config)
	return _result, _err
}

/**
 * API Info
 * @param path params
 * @return OpenApi.Params
 */
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// API Name
		Action: tea.String("ListInstancesTrafficPackages"),
		// API Version
		Version: tea.String("2020-06-01"),
		// Protocol
		Protocol: tea.String("HTTPS"),
		// HTTP Method
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("RPC"),
		// API PATH
		Pathname: tea.String("/"),
		// Request body content format
		ReqBodyType: tea.String("json"),
		// Response body content format
		BodyType: tea.String("json"),
	}
	_result = params
	return _result
}

func _main(args []*string) (_err error) {
	// Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
	// The project code leakage may result in the leakage of AccessKey, posing a threat to the security of all resources under the account. The following code example is called by using the environment variable to obtain the AccessKey, for reference only. It is recommended to use the more secure STS credential. For more credentials, please refer to: https://www.alibabacloud.com/help/en/alibaba-cloud-sdk-262060/latest/configure-credentials-378661
	client, _err := CreateClient(args[0], args[1])
	if _err != nil {
		return _err
	}

	params := CreateApiInfo()
	// query params
	queries := map[string]interface{}{}
	queries["RegionId"] = args[2]
	queries["InstanceIds"] = tea.String("[\"" + *args[3] + "\"]")
	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
	}

	// Copy the code to run, please print the return value of the API by yourself.
	// The return value is of Map type, and three types of data can be obtained from Map: response body, response headers, HTTP status code.
	res, _err := client.CallApi(params, request, runtime)
	if _err != nil {
		return _err
	}

	fmt.Println(res)

	TrafficPackageRemaining := gconv.Int64(res["body"].(map[string]interface{})["InstanceTrafficPackageUsages"].([]interface{})[0].(map[string]interface{})["TrafficPackageRemaining"])
	if TrafficPackageRemaining != 0 && TrafficPackageRemaining <= gconv.Int64(args[4]) {
		log.Println("执行系统关机...")
		cmd := exec.Command("/sbin/shutdown", "-h", "now")
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

		err := cmd.Run()
		if err != nil {
			log.Println("关机命令执行失败:", err)
			return
		}
	} else {
		log.Println("剩余流量:", TrafficPackageRemaining)
	}

	return _err
}

func main() {
	err := _main(tea.StringSlice(os.Args[1:]))
	if err != nil {
		panic(err)
	}
}








Preview Image