python使用阿里云ECS SDK统计出7天内到期的服务器

532次阅读
没有评论

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

由于阿里云的机器太多,而且账户也多,需要一个账户登录续费巡检不方便,
脚本内容如下

# -*- coding: utf-8 -*-
# yx  www.g6k.cn
# 遍历出 ecs rds mongdb redis 等续费信息,并打印成文件
"""
pip install aliyun-python-sdk-dds==3.7.3
pip install aliyun-python-sdk-ecs==4.24.26
pip install aliyun-python-sdk-rds==2.7.2
pip install aliyun-python-sdk-r-kvstore==2.20.7
"""

from aliyunsdkcore.client import AcsClient
from aliyunsdkrds.request.v20140815.DescribeDBInstancesRequest import DescribeDBInstancesRequest as Rdsgetinfoall
from aliyunsdkr_kvstore.request.v20150101.DescribeInstancesOverviewRequest import DescribeInstancesOverviewRequest
from aliyunsdkdds.request.v20151201.DescribeDBInstancesRequest import DescribeDBInstancesRequest as MongoDBgetinfoall
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
import json
from datetime import datetime
from xlsxwriter import workbook

def NowDatetime(ExpiredTime, strptime_time):
    news_date = datetime.strptime(ExpiredTime, strptime_time)
    long_data = (news_date - datetime.now()).days
    return long_data

#多个 ak, 只需要授权子账户 ecs 读取权限即可,避免出现乱调用出现问题!ak = {'access_key_id': 'access_key_secret',
      "access_key_id": "access_key_secret",
      "access_key_id": "access_key_secret",
      }
# 区域 id,根据实际情况补充列表
region_id = ['cn-beijing', 'cn-hangzhou', 'cn-shanghai', 'cn-shenzhen', 'cn-guangzhou', 'cn-hongkong']

expiration_ecs_xf_dict = []

####### 获取到期小于 7 天的 ecs#####
def get_ecs_data(access_key_id, access_key_secret, region_id):
    title_id = (
        '实例 ID',
        '主机名称',
        '所在区域',
        '系统类型',
        'CPU 核心',
        '内存大小',
        '运行状态',
        '过期时间',
        '剩余天数',
    )
    ecs_filename = "./aliyun_xf_ecs_Excel.xlsx"

    cli = client.AcsClient(access_key_id, access_key_secret, region_id)
    res = DescribeInstancesRequest.DescribeInstancesRequest()
    res.set_accept_format('json')
    res.set_PageSize(100)  ##  单页条数

    for i in range(1, 5):  ##  遍历 500 条数据,根据阿里云 ecs 实例实际情况调整
        res.set_PageNumber(i)  ## 遍历每页
        result = json.loads(cli.do_action_with_exception(res))
        ecs_info = result.get('Instances').get('Instance')
        # 遍历获取到的结果
        for info in ecs_info:
            Status = info.get('Status')  ## 实例状态
            InstanceId = info.get('InstanceId')  ## 实例 id
            InstanceName = info.get('InstanceName')  ## 实例名称
            ExpiredTime = info.get('ExpiredTime')  ## 实例到期时间
            RegionId = info.get('RegionId')  ## 所在区域
            OSType = info.get('OSType')
            Cpu = str(info.get('Cpu'))  ## cpu 核心数
            Memory = str(int(info.get('Memory')) / 1024)  ## 内存,单位 G
            strptime_time = "%Y-%m-%dT%M:%Sz"  #需要对时间格式处理
            xf = NowDatetime(ExpiredTime,strptime_time)+1
            news_date = datetime.strptime(info.get('ExpiredTime'), strptime_time)
            if int(xf) < 6:
                expiration_dict = (InstanceId,
                                   InstanceName,
                                   RegionId,
                                   OSType,
                                   Cpu,
                                   Memory,
                                   Status,
                                   news_date.date(),
                                   xf
                )
                expiration_ecs_xf_dict.append(expiration_dict)
            else:
                continue

    write_excel(ecs_filename, expiration_ecs_xf_dict, title_id)

def write_excel(file, data, title_id):
    '''
    1、设置 Excel 样式
    2、将数据写入到 Excel 中
    '''
    # 生成 Excel 文件
    work = workbook.Workbook(file)
    # 建立工作表,表名默认
    worksheet = work.add_worksheet("ecs 续费 ")
    # 设置字体加粗、字体大小
    format_title = work.add_format({'bold': True, 'font_size': 16})
    # 设置水平对齐、垂直对齐
    format_title.set_align('center')
    format_title.set_align('vcenter')

    format_body = work.add_format({'font_size': 14})
    # 设置样式,行高、列宽
    worksheet.set_row(0, 25)
    worksheet.set_column(0, 0, 35)
    worksheet.set_column(1, 1, 40)
    worksheet.set_column(2, 2, 20)
    worksheet.set_column(3, 5, 15)
    worksheet.set_column(6, 6, 20)
    worksheet.set_column(7, 7, 25)
    # 定义表头
    title = (title_id)
    row = 0
    col = 0


    # 表头写入文件,引用样式
    for item in title:
        worksheet.write(row, col, item, format_title)
        col += 1
    # 内容写入文件,引用样式
    for line in data:
        row += 1
        col = 0
        for key in line:
            worksheet.write(row, col, str(key), format_body)
            col += 1

    work.close()

#循环出 ak 并在每个 ak 下遍历出不同区域的 ecs 信息  
for k,v in ak.items():
    for i in region_id:
         get_ecs_data(access_key_id=k, access_key_secret=v, region_id=i)

效果如下
python 使用阿里云 ECS SDK 统计出 7 天内到期的服务器

正文完
 0
yx
版权声明:本站原创文章,由 yx 于2022-12-27发表,共计3367字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码