统计阿里云ECS停机状态的主机

  1. 一、缘由
  2. 二、环境
  3. 三、代码实现

一、缘由

本脚本是阿里云资源利用率定期统计方案中的其中一个脚本。

公司阿里云ECS比较多,地区比较多,乃至有多个账号,一个个查看和统计比较费事费力。现编写一个统计阿里云ECS处于停机状态的主机的脚本,输出Excel文档后,我们可以区分,哪些还处于停机收费状态,哪些可以释放,哪些不可以释放。

二、环境

**Python3.7 + 阿里云ECS的SDK + pandas **

三、代码实现

# -*- coding: utf-8 -*-
from typing import List
import pandas as pd

from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_ecs20140526 import models as ecs_20140526_models

REGION_ID = ['cn-beijing', 'cn-hangzhou', 'cn-zhangjiakou', 'cn-shenzhen', 'cn-shanghai', 'cn-hongkong',
             'ap-southeast-1', 'ap-northeast-1']


class GetInstanceIdName:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> Ecs20140526Client:
        config = open_api_models.Config(
            access_key_id='xxxxxxxxxx',
            access_key_secret='xxxxxxxxxx'
        )
        config.endpoint = 'ecs-cn-hangzhou.aliyuncs.com'
        return Ecs20140526Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = GetInstanceIdName.create_client('accessKeyId', 'accessKeySecret')
        describe_instances_request = ecs_20140526_models.DescribeInstancesRequest(
            region_id=args[1],
            next_token=args[0],
            max_results=50
        )
        res = client.describe_instances(describe_instances_request)
        return res.body


def get_instance_status():
    instance_dict = {}
    for i in range(0, len(REGION_ID)):
        token = 'init_data'
        while token:
            result = GetInstanceIdName.main([token, REGION_ID[i]])
            token = result.next_token
            info_list = result.instances.instance
            # print(dir(info_list[0]))
            for j in range(0, len(info_list)):
                if info_list[j].status == 'Stopped':
                    instance_dict[info_list[j].instance_id] = []
            for k in range(0, len(info_list)):
                if info_list[k].status == 'Stopped':
                    instance_dict[info_list[k].instance_id].append(info_list[k].instance_name)
                    instance_dict[info_list[k].instance_id].append(info_list[k].status)
                    instance_dict[info_list[k].instance_id].append(info_list[k].stopped_mode)
                    instance_dict[info_list[k].instance_id].append(info_list[k].description)
    return instance_dict


def write_to_execl(data):
    df = pd.DataFrame.from_dict(data, orient='index', columns=['实例名称', '实例状态', '停机收费状态', '实例备注'])
    df.to_excel('ecs_stopped.xlsx')


if __name__ == '__main__':
    instance_info = get_instance_status()
    write_to_execl(instance_info)

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 lxwno.1@163.com

×

喜欢就点赞,疼爱就打赏