Esempio n. 1
0
def monitor(secu_id, secu_key, region):
    # flag = 0
    ins_id = ''
    try:
        cred = credential.Credential(secu_id, secu_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, region, clientProfile)

        # 查询实例列表
        req = models.DescribeInstancesRequest()
        params = '{}'
        req.from_json_string(params)

        resp = client.DescribeInstances(req)
        # 转成python字典
        ins_set = json.loads(resp.to_json_string())
        # 初始化比较时间
        temp = datetime.datetime.strptime("2000-01-01 00:00:00",
                                          '%Y-%m-%d %H:%M:%S')

        # 遍历实例列表,取出创建时间比较拿到最新创建实例的那台实例id
        for ins in ins_set['InstanceSet']:
            create_time = datetime.datetime.strptime(
                ins['CreatedTime'].replace('T', ' ').replace('Z', ''),
                '%Y-%m-%d %H:%M:%S')
            if temp < create_time:
                ins_id = ins['InstanceId']
        # 查看这台实例的状态,循环检测,直到状态为运行态停止
        while True:
            req = models.DescribeInstancesStatusRequest()
            params = '{"InstanceIds":["%s"]}' % ins_id
            req.from_json_string(params)

            resp = client.DescribeInstancesStatus(req)
            # 转成python字典
            status = json.loads(resp.to_json_string())
            if status['InstanceStatusSet'][0]['InstanceState'] == "RUNNING":
                flag = 1
                req_ip = models.DescribeInstancesRequest()
                params = '{"InstanceIds":["%s"]}' % ins_id
                req_ip.from_json_string(params)

                resp = client.DescribeInstances(req_ip)
                # 转成python字典
                ins_set = json.loads(resp.to_json_string())
                # ip = ins_set['InstanceSet'][0]['PrivateIpAddresses']
                ip = ins_set['InstanceSet'][0]['PrivateIpAddresses']
                break
        if flag == 1:
            return ip
        else:
            return 0

    except TencentCloudSDKException as err:
        print(err)
Esempio n. 2
0
    def get_region_instance(self, region, offset_str=''):

        offset = "1" * len(offset_str)
        data = {"Offset": len(offset),
                "Limit": 100}
        try:
            client = cvm_client.CvmClient(self.cred, region, self.clientProfile)
            req = models.DescribeInstancesRequest()
            params = json.dumps(data)
            req.from_json_string(params)

            res = client.DescribeInstances(req)
            res = json.loads(res.to_json_string())
            tmp_ins = res.get("InstanceSet")
            for ins in tmp_ins:
                self.instances.append(ins)
            totalCount = res.get("TotalCount")

            if totalCount > data["Offset"] + data["Limit"]:
                offset_str = offset + "1" * len(tmp_ins)
                self.get_region_instance(region, offset_str=offset_str)
            else:
                return self.instances
        except TencentCloudSDKException:
            return {"msg": _("InvalidAccessKeyId.NotFound Specified access key is not found")}
Esempio n. 3
0
def getRegionCvmList(region):
    client = getCvmClient(region)
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    data = json.loads(resp.to_json_string())
    for instance in data["InstanceSet"]:
        saveInstance(instance)
Esempio n. 4
0
def describeIns(cred):
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        # cred = credential.Credential(
        #     os.environ.get("TENCENTCLOUD_SECRET_ID"),
        #     os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        client = new_cvm_client(cred=cred, method="GET")

        req = cvm_models.DescribeInstancesRequest()

        respFilter = cvm_models.Filter()
        respFilter.Name = "zone"
        respFilter.Values = ['ap-guangzhou-3', 'ap-guangzhou-2']

        resp = client.DescribeInstances(req)

        if os.getenv('API_JSON_INFO'):
            apiinfo("Json Response")
            print(resp.to_json_string())
        # return(resp.to_json_string())
        return (resp)

    except TencentCloudSDKException as err:
        # print(err)
        pass
