我不需要用企业微信进行通知,我只需要最后输出为execl,并且请将获取普罗米修斯数据的方式改为从api获取,请一步步协助我完成这个代码开发工作,并最终实现功能
时间: 2025-02-04 11:24:42 浏览: 25
好的,我们可以逐步修改代码以满足您的需求。以下是具体步骤:
### 步骤 1: 定义函数从 Prometheus API 获取数据
首先,我们需要编写一个函数来从 Prometheus API 获取监控数据。我们将使用 `requests` 库来发送 HTTP 请求。
```python
import requests
import json
def get_prometheus_data(query, start, end, step):
url = "http://127.0.0.1:9090/api/v1/query_range"
params = {
'query': query,
'start': start,
'end': end,
'step': step
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to fetch data from Prometheus: {response.status_code}")
```
### 步骤 2: 定义需要查询的指标
您已经定义了需要查询的指标列表,我们保留这一部分不变。
```python
def rds_metrics_list():
return {
'up': '状态',
'rds001_cpu_util': 'CPU使用率(%)',
'rds002_mem_util': '内存使用率(%)',
'rds003_iops': 'iops',
'rds004_bytes_in': '网络流量入(Bytes)',
'rds005_bytes_out': '网络流量出(Bytes)',
'rds008_qps': 'QPS',
'rds009_tps': 'TPS',
'rds081_vm_ioutils': 'io使用率(%)',
'rds047_disk_total_size': '磁盘总大小(G)',
'rds048_disk_used_size': '磁盘使用(G)',
'mysql_global_status_threads_connected': '当前连接数',
'mysql_global_variables_max_connections': '最大连接数',
}
```
### 步骤 3: 获取当前时间和构造查询参数
我们需要获取当前时间并构造查询的时间范围。
```python
import datetime
curhour = -17 # 默认给-17 当前时间是-8.1
check_time_day = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%Y-%m-%d")
check_time_hour = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%H:%M")
start_time = f"{check_time_day}T{check_time_hour}:00Z"
end_time = f"{check_time_day}T{check_time_hour}:15Z"
step = "15s"
```
### 步骤 4: 获取数据并处理
接下来,我们需要遍历每个指标,从 Prometheus 获取数据,并将其存储在一个字典中。
```python
import pandas as pd
def process_prometheus_data(metrics_list, start_time, end_time, step):
data = []
for metric in metrics_list:
result = get_prometheus_data(metric, start_time, end_time, step)
for key in result['data']['result']:
instance = key['metric']['instance']
value = key['values'][0][1]
entry = {'instance': instance, metrics_list[metric]: value}
data.append(entry)
return data
metrics_list = rds_metrics_list()
data = process_prometheus_data(metrics_list, start_time, end_time, step)
df = pd.DataFrame(data)
```
### 步骤 5: 将数据写入 Excel 文件
最后,我们将数据写入 Excel 文件。
```python
def write_to_excel(df, file_path):
df.to_excel(file_path, index=False)
check_file_dir = 'check_files'
if not os.path.exists(check_file_dir):
os.makedirs(check_file_dir)
file_name = f"monitoring_{check_time_day}_{check_time_hour}.xlsx"
file_path = os.path.join(check_file_dir, file_name)
write_to_excel(df, file_path)
print(f"Data written to {file_path}")
```
### 最终完整代码
将以上所有部分组合在一起,得到完整的代码如下:
```python
import requests
import json
import pandas as pd
import os
import datetime
def get_prometheus_data(query, start, end, step):
url = "http://127.0.0.1:9090/api/v1/query_range"
params = {
'query': query,
'start': start,
'end': end,
'step': step
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to fetch data from Prometheus: {response.status_code}")
def rds_metrics_list():
return {
'up': '状态',
'rds001_cpu_util': 'CPU使用率(%)',
'rds002_mem_util': '内存使用率(%)',
'rds003_iops': 'iops',
'rds004_bytes_in': '网络流量入(Bytes)',
'rds005_bytes_out': '网络流量出(Bytes)',
'rds008_qps': 'QPS',
'rds009_tps': 'TPS',
'rds081_vm_ioutils': 'io使用率(%)',
'rds047_disk_total_size': '磁盘总大小(G)',
'rds048_disk_used_size': '磁盘使用(G)',
'mysql_global_status_threads_connected': '当前连接数',
'mysql_global_variables_max_connections': '最大连接数',
}
curhour = -17 # 默认给-17 当前时间是-8.1
check_time_day = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%Y-%m-%d")
check_time_hour = (datetime.datetime.now() + datetime.timedelta(hours=curhour)).strftime("%H:%M")
start_time = f"{check_time_day}T{check_time_hour}:00Z"
end_time = f"{check_time_day}T{check_time_hour}:15Z"
step = "15s"
def process_prometheus_data(metrics_list, start_time, end_time, step):
data = []
for metric in metrics_list:
result = get_prometheus_data(metric, start_time, end_time, step)
for key in result['data']['result']:
instance = key['metric']['instance']
value = key['values'][0][1]
entry = {'instance': instance, metrics_list[metric]: value}
data.append(entry)
return data
metrics_list = rds_metrics_list()
data = process_prometheus_data(metrics_list, start_time, end_time, step)
df = pd.DataFrame(data)
def write_to_excel(df, file_path):
df.to_excel(file_path, index=False)
check_file_dir = 'check_files'
if not os.path.exists(check_file_dir):
os.makedirs(check_file_dir)
file_name = f"monitoring_{check_time_day}_{check_time_hour}.xlsx"
file_path = os.path.join(check_file_dir, file_name)
write_to_excel(df, file_path)
print(f"Data written to {file_path}")
```
运行上述代码后,您将会在 `check_files` 目录下看到一个包含监控数据的 Excel 文件。希望这能满足您的需求!如果有任何问题或需要进一步的帮助,请随时告诉我。
阅读全文
相关推荐














