#!/usr/bin/env python # coding: utf-8 # author: Wang XiaoQiang ''' 功能介紹: 1、調用阿裡雲API,收集所有區域 ECS 信息 2、將需要的數據整理、生成 Excel 文檔 3、關於阿裡 sdk 的安裝,api 的調用請參考阿裡雲官 ...
#!/usr/bin/env python # coding: utf-8 # author: Wang XiaoQiang ''' 功能介紹: 1、調用阿裡雲API,收集所有區域 ECS 信息 2、將需要的數據整理、生成 Excel 文檔 3、關於阿裡 sdk 的安裝,api 的調用請參考阿裡雲官網 4、xlsxwriter 請參考這裡:http://xlsxwriter.readthedocs.org/ ''' import json, sys try: from termcolor import colored from xlsxwriter import workbook from aliyunsdkcore import client from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest except ImportError as e: print(colored('%s : %s' % ('Error', e), 'red')) exit(9) reload(sys) sys.setdefaultencoding('utf8') def get_sys_info(key, secret, zone): ''' 1、獲取該區域全部主機詳細信息 2、參數:cn-qingdao、cn-hangzhou、cn-beijing 等 ''' # 與阿裡雲建立有效連接 clt = client.AcsClient(key, secret, zone) # 獲取該區域全部實例詳細信息 request = DescribeInstancesRequest.DescribeInstancesRequest() # 將數據格式化成 json,預設為 XML request.set_accept_format('json') # 發起請求,獲取數據 result = json.loads(clt.do_action(request)).get('Instances').get('Instance') return result def format_data(data_info): ''' 從全部數據中整理出需要的數據 ''' result = [] for line in data_info: data = ( line.get('InstanceId'), line.get('ZoneId'), line.get('HostName'), line.get('InstanceName'), line.get('PublicIpAddress').get('IpAddress')[0], line.get('InnerIpAddress').get('IpAddress')[0], line.get('Cpu'), line.get('Memory'), line.get('InternetMaxBandwidthOut'), line.get('Status'), line.get('CreationTime'), line.get('ExpiredTime') ) result.append(data) return result def write_excel(file, data): ''' 1、設置 Excel 樣式 2、將數據寫入到 Excel 中 ''' # 生成 Excel 文件 work = workbook.Workbook(file) # 建立工作表,表名預設 worksheet = work.add_worksheet() # 設置字體加粗、字體大小 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, 30) worksheet.set_column(1, 1, 20) worksheet.set_column(2, 3, 28) worksheet.set_column(4, 5, 25) worksheet.set_column(6, 6, 12) worksheet.set_column(7, 9, 16) worksheet.set_column(10, 11, 25) # 定義表頭 title = ( '實例 ID', '所在區域', '主機名稱', '主機別名', '公網地址', '私網地址', 'CPU 核數', '記憶體大小 MB', '網路帶寬 MB', '運行狀態', '創建時間', '過期時間' ) 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, key, format_body) col+=1 work.close() def main(): key = 'Access Key Id' secret = 'Access Key Secret' zones = ['cn-beijing', 'cn-shanghai', 'cn-qingdao', 'cn-hangzhou'] filename = './aliyunSystemToExcel.xlsx' result = [] for zone in zones: info = get_sys_info(key, secret, zone) data = format_data(info) [ result.append(line) for line in data ] write_excel(filename, result) if __name__ == '__main__': main()