Esempio n. 5
0
def _test_describe_instances(http_method, sign_method, unsigned_payload=False):
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    httpProfile = HttpProfile()
    httpProfile.reqMethod = http_method

    clientProfile = ClientProfile()
    clientProfile.signMethod = sign_method
    clientProfile.unsignedPayload = unsigned_payload
    clientProfile.httpProfile = httpProfile

    client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)
    req = models.DescribeInstancesRequest()
    headers = {
        "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca",
    }
    req.headers = headers

    fzone = models.Filter()
    fzone.Name = "zone"
    fzone.Values = ["ap-guangzhou-1", "ap-guangzhou-2"]
    fname = models.Filter()
    fname.Name = "instance-name"
    fname.Values = [u"中文", u"测试"]
    req.Filters = [fzone, fname]
    resp = client.DescribeInstances(req)
    assert resp.TotalCount >= 0
Esempio n. 6
0
def getInstanceIdByPrivateIpAddress(PrivateIpAddress):
    req = models.DescribeInstancesRequest()
    respFilter = models.Filter()
    respFilter.Name = "private-ip-address"
    respFilter.Values = [PrivateIpAddress]
    req.Filters = [respFilter]
    resp = client.DescribeInstances(req)
    return resp.InstanceSet[0].InstanceId
Esempio n. 7
0
def getInstanceAttribute(InstanceId):
    req = models.DescribeInstancesRequest()
    respFilter = models.Filter()
    respFilter.Name = "instance-id"
    respFilter.Values = [InstanceId]
    req.Filters = [respFilter]
    resp = client.DescribeInstances(req)
    return resp.InstanceSet[0] if resp.TotalCount > 0 else None
    def get_instance_by_id(self, region, instance_id):
        ''' Get CVM instance in a specified instance id '''

        client = self.get_cvm_client(region)
        request = models.DescribeInstancesRequest()
        request.InstanceIds = [instance_id]
        response = client.DescribeInstances(request)
        if len(response.InstanceSet) > 0:
            return response.InstanceSet[0]
def test_describe_instances():
    cred = credential.STSAssumeRoleCredential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"),
        os.environ.get("TENCENTCLOUD_ROLE_ARN"), "test")

    client = cvm_client.CvmClient(cred, "ap-guangzhou")
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    assert resp.TotalCount >= 0
Esempio n. 10
0
 def get_describe_instances(self):
     """获取实例列表"""
     # req = models.DescribeInstancesResponse()
     req = models.DescribeInstancesRequest()
     params = {"Offset": self.Offset, "Limit": self.Limit}
     req.from_json_string(json.dumps(params))
     resp = self.client.DescribeInstances(req)
     data = json.loads(resp.to_json_string())
     data['results'] = data.pop('InstanceSet')
     data['count'] = data.pop('TotalCount')
     return data
Esempio n. 11
0
def show_cvm_info(cvm_id):
    try:
        #cvm_params = {"InstanceIds.N": [cvm_id]}
        filter_params = {"Filters": [{"Name": "instance-id", "Values": [cvm_id]}]}
        req = cvm_models.DescribeInstancesRequest()
        req.from_json_string(json.dumps(filter_params))

        resp = cvm_client.DescribeInstances(req)
        cvm_ip = json.loads(resp.to_json_string())["InstanceSet"][0]["PublicIpAddresses"]
        return cvm_ip
    except TencentCloudSDKException as err:
        print(err)
Esempio n. 12
0
 def get_describeinstances(self,region):
     try:
         cred = self.get_cred()
         self.hp.endpoint = "cvm.tencentcloudapi.com"
         self.cp.httpProfile = self.hp
         client = cvm_client.CvmClient(cred,region,self.cp)
         req = models.DescribeInstancesRequest()
         params = '{}'
         req.from_json_string(params)
         resp = client.DescribeInstances(req)
         return resp.to_json_string()
     except TencentCloudSDKException as e:
         return None
