关于云服务:阿里云获取所有实例信息-API-使用

31次阅读

共计 3197 个字符,预计需要花费 8 分钟才能阅读完成。

阿里云获取所有实例信息 API 应用

应用前需装置依赖的 sdk 模块,能够在阿里云后盾查问相干 API 应用形式:

示例代码:

#! /usr/bin/env python
# -\*- coding: utf-8 -\*-
# \_\_author\_\_ = "shuke"
# Date: 2017/9/26

import json, yaml

try:
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkcore import client
    from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
except ImportError as e:
    print("Error:", e)
    exit()


class AliCloudApi(object):
    """阿里云 API 获取数据"""
    # 实例编号
    hid = 1
    # 所有 region 的主机
    all\_instances\_dic = {}

    def \_\_init\_\_(self, key, secret, zone="cn-beijing"):
        self.key = key
        self.secret = secret
        self.zone = zone
        self.client = AcsClient(self.key, self.secret, self.zone)

    def instances\_count(self, page\_size=10):
        """
        返回页码数量
        :param page\_size:
        :return:
        """
        # 创立 request,并设置参数
        request = DescribeInstancesRequest.DescribeInstancesRequest()
        request.set\_PageSize(page\_size)
        # 发动 API 申请并打印返回
        response = self.client.do\_action\_with\_exception(request)
        ret = json.loads(response, encoding='utf-8')

        # 页码
        total\_page, b = divmod(ret\['TotalCount'\], page\_size)
        if b:
            total\_page = total\_page + 1
        return total\_page

    def queryinstances(self):
        """
        获取各 region 的实例信息
        :return: region 下所有的实例信息
        """
        per\_region\_instances = \[\]
        try:
            total\_page = self.instances\_count()
            for page\_num in range(1, total\_page + 1):
                num = "第 %d 页" % page\_num
                print(num.center(100, "\*"))
                # 创立 request,并设置参数
                request = DescribeInstancesRequest.DescribeInstancesRequest()
                request.set\_PageNumber(page\_num)

                # 发动 API 申请并打印返回
                response = self.client.do\_action\_with\_exception(request)
                ret = json.loads(response, encoding='utf-8')
                # print(json.dumps(ret), indent=4, ensure\_ascii=False))

                instances = ret\['Instances'\]\['Instance'\]
                for item in instances:
                    ele = {}
                    ele\['ZoneId'\] = item\['ZoneId'\]
                    ele\['InstanceId'\] = item\['InstanceId'\]
                    ele\['InstanceType'\] = item\['InstanceType'\]
                    ele\['HostName'\] = item\['HostName'\]
                    ele\['InstanceName'\] = item\['InstanceName'\]
                    # 公网 IP
                    if item\['PublicIpAddress'\]\['IpAddress'\]:
                        ele\['PublicIpAddress'\] = item\['PublicIpAddress'\]\['IpAddress'\]\[0\]
                    else:
                        ele\['PublicIpAddress'\] = ""
                    # 私网 IP
                    if item\['InnerIpAddress'\]\['IpAddress'\]:
                        ele\['InnerIpAddress'\] = item\['InnerIpAddress'\]\['IpAddress'\]\[0\]
                    else:
                        ele\['InnerIpAddress'\] = item\['VpcAttributes'\]\['PrivateIpAddress'\]\['IpAddress'\]\[0\]

                    print(AliCloudApi.hid, ele\['ZoneId'\], ele\['InstanceId'\], ele\['InstanceType'\], ele\['HostName'\],
                          ele\['InstanceName'\], ele\['PublicIpAddress'\], ele\['InnerIpAddress'\])
                    AliCloudApi.hid += 1
                    # 每个实例放入列表中
                    # print(ele)
                    per\_region\_instances.append(ele)
                page\_num += 1
        except Exception as e:
            print("ERROR:", e)

        return per\_region\_instances

    def get\_all\_instances(self, region\_li):
        """
        取得所有 region 实例
        :param region\_li: region 列表
        :return:
        """
        for zone in region\_li:
            self.zone = zone
            print("\\033\[0;32mNow,start query %s region\\033\[0m" % zone)
            obj = AliCloudApi(self.key, self.secret, zone)
            per\_region\_instances = obj.queryinstances()
            AliCloudApi.all\_instances\_dic\[zone\] = per\_region\_instances

        return AliCloudApi.all\_instances\_dic


if \_\_name\_\_ == '\_\_main\_\_':
    # 加载阿里云拜访 key
    key\_pair = yaml.load(open('aliyun.yml'))
    key = key\_pair\['key'\]
    secret = key\_pair\['secret'\]
    zones = \["cn-qingdao", "cn-hangzhou", "cn-beijing"\]
    # for zone in zones:
    #     print("\\033\[1;32mNow,start query %s region\\033\[0m" % zone)
    #     obj = AliCloudApi(key, secret, zone)
    #     per\_region\_instances = obj.queryinstances()
    #     all\_instances\_li\[zone\] = per\_region\_instances
    obj = AliCloudApi(key, secret)
    ret = obj.get\_all\_instances(zones)

正文完
 0