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
|
# -*- coding: utf-8 -*-
# @Time : 2023/4/11 17:17
# @Author : 南宫乘风
# @Email : 1794748404@qq.com
# @File : ecs_monitor.py
# @Software: PyCharm
# 产品排列表 https://cms.console.aliyun.com/metric-meta/acs_ecs_dashboard/ecs?spm=a2c4g.163515.0.0.27c776abvQGocz
# 获取所有机器 https://next.api.aliyun.com/api/Cms/2019-01-01/DescribeMonitoringAgentHosts?params={}&tab=DEBUG
# 获取所有redsi https://next.api.aliyun.com/api/R-kvstore/2015-01-01/DescribeInstancesOverview?spm=a2c4g.473769.0.i0&lang=PYTHON¶ms={%22RegionId%22:%22cn-shenzhen%22}&tab=DEBUG
import json
import sys
from typing import List
from alibabacloud_cms20190101.client import Client as Cms20190101Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cms20190101 import models as cms_20190101_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
class Sample:
def __init__(self):
pass
@staticmethod
def create_client(
access_key_id: str,
access_key_secret: str,
) -> Cms20190101Client:
"""
使用AK&SK初始化账号Client
@param access_key_id:
@param access_key_secret:
@return: Client
@throws Exception
"""
config = open_api_models.Config(
# 必填,您的 AccessKey ID,
access_key_id=access_key_id,
# 必填,您的 AccessKey Secret,
access_key_secret=access_key_secret
)
# 访问的域名
config.endpoint = f'metrics.ap-southeast-1.aliyuncs.com'
return Cms20190101Client(config)
@staticmethod
def main(parameter):
# 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html
client = Sample.create_client('xxxx', 'xxx')
describe_metric_top_request = cms_20190101_models.DescribeMetricTopRequest(
period='2592000',
namespace='acs_kvstore',
metric_name=parameter,
orderby='Average',
start_time='2023-03-12 00:00:00',
end_time='2023-04-11 00:00:00',
length='100',
)
runtime = util_models.RuntimeOptions()
try:
# 复制代码运行请自行打印 API 的返回值
data = client.describe_metric_top_with_options(describe_metric_top_request, runtime)
return data
except Exception as error:
# 如有需要,请打印 error
UtilClient.assert_as_string(error.message)
def get_host():
global host_list
# 打开 host.json 文件
with open('redis.json', 'r', encoding='utf-8') as f:
# 读取文件中的 JSON 数据
data = json.load(f)
# 输出读取到的数据
print(data)
host_list = data['body']["Instances"]
host_list = [{k: v for k, v in d.items() if
k not in ('ArchitectureType', 'EngineVersion', 'EndTime', 'ResourceGroupId', 'ZoneId', 'CreateTime',
'VSwitchId', 'InstanceClass', 'ConnectionDomain', 'VpcId', 'ChargeType', 'NetworkType',
'InstanceStatus', 'RegionId', 'InstanceType', 'SecondaryZoneId')}
for d in
host_list]
return host_list
def ecs_dashboard(parameter):
data_ecs = Sample.main(parameter)
response_dict = data_ecs.body.to_map()
data_Datapoints = json.loads(response_dict["Datapoints"])
return data_Datapoints
def set_workbook(host_list_data):
data = {
'Capacity': 256,
'InstanceId': 'r-xxxxx',
'InstanceName': '大数据',
'PrivateIp': 'xxxxxxxx',
'Memory_Average': 15.719
}
# 新建一个 Workbook 对象
wb = Workbook()
# 获取第一个 sheet
ws = wb.active
# 获取最大行数
max_row = ws.max_row
# 设置表头
headers = list(data.keys())
for i, header in enumerate(headers, start=1):
ws.cell(row=1, column=i).value = header
# 写入数据
for row_data in host_list_data:
# 写入数据
max_row += 1
for i, header in enumerate(row_data.keys(), start=1):
column_letter = get_column_letter(i)
cell_address = '{}{}'.format(column_letter, max_row)
ws[cell_address] = row_data[header]
# 保存文件
wb.save('Redis_服务器资源.xlsx')
if __name__ == '__main__':
host_list_data = get_host()
redis_monitor_list_Memory = ecs_dashboard("StandardMemoryUsage")
# 匹配CPU
# 遍历 list2,匹配 instanceId 并添加 Average 值到 list1 的对应字典中
for d2 in redis_monitor_list_Memory:
for d1 in host_list_data:
if d1['InstanceId'] == d2['instanceId']:
d1['Memory_Average'] = d2['Average']
# # 输出更新后的 list1
lst_sorted = sorted(host_list_data, key=lambda x: x['Memory_Average'], reverse=True)
print(host_list_data)
set_workbook(lst_sorted)
|