Esempio n. 13
0
def insert_ins_type(account_name, httpProfile, cred, region):

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = cvm_client.CvmClient(cred, region, clientProfile)

    # 向腾讯云发送实例列表描述请求
    req = models.DescribeInstancesRequest()
    params = '{}'
    req.from_json_string(params)

    # 腾讯云应当包
    resp = client.DescribeInstances(req)

    # 转换为python字典
    res = json.loads(resp.to_json_string())

    # 实例集合
    for ins_set in res['InstanceSet']:
        ins_cpu = ins_set['CPU']
        ins_memory = ins_set['Memory']
        ins_id = ins_set['InstanceId']
        disk_size = ins_set['SystemDisk']['DiskSize']

        req = models.DescribeInstanceInternetBandwidthConfigsRequest()
        params = '{"InstanceId":"%s"}' % ins_id
        req.from_json_string(params)

        # 查询实例带宽配置
        resp = client.DescribeInstanceInternetBandwidthConfigs(req)
        # 转成python字典
        res = json.loads(resp.to_json_string())

        internet_width = res['InternetBandwidthConfigSet'][0][
            'InternetAccessible']['InternetMaxBandwidthOut']

        # 组合cpu/memory/disk_size/internet_width信息
        merge = str(ins_cpu) + '核/' + str(ins_memory) + 'G/' + str(
            internet_width) + 'Mbps/' + str(disk_size) + 'G'

        # 插入数据库,上线部署后换为私有ip
        str_ip = str(ins_set['PrivateIpAddresses']).replace('[', '').replace(
            ']', '').replace("'", "")
        # str_ip = str(ins_set['PrivateIpAddresses']).replace('[', '').replace(']', '').replace("'", "")

        # 查看ip是否已经存在,不存在则插入,存在则更新
        ins_type = InsType(ins_type=merge,
                           ip=str_ip,
                           account_name=account_name)
        ins_type.save()
Esempio n. 14
0
def get_cvm(Region_Id):
    """
    查询实例列表
    :param config_dict:
    :return: InstanceId
    """
    describe_request = cvm_models.DescribeInstancesRequest()
    try:
        clt = cvm_client.CvmClient(cred, Region_Id)
        response = clt.DescribeInstances(describe_request)
        result_content = response.to_json_string()
        return json.loads(result_content)
    except TencentCloudSDKException as e:
        print(e)
Esempio n. 15
0
 def get_describe_instances(self, region):
     """
     请求cvm实例
     :param region:
     :return:
     """
     try:
         client = cvm_client.CvmClient(self.cred, region)
         request = models.DescribeInstancesRequest()
         response = client.DescribeInstances(request)
         data_json = json.loads(response.to_json_string())
         return data_json
     except TencentCloudSDKException as e:
         return e
Esempio n. 16
0
def test_req_deserialize_warning():
    warnings.simplefilter('error')

    req = models.DescribeInstancesRequest()
    params = '''{
        "TopUnknownField": "some value",
        "Filters": [
            {
                "Name": "zone",
                "Values": ["ap-shanghai-1", "ap-shanghai-2"],
                "InnerUnknownField": "some value"
            }
        ]
    }'''

    with pytest.raises(Exception) as e:
        req.from_json_string(params)
    assert "fileds are useless" in str(e)
Esempio n. 17
0
    def des_cvm(self, instance_id):
        """
        根据实例id查询cvm信息
        :return:
        """

        describe_req = cvm_models.DescribeInstancesRequest()
        describe_req.Filters = [{
            "Name": "instance-id",
            "Values": [instance_id]
        }]
        try:
            response = self.cvm_helper.DescribeInstances(describe_req)
            result_content = response.to_json_string()

            return json.loads(result_content)
        except TencentCloudSDKException as err:
            print(err)
Esempio n. 18
0
def cvm(client_cvm):
    try:
        filter_params = {
            "Filters": [{
                "Name": "instance-charge-type",
                "Values": ["PREPAID"]
            }]
        }
        req = cvm_models.DescribeInstancesRequest()
        """req.Filters = [{
            "Name": "instance-charge-type",
            "Values": ["PREPAID"]
        }]"""
        req.from_json_string(json.dumps(filter_params))
        resp = client_cvm.DescribeInstances(req)
        cvm_info = json.loads(resp.to_json_string())["InstanceSet"]
        return cvm_info
    except TencentCloudSDKException as err:
        print(err)
