# -*- coding: utf-8 -*- from __future__ import absolute_import import os 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.cvm.v20170312 import cvm_client, models from ops.mmysql import MysqlBase class Qclound(): def __init__(self, area="ap-beijing"): secretid = os.getenv("miles_id") secretkey = os.getenv("miles_key") cred = credential.Credential(secretid, secretkey) httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile self.client = cvm_client.CvmClient(cred, area, clientProfile) def start_instance(self, instanceid): try: req = models.StartInstancesRequest() params = '{"InstanceIds":["%s"]}' % instanceid req.from_json_string(params) resp = self.client.StartInstances(req) print(resp.to_json_string()) data = resp.to_json_string() return True, data except TencentCloudSDKException as err: print(err) return False, err def stop_instance(self, instanceid): try: req = models.StopInstancesRequest() params = '{"InstanceIds":["%s"],"StoppedMode":"STOP_CHARGING"}' % instanceid req.from_json_string(params) resp = self.client.StopInstances(req) print(resp.to_json_string()) data = resp.to_json_string() return True, data except TencentCloudSDKException as err: print(err) return True, err def desc_instance(self, instanceid): try: req = models.DescribeInstancesStatusRequest() params = '{"InstanceIds":["%s"]}' % instanceid req.from_json_string(params) resp = self.client.DescribeInstancesStatus(req) print(resp.to_json_string()) data = resp.InstanceStatusSet[0].InstanceState return True, data except TencentCloudSDKException as err: print(err) return True, err def get_all_instance(self): all = {} try: req = models.DescribeInstancesRequest() for i in range(10): params = '{"Offset":%s,"Limit":20}' % str(i) req.from_json_string(params) resp = self.client.DescribeInstances(req) if resp: for item in resp.InstanceSet: if item: all[item.PrivateIpAddresses[0]] = item.InstanceId else: break except TencentCloudSDKException as err: print(err) return all def get_instanceid(self, ip): all = self.get_all_instance() if ip in all.keys(): return all[ip] else: return None if __name__ == "__main__": qc = Qclound('ap-beijing') # aa = qc.get_all_instance() #print(aa) id = qc.get_instanceid('10.10.7.17') print("2 {}".format(id)) if id: qc.desc_instance(id) qc.stop_instance(id) #qc.start_instance(id)