文档展示
万年历
AI 对话
Python 脚本
分组
python
(1)
📝 Python 脚本
+ 新建脚本
test1.py
2026-04-28 19:54
📋 复制
💾 保存
🗑️ 删除
📋 复制代码
import os import json import pandas as pd from collections import defaultdict def calculate_and_export_to_excel(base_backup_dir, target_date, output_dir="./metrics"): """ 读取某天的所有分钟备份数据,按机器聚合指标,导出为Excel :param base_backup_dir: 备份根目录(如 ./es_backup) :param target_date: 目标日期字符串,格式 "YYYY-MM-DD" :param output_dir: Excel文件输出目录 """ date_dir = os.path.join(base_backup_dir, target_date) if not os.path.exists(date_dir): print(f"❌ 目录不存在:{date_dir}") return # 按 hostname 聚合数据 host_metrics = defaultdict(lambda: { "cpuAvg_list": [], "memAvg_list": [] }) # 遍历当天所有分钟文件 print(f"开始读取 {target_date} 的备份数据...") for filename in os.listdir(date_dir): if not filename.endswith(".ndjson"): continue file_path = os.path.join(date_dir, filename) print(f"读取文件:{filename}") with open(file_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: # 解析 NDJSON 行(兼容你的格式) doc = json.loads(line) source = doc.get("_source", {}) hostname = source.get("hostname") cpu_avg = source.get("cpuAvg") mem_avg = source.get("memAvg") if hostname and cpu_avg is not None and mem_avg is not None: host_metrics[hostname]["cpuAvg_list"].append(cpu_avg) host_metrics[hostname]["memAvg_list"].append(mem_avg) except Exception as e: print(f"⚠️ 解析行失败:{line[:50]}... 错误:{e}") continue # 计算每台机器的最终指标 rows = [] for hostname, metrics in host_metrics.items(): cpu_list = metrics["cpuAvg_list"] mem_list = metrics["memAvg_list"] if not cpu_list or not mem_list: continue rows.append({ "hostname": hostname, "avg_cpuAvg": round(sum(cpu_list) / len(cpu_list), 2), "max_cpuAvg": max(cpu_list), "avg_memAvg": round(sum(mem_list) / len(mem_list), 2), "max_memAvg": max(mem_list), "data_count": len(cpu_list) }) # 生成DataFrame并导出Excel if not rows: print("❌ 没有有效数据,无法生成Excel") return df = pd.DataFrame(rows) os.makedirs(output_dir, exist_ok=True) excel_path = os.path.join(output_dir, f"{target_date}_host_metrics.xlsx") # 写入Excel,自动调整列宽 with pd.ExcelWriter(excel_path, engine="openpyxl") as writer: df.to_excel(writer, sheet_name="机器指标统计", index=False) worksheet = writer.sheets["机器指标统计"] for col in worksheet.columns: max_len = max(len(str(cell.value)) for cell in col) worksheet.column_dimensions[col[0].column_letter].width = max_len + 2 print(f"\n✅ Excel报表已生成:{excel_path}") return excel_path # -------------------------- # 使用示例 # -------------------------- if __name__ == "__main__": # 配置你的备份目录和目标日期 backup_dir = "./es_backup" # 你的备份根目录 target_date = "2026-04-17" # 要统计的日期 calculate_and_export_to_excel(backup_dir, target_date)