Esempio n. 19
0
    def get_instances(self):
        try:
            # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
            cred = credential.Credential(AccessKeyId, AccessKeySecret)
            # 实例化要请求产品(以cvm为例)的client对象
            client = cvm_client.CvmClient(cred, region)
            # 实例化一个请求对象
            # req = models.DescribeZonesRequest()
            # # 通过client对象调用想要访问的接口,需要传入请求对象
            # resp = client.DescribeZones(req)

            req = models.DescribeInstancesRequest()
            resp = client.DescribeInstances(req)
            # 输出json格式的字符串回包
            print(resp.to_json_string())
            info = resp.to_json_string()
            return info
        except TencentCloudSDKException as err:
            print(err)
Esempio n. 20
0
def _describe_instances():
    global TOTAL_CVM_INSTANCES
    TOTAL_CVM_INSTANCES.clear()

    client = _get_cvm_client()

    offset = 0
    while (True):
        req = models.DescribeInstancesRequest()
        req.Offset = offset
        req.Limit = ITEM_UNIT

        resp = client.DescribeInstances(req)
        for instance in resp.InstanceSet:
            TOTAL_CVM_INSTANCES[instance.InstanceId] = instance

        if len(resp.InstanceSet) < ITEM_UNIT:
            break
        offset = offset + ITEM_UNIT
        time.sleep(0.025)
Esempio n. 21
0
def _get_node(name):
    '''
    Return Tencent Cloud instance detail by name
    '''
    attempts = 5
    while attempts >= 0:
        try:
            client = get_provider_client("cvm_client")
            req = cvm_models.DescribeInstancesRequest()
            req.Filters = [{"Name": "instance-name", "Values": [name]}]
            resp = client.DescribeInstances(req)
            return resp.InstanceSet[0]
        except Exception as ex:
            attempts -= 1
            log.debug(
                'Failed to get data for node \'%s\': %s. Remaining attempts: %d',
                name, ex, attempts)
            time.sleep(0.5)

    raise SaltCloudNotFound('Failed to get instance info {0}'.format(name))
    def get_instances_by_region(self, region):
        ''' Makes an API call to the list of instances in a particular region '''

        client = self.get_cvm_client(region)
        instances = []
        page_number = 0
        limit = 20
        while True:
            request = models.DescribeInstancesRequest()
            request.Offset = limit * page_number
            request.Limit = limit
            response = client.DescribeInstances(request)
            # print(request.to_json_string())
            # print(response.to_json_string())
            instances.extend(response.InstanceSet)
            if len(response.InstanceSet) < limit:
                break
            page_number += 1

        for instance in instances:
            self.add_instance(instance, region)
Esempio n. 23
0
def _get_nodes():
    """
    Return all list of Tencent Cloud instances
    """
    ret = []
    offset = 0
    limit = 100

    while True:
        client = get_provider_client("cvm_client")
        req = cvm_models.DescribeInstancesRequest()
        req.Offset = offset
        req.Limit = limit
        resp = client.DescribeInstances(req)
        for v in resp.InstanceSet:
            ret.append(v)
        if len(ret) >= resp.TotalCount:
            break
        offset += len(resp.InstanceSet)

    return ret
Esempio n. 24
0
def test_describe_instances():
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    hp = HttpProfile()
    hp.scheme = "http"
    hp.endpoint = "cvm.ap-shanghai.tencentcloudapi.com"

    cp = ClientProfile()
    cp.httpProfile = hp

    client = cvm_client.CvmClient(cred, "ap-guangzhou", cp)
    req = models.DescribeInstancesRequest()
    try:
        resp = client.DescribeInstances(req)
    except TencentCloudSDKException as e:
        # 403 forbidden
        assert e.code == "ServerNetworkError"
        assert b"403 Forbidden" in e.message
        return
    assert "" == "exception is not captured"
