8-13 11 views
背景
做为乙方运维人员经常会有要提供服务器的资源利用率报表的时候,随便搞搞就要花半天时间,为此写了这么一个自动化的脚本,你可以将其集合到自己的运维平台上做个定时异步,废话不多说,上脚本
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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Eric Winn # @Email : eng.eric.winn@gmail.com # @Time : 2018/2/25 14:53 # @Version : 1.0 # @File : aliyun_monitor # @Software : PyCharm import os import logging import logging.config from aliyunsdkcore import client from aliyunsdkcms.request.v20170301 import QueryMetricListRequest import xlsxwriter import datetime, time import json from concurrent.futures import ProcessPoolExecutor class aliyun_monitor: def __init__(self, access_key, access_secret, region_ids, period, start_time, days_ago): self.project = '' self.metric = '' self.instrance = '' self.period = period self.start_time = start_time self.days_ago = days_ago self.clt = client.AcsClient(access_key, access_secret, region_ids) self.request = QueryMetricListRequest.QueryMetricListRequest() self.request.set_accept_format('json') def setattr(self, project, metric, instrance): self.project = project self.metric = metric self.instrance = instrance def factory(self): self.request.set_Project(self.project) self.request.set_Metric(self.metric) timestamp_start = int(time.mktime(time.strptime(self.start_time, "%Y-%m-%d %H:%M:%S"))) * 1000 self.request.set_StartTime(timestamp_start) self.request.set_Dimensions("{'instanceId':'" + self.instrance + "'}") self.request.set_Period(self.period) result = self.clt.do_action_with_exception(self.request) result = json.loads(result) result = result['Datapoints'] return result def run(self): result = self.factory() MaxUse = [] MinUse = [] average = [] UseTime = [] data = {} for mx in result: if self.metric == "diskusage_utilization" and mx['diskname'] == "/": continue MaxUse.append(float('%.2f' % mx['Average'])) UseTime.append(mx['timestamp']) MinUse.append(mx['Minimum']) average.append(mx['Average']) MaxUseTime = datetime.datetime.strftime( datetime.datetime.fromtimestamp(UseTime[MaxUse.index(max(MaxUse))] / 1000), "%Y-%m-%d %H:%M:%S") MinUseTime = datetime.datetime.strftime( datetime.datetime.fromtimestamp(UseTime[MinUse.index(min(MinUse))] / 1000), "%Y-%m-%d %H:%M:%S") AverageTime = datetime.datetime.strftime( datetime.datetime.fromtimestamp(UseTime[average.index(max(average))] / 1000), "%Y-%m-%d %H:%M:%S") data.update({ 'MaxUseTime': MaxUseTime, 'MinUseTime': MinUseTime, 'MaxUse': max(MaxUse), 'MinUse': min(MinUse), 'AverageTime': AverageTime, 'Average': max(average) }) return data class Excel: def __init__(self, fname): self.fname = fname self.workbook = xlsxwriter.Workbook(fname) self.worksheet = self.workbook.add_worksheet() self.format_body = self.workbook.add_format({ 'align': 'center', 'valign': 'vcenter', 'font_size': 12, 'bg_color': '#5ABAFE', 'border': 1 }) self.format_title = self.workbook.add_format({ 'bold': True, 'align': 'center', 'valign': 'vcenter', 'font_size': 20, 'bg_color': 'green', 'border': 1 }) self.format_buname = self.workbook.add_format({ 'bold': True, 'align': 'center', 'valign': 'vcenter', 'font_size': 15, 'bg_color': '#5ABAFE', 'border': 1 }) def write(self, col, data, key): if key == 'title': format = self.format_title self.worksheet.write_row(col, data, format) elif key == 'body': format = self.format_body self.worksheet.write_column(col, data, format) elif key == 'buname': format = self.format_buname for v in data: co = 'A' + str(col) + ':A' + str(col + 1) self.worksheet.merge_range(co, v, format) col += 2 def close(self): self.workbook.close() def read_config(conf): from ConfigParser import ConfigParser import codecs cfg = ConfigParser() cfg.readfp(codecs.open(conf, 'r', encoding='utf-8')) instanceIds = eval(cfg.get('aliyun_monitor', 'instanceIds')) metric_list = eval(cfg.get('aliyun_monitor', 'metric_list')) rds_metric_list = eval(cfg.get('aliyun_monitor', 'rds_metric_list')) lbs_metric_list = eval(cfg.get('aliyun_monitor', 'lbs_metric_list')) access_key = eval(cfg.get('aliyun_monitor', 'access_key')) access_secret = eval(cfg.get('aliyun_monitor', 'access_secret')) region_ids = eval(cfg.get('aliyun_monitor', 'region_ids')) days_ago = eval(cfg.get('aliyun_monitor', 'days_ago')) period = eval(cfg.get('aliyun_monitor', 'period')) title = eval(cfg.get('aliyun_monitor', 'title')) buname = eval(cfg.get('aliyun_monitor', 'buname')) start_time = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=days_ago), "%Y-%m-%d %H:%M:%S") return access_key, access_secret, region_ids, days_ago, period, title, buname, instanceIds, metric_list, rds_metric_list, lbs_metric_list, start_time def make_message(result, start_time, excel_file_name): from mail import mailFactory msgBody = u''' <table> <thead> <tr style="font-size:20px;background-color: green"> <th>主机</th> <th>CPU</th> <th>内存</th> <th>磁盘</th> <th>流量入</th> <th>流量出</th> </tr> </thead> <tbody> ''' for s in result: msgBody += u''' <tr> <td rowspan="2" style="background-color: #5ABAFE;font-size: 15px;font-weight: bold;text-align: center;vertical-align: middle"> %s </td> ''' % s['name'] for metric_value in s['value']: msgBody += u''' <td> 最高:%s </td> ''' % metric_value[0] msgBody += ''' </tr> <tr> ''' for metric_value in s['value']: msgBody += u''' <td> 最低:%s </td> ''' % metric_value[1] msgBody += u''' </tr> </tbody> </table> <a href="http://www.itnotebooks.com/public/data/%s" style="font-size: 20px;color: blue;" >下载到本地</a> ''' % excel_file_name header = {'Content-Type': 'text/html; charset="utf-8"', } mailFactory(['aaa@aaa.com','bbb@aaa.com'], u'XX项目阿里云监控月报' + ' (' + start_time + " ~ " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( time.time())) + ')', None, msgBody, header) if __name__ == '__main__': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) logging.config.fileConfig(os.path.join(BASE_DIR, "../conf/logs.cnf")) access_key, access_secret, region_ids, days_ago, period, title, buname, instanceIds, metric_list, rds_metric_list, lbs_metric_list, start_time = read_config( os.path.join(BASE_DIR, "../conf/aliyun.cnf")) excel_file_name = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d_%H%M%S") + '.xlsx' excel_file = os.path.join(BASE_DIR, "../data" + "/" + excel_file_name) alm = aliyun_monitor(access_key, access_secret, region_ids, period, start_time, days_ago) excel = Excel(excel_file) excel.write('A1', title, 'title') excel.write(2, buname, 'buname') result = [] v = 2 for inds in instanceIds: k = 66 metric_result = [] _metric_result = {} if instanceIds.index(inds) == 4: project_name = 'acs_slb' metric_list = lbs_metric_list elif instanceIds.index(inds) == 5: project_name = 'acs_rds' metric_list = rds_metric_list else: project_name = 'acs_ecs_dashboard' for mt in metric_list: if mt: alm.setattr(project_name, mt, inds) data = alm.run() if metric_list.index(mt) >= 3: MaxUse = data.get('MaxUse') MinUse = data['MinUse'] if MaxUse > 1024 and MaxUse < (1024 * 1024): MaxUse = '%.2fKb' % (MaxUse / 1024) elif MaxUse >= (1024 * 1024): MaxUse = '%.2fMb' % (MaxUse / 1024 / 1024) else: MaxUse = '%.2f' % MaxUse if MinUse > 1024 and MinUse < (1024 * 1024): MinUse = '%.2fKb' % (MinUse / 1024) elif MinUse >= (1024 * 1024): MinUse = '%.2fMb' % (MinUse / 1024 / 1024) else: MinUse = '%.2f' % MinUse else: if data: MaxUse = '%.2f%%' % data.get('MaxUse') MinUse = '%.2f%%' % data['MinUse'] else: MaxUse = None MinUse = None metric_one_result = [MaxUse, MinUse] excel.write(chr(k) + str(v), [u'最大:%s' % (MaxUse), u'最小:%s' % (MinUse)], 'body') k += 1 metric_result.append(metric_one_result) v += 2 _metric_result['name'] = buname[instanceIds.index(inds)] _metric_result['value'] = (metric_result) result.append(_metric_result) excel.close() make_message(result, start_time, excel_file_name) |
如果想赏钱,可以用微信扫描下面的二维码,一来能刺激我写博客的欲望,二来好维护云主机的费用; 另外再次标注博客原地址 itnotebooks.com 感谢!

你好,请问下aliyun.cnf文件的格式是什么样的
里面就是定义了一些基本信息,如access_key,access_secret等认证信息、区域、获取前多少天的数据、instranceId等
已经调试出来了 ,谢谢!