10-15 3 views
1. 安装阿里云云主机ECS管理模块
参考:https://help.aliyun.com/document_detail/25699.html?spm=a2c4g.11174283.2.52.119052feDvILXq
1 |
pip install aliyun-python-sdk-ecs |
2. 接口使用
https://help.aliyun.com/document_detail/25506.html?spm=a2c4g.11186623.6.1162.477c49baOuAWJA
https://help.aliyun.com/document_detail/25514.html?spm=a2c4g.11186623.6.1216.39a5431dHF33HN
3. 代码
以下为个人在项目中的应用,仅供参考
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : Eric Winn # @Email : eng.eric.winn@gmail.com # @Time : 2019/10/14 9:59 AM # @Version : 1.0 # @File : aliecs # @Software : PyCharm import json from multiprocessing import Pool from django.conf import settings from aliyunsdkcore.client import AcsClient from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest from aliyunsdkecs.request.v20140526.DescribeRegionsRequest import DescribeRegionsRequest from aliyunsdkecs.request.v20140526.DescribeDisksRequest import DescribeDisksRequest from libs.utils import get_logger logger = get_logger(__file__) def print_dict_key(item, key): region_id = item.get(key) return region_id class ECS: ''' 获取阿里云当前账户下所有的ECS主机及其详细信息 参考文档:https://help.aliyun.com/document_detail/25506.html?spm=a2c4g.11186623.6.1162.477c49baOuAWJA 参考文档:https://help.aliyun.com/document_detail/25514.html?spm=a2c4g.11186623.6.1216.39a5431dHF33HN ''' def __init__(self, access_key_id=None, access_key_secret=None): self.access_key = access_key_id if access_key_id else settings.ALIYUN_ACCESS_KEY_ID self.secret = access_key_secret if access_key_secret else settings.ALIYUN_ACCESS_KEY_SECRET self.client = None self.currentPage = [] self.regionList = [] self.instance_list_total = [] self.disk_list_total = [] self.TotalPageNum = 0 self.PageSize = 100 def __get_client(self, region_id='cn-hangzhou'): self.client = AcsClient(self.access_key, self.secret, region_id) def __do_action(self, request): try: request.set_accept_format('json') response = self.client.do_action_with_exception(request) except Exception as e: logger.error(e) return return json.loads(str(response, encoding='utf-8')) def __get_total_page_num(self, PageNum=1, PageSize=1): ''' 获取ECS总数,及当前页ECS列表 :param PageNum: 页ID :param PageSize: 页大小 :return: ''' request = DescribeInstancesRequest() request.set_PageNumber(PageNum) request.set_PageSize(PageSize) response = self.__do_action(request) if self.TotalPageNum != 0: ins_obj = response['Instances']['Instance'] self.instance_list_total.extend(ins_obj) return else: if int(response['TotalCount']) % self.PageSize != 0: self.TotalPageNum = int(response['TotalCount'] / self.PageSize) + 1 else: self.TotalPageNum = int(response['TotalCount'] / self.PageSize) return self.TotalPageNum def __get_disk_total_page_num(self, PageNum=1, PageSize=1): request = DescribeDisksRequest() request.set_PageSize(PageSize) request.set_PageNumber(PageNum) response = self.__do_action(request) if self.TotalPageNum != 0: ins_obj = response['Disks']['Disk'] self.disk_list_total.extend(ins_obj) return else: if int(response['TotalCount']) % self.PageSize != 0: self.TotalPageNum = int(response['TotalCount'] / self.PageSize) + 1 else: self.TotalPageNum = int(response['TotalCount'] / self.PageSize) return self.TotalPageNum def __get_ecs_of_region(self, region): ''' 按区获取 :param region: :return: ''' self.TotalPageNum = 0 self.__get_client(region) self.__get_total_page_num() # self.instance_list_obj.clear() list(map(self.__get_total_page_num, range(1, self.TotalPageNum + 1), [self.PageSize] * self.TotalPageNum)) return def __get_disk_of_region(self, region): ''' 按区获取硬盘 :param region: :return: ''' self.TotalPageNum = 0 self.__get_client(region) self.__get_disk_total_page_num() list(map(self.__get_disk_total_page_num, range(1, self.TotalPageNum + 1), [self.PageSize] * self.TotalPageNum)) return def translate(self, ins): ''' 将接口返回的数据翻译成库字段,便于批量插入 :param ins: :return: ''' instrance = {} try: instrance['disk'] = 0 instrance['hostname'] = ins['HostName'] if ins.get('NetworkInterfaces'): instrance['host_ip'] = ins['NetworkInterfaces']['NetworkInterface'][0]['PrimaryIpAddress'] if ins['PublicIpAddress'].get('IpAddress'): ip = ins['PublicIpAddress'].get('IpAddress', '') instrance['public_ip'] = ip[0] if ins.get('NetworkInterfaces'): instrance['mac'] = ins['NetworkInterfaces']['NetworkInterface'][0]['MacAddress'] instrance['os'] = ins['OSNameEn'] instrance['cpu'] = ins['Cpu'] instrance['memory'] = int(ins['Memory'] / 1024) instrance['sn'] = ins['SerialNumber'] instrance['instance_id'] = ins['InstanceId'] instrance['instance_name'] = ins['InstanceName'] instrance['create_time'] = ins['CreationTime'] instrance['expiration_time'] = ins['ExpiredTime'] instrance['zone'] = ins['ZoneId'] instrance['region'] = ins['RegionId'] instrance['status'] = ins['Status'] if ins['Status'] != 'Running': instrance['power_state'] = 'poweredOff' else: instrance['power_state'] = 'poweredOn' instrance['ostype'] = ins['OSType'] instrance['instancechargetype'] = ins['InstanceChargeType'] instrance['internetchargetype'] = ins['InternetChargeType'] instrance['salecycle'] = ins.get('SaleCycle', '') instrance['comment'] = ins.get('Description', '') instrance['specs'] = { 'name': ins['InstanceType'], 'family': ins['InstanceTypeFamily'], 'cpu': ins['Cpu'], 'memory': ins['Memory'] } except Exception as e: logger.error(e) return instrance def get_ecs(self): ''' 获取所有ECS信息 :return: ''' list(map(self.__get_ecs_of_region, self.regionList)) pool = Pool(50) ins_list_total = list(pool.map(self.translate, self.instance_list_total)) return ins_list_total def get_disk(self): ''' 获取所有硬盘信息 :return: ''' self.PageSize = 100 list(map(self.__get_disk_of_region, self.regionList)) return self.disk_list_total def get_region(self): ''' 获取账户支持的所有区域id :return: ''' self.__get_client() request = DescribeRegionsRequest() response = self.__do_action(request) region_list = response.get('Regions').get('Region') assert response is not None assert region_list is not None self.regionList = list(map(print_dict_key, region_list, ['RegionId'] * len(region_list))) return self.regionList |
如果想赏钱,可以用微信扫描下面的二维码,一来能刺激我写博客的欲望,二来好维护云主机的费用; 另外再次标注博客原地址 itnotebooks.com 感谢!