Esempio n. 25
0
def _get_node(name):
    """
    Return Tencent Cloud instance detail by name
    """
    attempts = 5
    while attempts >= 0:
        try:
            client = get_provider_client("cvm_client")
            req = cvm_models.DescribeInstancesRequest()
            req.Filters = [{"Name": "instance-name", "Values": [name]}]
            resp = client.DescribeInstances(req)
            return resp.InstanceSet[0]
        except Exception as ex:  # pylint: disable=broad-except
            attempts -= 1
            log.debug(
                "Failed to get data for node '%s': %s. Remaining attempts: %d",
                name,
                ex,
                attempts,
            )
            time.sleep(0.5)

    raise SaltCloudNotFound("Failed to get instance info {}".format(name))
Esempio n. 26
0
def cloud(request):
    # 注意保密
    sId = 'Your_ID'
    sKey = 'Your_Key'

    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(sId, sKey)
        # 实例化要请求产品的client对象
        client = cvm_client.CvmClient(cred, "ap-guangzhou")
        # 实例化一个请求对象
        req = models.DescribeInstancesRequest()
        # 传入参数
        req.Limit = 100
        # 通过client对象调用想要访问的接口,需要传入请求对象
        resp = client.DescribeInstances(req).to_json_string()
        servers = json.loads(resp)['InstanceSet']
    except TencentCloudSDKException as err:
        print(err)

    context = {
        'servers': servers,
    }
    return render(request, 'cmdb_info/cloud.html', context=context)
Esempio n. 27
0
def insert():
    # 休眠5秒,等待所有服务器信息全部传过来
    time.sleep(5)
    region = []
    # 连接数据库获取腾讯云账户信息
    conn = pymysql.connect('localhost', 'root', 'P@ssw0rd1', 'zero_server')
    cursor = conn.cursor()
    sql = "select * from zero_cloud_user;"
    cursor.execute(sql)
    data = cursor.fetchall()
    for info in data:
        try:
            # 密钥
            cred = credential.Credential(info[2], info[3])
            httpProfile = HttpProfile()
            httpProfile.endpoint = "cvm.tencentcloudapi.com"

            # clientProfile = ClientProfile()
            # clientProfile.httpProfile = httpProfile
            # client = cvm_client.CvmClient(cred, "", clientProfile)
            #
            # # 所有可用地域,
            # req = models.DescribeRegionsRequest()
            # params = '{}'
            # req.from_json_string(params)
            #
            # # 结果转成字典类型
            # resp = client.DescribeRegions(req)
            # # print(resp.to_json_string())
            # res = json.loads(resp.to_json_string())
            #
            # for i in range(res['TotalCount']):
            #     region.append(res['RegionSet'][i]['Region'])

            region_sql = """select a.code from zero_zone_code a right join zero_server_account_zone b on a.zone=b.zone 
                                and b.account_name='%s';""" % info[1]
            cursor.execute(region_sql)
            region = cursor.fetchall()
            region = [x[0] for x in region]

            for reg in region:
                # 服务器所在大区
                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = cvm_client.CvmClient(cred, reg, clientProfile)

                # 向腾讯云发送实例列表描述请求
                req = models.DescribeInstancesRequest()
                params = '{}'
                req.from_json_string(params)

                # 腾讯云应当包
                resp = client.DescribeInstances(req)
                # 腾讯云应答包,json串,string
                # print(resp.to_json_string())

                # 转换为python字典
                res = json.loads(resp.to_json_string())

                # 该账户下总的实例个数
                total = res['TotalCount']

                # 一个账户下多个实例,根据内网ip进行通信,做好对等连接
                for i in range(total):
                    pub_ip = res['InstanceSet'][i]['PrivateIpAddresses']
                    # PriIp = res['InstanceSet'][i]['PrivateIpAddresses']
                    # print(PriIp)
                    # 根据公网Ip获得一个实例上所有游戏服务器的名称,人数,繁忙服务器台数,空闲服务器台数
                    instance_insert_mysql.insert_mysql(
                        ''.join(pub_ip), 'root',
                        res['InstanceSet'][i]['InstanceId'], info[1])
                    # os.system("echo '%s' /home/tt.txt" % PriIp)
                    # instance_insert_mysql(''.join(PriIp), 'root', res['InstanceSet'][i]['InstanceId'], info[1])

        except TencentCloudSDKException as err:
            print(err)
