在企业级系统运维和性能优化场景中,手动排查系统瓶颈指标效率低且容易出错,用Python编写自动化脚本可以高效完成指标采集、瓶颈识别和报告生成全流程。这种脚本通常不需要复杂的架构,按照功能拆分模块就能满足大部分日常使用需求。

脚本整体结构划分
一个完整的自动识别系统瓶颈并生成性能报告的Python脚本,通常可以分为四个核心模块,各模块职责清晰,方便后续扩展维护:
- 指标采集模块:负责采集系统各类性能指标原始数据
- 瓶颈识别模块:基于预设规则分析采集到的数据,定位异常指标
- 报告生成模块:将识别结果整理成可读的结构化报告
- 主调度模块:串联各个模块,控制脚本整体执行流程
各模块具体实现逻辑
指标采集模块
该模块可以使用psutil库获取系统基础性能数据,覆盖CPU、内存、磁盘、网络四个核心维度,采集时可以根据需求设置采集周期和采样次数,保证数据的准确性。
import psutil
import time
def collect_metrics(sample_count=3, interval=1):
"""采集系统性能指标,返回各指标的采样列表"""
cpu_usage = []
mem_usage = []
disk_io = []
net_io = []
for i in range(sample_count):
# 采集CPU使用率,间隔1秒
cpu_usage.append(psutil.cpu_percent(interval=1))
# 采集内存使用率
mem_usage.append(psutil.virtual_memory().percent)
# 采集磁盘IO读写速率,单位MB/s
disk_stat = psutil.disk_io_counters()
disk_io.append({
"read_mb": disk_stat.read_bytes / 1024 / 1024,
"write_mb": disk_stat.write_bytes / 1024 / 1024
})
# 采集网络收发速率,单位MB/s
net_stat = psutil.net_io_counters()
net_io.append({
"send_mb": net_stat.bytes_sent / 1024 / 1024,
"recv_mb": net_stat.bytes_recv / 1024 / 1024
})
time.sleep(interval)
return {
"cpu": cpu_usage,
"mem": mem_usage,
"disk": disk_io,
"net": net_io
}
瓶颈识别模块
该模块需要提前预设各指标的阈值,比如CPU使用率超过80%视为异常,内存使用率超过85%视为异常,然后对比采集到的指标数据,标记出超出阈值的指标,同时可以计算平均值、峰值等辅助分析的数据。
def identify_bottlenecks(metrics, thresholds):
"""识别性能瓶颈,返回异常指标列表"""
bottleneck_list = []
# 处理CPU指标
cpu_avg = sum(metrics["cpu"]) / len(metrics["cpu"])
cpu_max = max(metrics["cpu"])
if cpu_avg > thresholds["cpu_avg"] or cpu_max > thresholds["cpu_max"]:
bottleneck_list.append({
"type": "CPU",
"detail": f"平均使用率{cpu_avg}%,峰值{cpu_max}%,超过阈值"
})
# 处理内存指标
mem_avg = sum(metrics["mem"]) / len(metrics["mem"])
mem_max = max(metrics["mem"])
if mem_avg > thresholds["mem_avg"] or mem_max > thresholds["mem_max"]:
bottleneck_list.append({
"type": "内存",
"detail": f"平均使用率{mem_avg}%,峰值{mem_max}%,超过阈值"
})
# 处理磁盘IO指标,这里简单判断读写速率是否超过阈值
disk_read_avg = sum([d["read_mb"] for d in metrics["disk"]]) / len(metrics["disk"])
if disk_read_avg > thresholds["disk_read"]:
bottleneck_list.append({
"type": "磁盘IO",
"detail": f"平均读取速率{disk_read_avg}MB/s,超过阈值"
})
return bottleneck_list
报告生成模块
报告生成可以选择生成文本文件、HTML文件或者Excel文件,这里以生成HTML报告为例,将采集到的原始数据和识别出的瓶颈整合到HTML模板中,方便查看和分享。
def generate_report(metrics, bottlenecks, report_path):
"""生成HTML格式的性能报告"""
html_content = """
<html>
<head>
<meta charset="utf-8">
<title>系统性能分析报告</title>
<style>
table { border-collapse: collapse; width: 80%; margin: 20px 0; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
th { background-color: #f5f5f5; }
.bottleneck { color: red; font-weight: bold; }
</style>
</head>
<body>
<h1>系统性能分析报告</h1>
<h2>原始指标数据</h2>
<table>
<tr>
<th>指标类型</th>
<th>采样值</th>
</tr>
<tr>
<td>CPU使用率(%)</td>
<td>{cpu_data}</td>
</tr>
<tr>
<td>内存使用率(%)</td>
<td>{mem_data}</td>
</tr>
</table>
<h2>识别到的瓶颈</h2>
{bottleneck_content}
</body>
</html>
"""
# 填充指标数据
cpu_data = ",".join([str(v) for v in metrics["cpu"]])
mem_data = ",".join([str(v) for v in metrics["mem"]])
# 填充瓶颈内容
if not bottlenecks:
bottleneck_content = "<p>未识别到性能瓶颈</p>"
else:
bottleneck_content = "<ul>"
for item in bottlenecks:
bottleneck_content += f"<li class='bottleneck'>{item['type']}: {item['detail']}</li>"
bottleneck_content += "</ul>"
# 替换模板中的占位符
final_html = html_content.format(
cpu_data=cpu_data,
mem_data=mem_data,
bottleneck_content=bottleneck_content
)
with open(report_path, "w", encoding="utf-8") as f:
f.write(final_html)
return report_path
主调度模块
主调度模块负责整合前面三个模块,设置好阈值参数,控制整个脚本的执行顺序,同时可以添加日志记录,方便排查脚本运行过程中的问题。
def main():
# 预设阈值,可根据实际业务调整
thresholds = {
"cpu_avg": 70,
"cpu_max": 80,
"mem_avg": 75,
"mem_max": 85,
"disk_read": 100
}
# 1. 采集指标
print("开始采集系统性能指标...")
metrics = collect_metrics(sample_count=3, interval=1)
# 2. 识别瓶颈
print("开始识别性能瓶颈...")
bottlenecks = identify_bottlenecks(metrics, thresholds)
# 3. 生成报告
report_path = "system_performance_report.html"
print("开始生成性能报告...")
generate_report(metrics, bottlenecks, report_path)
print(f"报告生成完成,路径:{report_path}")
if __name__ == "__main__":
main()
脚本扩展建议
上述基础结构可以根据实际需求扩展,比如添加更多指标采集项,支持自定义采集周期,或者将报告发送邮件通知相关人员,还可以对接监控系统,实现定时自动执行分析任务。如果需要适配容器环境,还可以增加容器相关指标的采集逻辑,让脚本能覆盖更多使用场景。