Python3获取ECS相关信息

aliyun-openapi-python-sdk  ecs api概览传送门 Openapi


pip3 install  aliyun-python-sdk-core
pip3 install aliyun-python-sdk-ecs



# -*- coding: utf-8 -*-

'''
Copyright (c) 2018, mersap
All rights reserved.

摘    要: base aliyun ecs api.py
创 建 者: mersap
创建日期: 2019-01-30
'''
import json
from aliyunsdkcore import client
from aliyunsdkcore.request import CommonRequest
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest

KEYS = client.AcsClient(
    "aaaaaaaa",
    "bbbbbbbbbbbbb",
    "cn-beijing")
class AliyunEcsHandler(object):
    """docstring for Ali"""
    def DescribeInstances(self, client, page_num=1, innerip='', instanceids=''):
        """
        :DescribeInstances(client=KEYS,innerip='"10.10.10.10","10.10.10.11"')
        """

        request = DescribeInstancesRequest.DescribeInstancesRequest()
        request.set_PageNumber(page_num)
        request.set_PageSize(100)
        if not len(innerip) == 0:
            request.set_InnerIpAddresses('[{}]'.format(innerip))
        if not len(instanceids) == 0:
            request.set_InstanceIds('[{}]'.format(instanceids))
        response = client.do_action_with_exception(request)
        return json.loads(response)



    def Instances_Details(self, client):
        """获取帐号下所有主机信息:  所有
        :params client:阿里云accesskey
        """
        ecs_details = self.DescribeInstances(client)
        totalcount = ecs_details['TotalCount']
        for num in range(2, int(totalcount/100)+2):
            ecs_detail = self.DescribeInstances(client=client, page_num=num)
            for ecs in  ecs_detail["Instances"]["Instance"]:          
                ecs_details["Instances"]["Instance"].append(ecs)
        return  ecs_details


def test_ecs():
    """ecs信息汇总
    """
    ecs = AliyunEcsHandler()
    ecs_details = ecs.Instances_Details(KEYS)
    cpus , memorys = 0, 0
    for ecs in ecs_details['Instances']['Instance']:
        cpus += ecs['Cpu']
        memorys += ecs['Memory']
    print('ECS总数: {} 台,共{} Cpus、 {} GB '.format(
        ecs_details['TotalCount'],
        cpus , 
        memorys/1024)
    )
    

if __name__ == '__main__':
    test_ecs()


上一篇:POJ 1321 棋盘问题(DFS板子题,简单搜索练习)


下一篇:Web应用防火墙使用“指北”