import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

try:
    cred = credential.STSAssumeRoleCredential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"), # or read it from your config file
        os.environ.get("TENCENTCLOUD_SECRET_KEY"),
        "must-a-valid-role-arn", # for e.g.: "qcs::cam::uin/100123456789:roleName/test"
        "whatever-role-session-name")

    client = cvm_client.CvmClient(cred, "ap-guangzhou")
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    print(resp.to_json_string(indent=2))
except TencentCloudSDKException as err:
    print(err)
Esempio n. 29
0
def ip(ins_type):

    # 查询所有账户
    all_info = Account.objects.all().values_list('account_name', 'account_id',
                                                 'account_key')
    # 查询实例表中所有ip,放在ip_info列表中
    available_ip = []
    # 遍历账户查询结果
    for info in all_info:
        try:
            # 密钥
            cred = credential.Credential(info[1], info[2])
            httpProfile = HttpProfile()
            httpProfile.endpoint = "cvm.tencentcloudapi.com"
            region_code, region_name = real_time_region.search(
                info[1], info[2])
            # 服务器所在大区
            for region in region_code:

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = cvm_client.CvmClient(cred, region, clientProfile)

                # 向腾讯云发送实例列表描述请求
                req = models.DescribeInstancesRequest()
                params = '{}'
                req.from_json_string(params)

                # 腾讯云应当包
                resp = client.DescribeInstances(req)

                # 转换为python字典
                res = json.loads(resp.to_json_string())

                # 实例集合
                for ins_set in res['InstanceSet']:
                    ins_cpu = ins_set['CPU']
                    ins_memory = ins_set['Memory']
                    ins_id = ins_set['InstanceId']
                    disk_size = ins_set['SystemDisk']['DiskSize']

                    req = models.DescribeInstanceInternetBandwidthConfigsRequest(
                    )
                    params = '{"InstanceId":"%s"}' % ins_id
                    req.from_json_string(params)

                    # 查询实例带宽配置
                    resp = client.DescribeInstanceInternetBandwidthConfigs(req)
                    # 转成python字典
                    res = json.loads(resp.to_json_string())

                    internet_width = res['InternetBandwidthConfigSet'][0][
                        'InternetAccessible']['InternetMaxBandwidthOut']

                    # 组合cpu/memory/disk_size/internet_width信息
                    merge = str(ins_cpu) + '核/' + str(ins_memory) + 'G/' + str(internet_width) + 'Mbps/' +\
                        str(disk_size) + 'G'

                    # 插入数据库, 部署后改为内网
                    # str_ip = str(ins_set['PrivateIpAddresses']).replace('[', '').replace(']', '').replace("'", "")
                    str_ip = str(ins_set['PrivateIpAddresses']).replace(
                        '[', '').replace(']', '').replace("'", "")
                    # 如果要开设的服务器的实例类型和该实例一样,则加入可开设服务器的ip列表
                    if ins_type == merge:
                        available_ip.append(str_ip)
                    # 查看ip是否已经存在,不存在则插入,存在则更新
                    ins_type_save = InsType(ins_type=merge,
                                            ip=str_ip,
                                            account_name=info[0])
                    ins_type_save.save()

        except TencentCloudSDKException as err:
            print(err)
            raise err

    return available_ip
