Tencent cloud lightweight worry free plan New and old users enjoy the same discount As low as 15 element / Month begins Lifetime renewal at the same price A year's worth of top-level domain names , And enjoy long-term renewal discount
Activity Links :https://cloud.tencent.com/act/lighthouse
Please use this code first Child users create And authorize cloud API With all permissions of lightweight application server
Please note that To ensure the security of your account and cloud assets Please keep it carefully SecretId And SecretKey And regularly update Delete useless permissions
Go to create sub user :https://console.cloud.tencent.com/cam
Please make sure Python Version is 3.6+
see Python edition
python3 -V
Install Tencent cloud Python SDK
pip3 install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
Code principle : By calling the cloud api Get lightweight instance information , And judge whether the traffic packet usage reaches the preset value , If yes, the instance information will be output ( Optional : And shut down the instance ), Avoid expense
Most of the code contains comments This code only needs to be modified SecretId And 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','ap-mumbai','eu-frankfurt'] # Add... Here SecretId And 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: # See all instances req = models.DescribeInstancesRequest() params = { } req.from_json_string(json.dumps(params)) resp = client.DescribeInstances(req) response = json.loads(resp.to_json_string()) # print(response1) # Instance details basic = response['InstanceSet'] # Determine whether the region contains instances if response['TotalCount'] > 0: print(aria[i] + ' The number of instances is ' + str(response['TotalCount'])) # Extract returned json Information 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'] # View traffic package 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] # Total discharge tft = str(round(tf['TrafficPackageTotal'] / 1073741824, 2)) # Used flow tfu = str(round(tf['TrafficUsed'] / 1073741824, 2)) # Residual flow tfr = str(round(tf['TrafficPackageRemaining'] / 1073741824, 2)) # Used flow % percent_tfu = round( round(tf['TrafficUsed'] / 1073741824, 2) / round(tf['TrafficPackageTotal'] / 1073741824, 2) * 100, 3) # Residual flow % percent_tfr = 100 - percent_tfu # Judge whether the used flow of the instance reaches the preset value (1 That is to say 1%) if percent_tfu > 1.000: print('IP by :' + ip + ' example Id by : ' + id + ' The flow of has reached the preset value ',' Time :'+strftime('%Y-%m-%d %H:%M:%S', localtime()),sep='\n') # Judge instance status If it is turned on, it will be turned off ( Please consider whether to comment the following code according to the actual situation ) if state == 'RUNNING': # Close instance 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(' Yes. IP by :' + ip + ', example id by :' + id + ' Shut down ',' execution time :'+execute_time,sep='\n') except TencentCloudSDKException as err: print(err) except TencentCloudSDKException as err: print(err) print('--------------------------------', 'id: ' + id, ' Instance status : ' + state, 'ip: ' + ip, ' Creation time : ' + ct, ' Due time : ' + et, ' operating system : ' + os, ' Total discharge :' + tft + 'GB', ' Used flow (%): ' + tfu + 'GB' + ' (' + str(percent_tfu) + '%)', ' Residual flow : ' + tfr + 'GB' + ' (' + str(percent_tfr) + '%)', ' When the request was sent :' + strftime('%Y-%m-%d %H:%M:%S', localtime()), '--------------------------------', sep='\n') except TencentCloudSDKException as err: print(err) end = time() print(' This code execution takes a total of :', round(end - start, 2), 's') # Execute every minute , You can modify sleep(60)
Upload the code to Linux The server can use nohup And & Command suspends code in the background
nohup python3 <name>.py &
The output content will be saved in the current directory ’nohup.out' in
You can use cat Command to view
cat nohup.out
Any questions can be left in the comment area
Coding is not easy Click "like" and "pay attention" before you leave ~