Esempio n. 30
0
def insert_ins_type():
    # 连接数据库,创建游标
    # conn = pymysql.connect("localhost", "root", "P@ssw0rd1", "zero_server")
    # cursor = conn.cursor()
    # sql查询语句执行,查询所有账户
    # sql = "select account_name,account_id,account_key from zero_cloud_user;"
    # cursor.execute(sql)
    # # 查询结果
    # all_info = cursor.fetchall()
    all_info = Account.objects.all().values_list('account_name', 'account_id',
                                                 'account_key')
    # 查询实例表中所有ip,放在ip_info列表中
    # sql2 = "select ip from zero_ins_type;"
    # cursor.execute(sql2)
    # ip_data = cursor.fetchall()
    ip_info = InsType.objects.all().values_list('ip', flat=True)
    # ip_info = []
    # for i in ip_data:
    #     ip_info.append(i[0])

    # 遍历账户查询结果
    for info in all_info:
        try:
            # 根据账户名称查询区域region
            # sql_region = "select region from zero_account_zone where account_name='%s';" % info[0]
            # cursor.execute(sql_region)
            # region_name = cursor.fetchone()
            region_name = AccountZone.objects.get(account_name=info[0]).region
            # 将region_name这个大字符串变成列表,并去掉字符串中的空格
            region_name = [x.strip() for x in region_name[0].split(',')]
            # 密钥
            cred = credential.Credential(info[1], info[2])
            httpProfile = HttpProfile()
            httpProfile.endpoint = "cvm.tencentcloudapi.com"

            # 服务器所在大区
            for region in region_name:
                # 根据region中文名在zero_zone_code表中查询中对应代号,code[0](code是数据库查询返回的元组)
                # sql_code = "select code from zero_zone_code where zone='%s';" % region
                # cursor.execute(sql_code)
                # code = cursor.fetchone()
                code = ZoneCode.objects.get(zone=region).code

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = cvm_client.CvmClient(cred, code[0], clientProfile)

                # 向腾讯云发送实例列表描述请求
                req = models.DescribeInstancesRequest()
                params = '{}'
                req.from_json_string(params)

                # 腾讯云应当包
                resp = client.DescribeInstances(req)

                # 转换为python字典
                res = json.loads(resp.to_json_string())

                # 实例集合
                for ins_set in res['InstanceSet']:
                    ins_cpu = ins_set['CPU']
                    ins_memory = ins_set['Memory']
                    ins_id = ins_set['InstanceId']
                    disk_size = ins_set['SystemDisk']['DiskSize']

                    req = models.DescribeInstanceInternetBandwidthConfigsRequest(
                    )
                    params = '{"InstanceId":"%s"}' % ins_id
                    req.from_json_string(params)

                    # 查询实例带宽配置
                    resp = client.DescribeInstanceInternetBandwidthConfigs(req)
                    # 转成python字典
                    res = json.loads(resp.to_json_string())

                    internet_width = res['InternetBandwidthConfigSet'][0][
                        'InternetAccessible']['InternetMaxBandwidthOut']

                    # 组合cpu/memory/disksize/bandwidth信息
                    merge = str(ins_cpu) + '核/' + str(ins_memory) + 'G/' \
                        + str(internet_width) + 'Mbps' + str(disk_size) + 'G/'

                    # 插入数据库
                    str_ip = str(ins_set['PrivateIpAddressed']).replace(
                        '[', '').replace(']', '').replace("'", "")

                    # 查看ip是否已经存在,不存在则插入,存在则更新
                    if str_ip not in ip_info:
                        # insert_sql = "insert into zero_ins_type(ins_type,ip,account_name) values('%s','%s','%s')" \
                        #              % (merge, str_ip, info[0])
                        # cursor.execute(insert_sql)
                        ins_type = InsType(ins_type=merge,
                                           ip=str_ip,
                                           account_name=info[0])
                        ins_type.save(force_insert=True)
                    else:
                        # update_sql = "update zero_ins_type set ins_type='%s' where ip='%s';" % (merge, str_ip)
                        # cursor.execute(update_sql)
                        InsType.objects.filter(ip=str_ip).update(
                            ins_type=merge)
                    # conn.commit()

        except TencentCloudSDKException as err:
            print(err)
            raise err