Python实时监控系统性能:参数获取与文件存储全流程解析
2025.09.25 23:05浏览量:5简介:本文详细讲解如何使用Python获取系统基础性能参数(CPU、内存、磁盘、网络等),并将数据结构化写入文件。通过标准库和第三方工具实现跨平台监控,提供完整代码示例与异常处理方案。
Python获取系统基础性能参数实现写入文件
在系统运维和性能分析场景中,实时获取并记录系统基础性能参数是故障排查、容量规划和性能优化的关键环节。Python凭借其丰富的标准库和第三方生态,能够高效实现跨平台的系统监控与数据持久化。本文将系统阐述如何通过Python获取CPU、内存、磁盘、网络等核心性能指标,并将数据结构化写入文件,提供完整的实现方案与优化建议。
一、核心性能参数分类与获取方式
1. CPU使用率监控
CPU作为计算核心,其使用率直接反映系统负载。Python可通过以下方式获取:
psutil库:跨平台系统监控工具,支持获取CPU逻辑核心数、使用率、空闲时间等/proc/stat文件(Linux):解析内核提供的CPU时间统计wmi模块(Windows):通过WMI接口获取性能计数器
import psutildef get_cpu_info():# 获取CPU逻辑核心数cpu_count = psutil.cpu_count(logical=True)# 获取每颗CPU的使用率(间隔1秒采样)cpu_percent = psutil.cpu_percent(interval=1, percpu=True)# 获取系统全局CPU使用率global_percent = psutil.cpu_percent(interval=1)return {"cpu_cores": cpu_count,"percpu_usage": cpu_percent,"global_usage": global_percent}
2. 内存使用情况
内存监控需关注总量、已用、空闲和缓存等指标:
psutil.virtual_memory():获取物理内存信息psutil.swap_memory():获取交换分区信息memory_profiler:更精细的内存分析(需安装)
def get_memory_info():mem = psutil.virtual_memory()swap = psutil.swap_memory()return {"total_memory": mem.total,"available": mem.available,"used_percent": mem.percent,"swap_total": swap.total,"swap_used_percent": swap.percent}
3. 磁盘I/O监控
磁盘性能直接影响系统响应速度,需监控:
- 分区使用情况:
psutil.disk_usage() - 磁盘I/O统计:
psutil.disk_io_counters() - 文件系统信息:
os.statvfs()(Linux)
def get_disk_info():# 获取所有磁盘分区partitions = psutil.disk_partitions(all=False)disk_info = []for partition in partitions:usage = psutil.disk_usage(partition.mountpoint)io_stats = psutil.disk_io_counters(perdisk=True).get(partition.device.split('/')[-1], None)disk_info.append({"device": partition.device,"mountpoint": partition.mountpoint,"fstype": partition.fstype,"total": usage.total,"used": usage.used,"free": usage.free,"percent": usage.percent,# 转换为MB单位"read_bytes": io_stats.read_bytes / (1024**2) if io_stats else 0,"write_bytes": io_stats.write_bytes / (1024**2) if io_stats else 0})return disk_info
4. 网络流量统计
网络监控需捕获:
- 接口流量:
psutil.net_io_counters() - 连接状态:
psutil.net_connections() - 带宽使用率:需结合时间差计算
def get_network_info():net_io = psutil.net_io_counters()connections = psutil.net_connections(kind='inet')return {"bytes_sent": net_io.bytes_sent / (1024**2), # 转换为MB"bytes_recv": net_io.bytes_recv / (1024**2),"packets_sent": net_io.packets_sent,"packets_recv": net_io.packets_recv,"active_connections": len(connections)}
二、数据持久化方案
1. CSV文件存储
适合结构化数据存储,便于后续分析:
import csvfrom datetime import datetimedef write_to_csv(data, filename="system_metrics.csv"):# 如果是首次写入,创建文件并写入表头first_write = not os.path.exists(filename)with open(filename, mode='a', newline='') as file:writer = csv.writer(file)if first_write:writer.writerow(["timestamp", "cpu_global", "mem_used%", "disk_used%", "net_sent(MB)", "net_recv(MB)"])# 提取关键指标写入writer.writerow([datetime.now().isoformat(),data["cpu"]["global_usage"],data["memory"]["used_percent"],sum(disk["percent"] for disk in data["disk"])/len(data["disk"]) if data["disk"] else 0,data["network"]["bytes_sent"],data["network"]["bytes_recv"]])
2. JSON文件存储
适合嵌套数据结构,保留完整信息:
import jsondef write_to_json(data, filename="system_metrics.json"):# 读取现有数据(如果存在)existing_data = []if os.path.exists(filename):with open(filename, 'r') as f:try:existing_data = json.load(f)except json.JSONDecodeError:existing_data = []# 添加新记录new_entry = {"timestamp": datetime.now().isoformat(),"cpu": data["cpu"],"memory": data["memory"],"disk": data["disk"],"network": data["network"]}existing_data.append(new_entry)# 写入文件with open(filename, 'w') as f:json.dump(existing_data, f, indent=2)
3. 数据库存储(SQLite示例)
适合长期存储和复杂查询:
import sqlite3def init_db(db_path="system_metrics.db"):conn = sqlite3.connect(db_path)cursor = conn.cursor()cursor.execute('''CREATE TABLE IF NOT EXISTS metrics (id INTEGER PRIMARY KEY AUTOINCREMENT,timestamp TEXT NOT NULL,cpu_global REAL,mem_used_percent REAL,disk_avg_used_percent REAL,net_sent_mb REAL,net_recv_mb REAL)''')conn.commit()conn.close()def write_to_db(data, db_path="system_metrics.db"):conn = sqlite3.connect(db_path)cursor = conn.cursor()cursor.execute('''INSERT INTO metrics(timestamp, cpu_global, mem_used_percent, disk_avg_used_percent, net_sent_mb, net_recv_mb)VALUES (?, ?, ?, ?, ?, ?)''', (datetime.now().isoformat(),data["cpu"]["global_usage"],data["memory"]["used_percent"],sum(disk["percent"] for disk in data["disk"])/len(data["disk"]) if data["disk"] else 0,data["network"]["bytes_sent"],data["network"]["bytes_recv"]))conn.commit()conn.close()
三、完整实现示例
import osimport timeimport psutilfrom datetime import datetimeimport jsonimport csvimport sqlite3def collect_system_metrics():# CPU信息cpu_info = {"cpu_cores": psutil.cpu_count(logical=True),"percpu_usage": psutil.cpu_percent(interval=1, percpu=True),"global_usage": psutil.cpu_percent(interval=1)}# 内存信息mem = psutil.virtual_memory()swap = psutil.swap_memory()memory_info = {"total_memory": mem.total,"available": mem.available,"used_percent": mem.percent,"swap_total": swap.total,"swap_used_percent": swap.percent}# 磁盘信息partitions = psutil.disk_partitions(all=False)disk_info = []for partition in partitions:try:usage = psutil.disk_usage(partition.mountpoint)io_stats = psutil.disk_io_counters(perdisk=True).get(partition.device.split('/')[-1], None)disk_info.append({"device": partition.device,"mountpoint": partition.mountpoint,"fstype": partition.fstype,"total": usage.total,"used": usage.used,"free": usage.free,"percent": usage.percent,"read_bytes": io_stats.read_bytes / (1024**2) if io_stats else 0,"write_bytes": io_stats.write_bytes / (1024**2) if io_stats else 0})except PermissionError:continue# 网络信息net_io = psutil.net_io_counters()connections = psutil.net_connections(kind='inet')network_info = {"bytes_sent": net_io.bytes_sent / (1024**2),"bytes_recv": net_io.bytes_recv / (1024**2),"packets_sent": net_io.packets_sent,"packets_recv": net_io.packets_recv,"active_connections": len(connections)}return {"timestamp": datetime.now().isoformat(),"cpu": cpu_info,"memory": memory_info,"disk": disk_info,"network": network_info}def save_metrics(data, csv_file="metrics.csv", json_file="metrics.json", db_file="metrics.db"):# 初始化数据库if not os.path.exists(db_file):conn = sqlite3.connect(db_file)cursor = conn.cursor()cursor.execute('''CREATE TABLE metrics (id INTEGER PRIMARY KEY AUTOINCREMENT,timestamp TEXT NOT NULL,cpu_global REAL,mem_used_percent REAL,disk_avg_used_percent REAL,net_sent_mb REAL,net_recv_mb REAL)''')conn.commit()conn.close()# 写入CSVfirst_write = not os.path.exists(csv_file)with open(csv_file, mode='a', newline='') as file:writer = csv.writer(file)if first_write:writer.writerow(["timestamp", "cpu_global", "mem_used%", "disk_used%", "net_sent(MB)", "net_recv(MB)"])writer.writerow([data["timestamp"],data["cpu"]["global_usage"],data["memory"]["used_percent"],sum(disk["percent"] for disk in data["disk"])/len(data["disk"]) if data["disk"] else 0,data["network"]["bytes_sent"],data["network"]["bytes_recv"]])# 写入JSONexisting_data = []if os.path.exists(json_file):with open(json_file, 'r') as f:try:existing_data = json.load(f)except json.JSONDecodeError:existing_data = []existing_data.append(data)with open(json_file, 'w') as f:json.dump(existing_data, f, indent=2)# 写入数据库conn = sqlite3.connect(db_file)cursor = conn.cursor()cursor.execute('''INSERT INTO metrics(timestamp, cpu_global, mem_used_percent, disk_avg_used_percent, net_sent_mb, net_recv_mb)VALUES (?, ?, ?, ?, ?, ?)''', (data["timestamp"],data["cpu"]["global_usage"],data["memory"]["used_percent"],sum(disk["percent"] for disk in data["disk"])/len(data["disk"]) if data["disk"] else 0,data["network"]["bytes_sent"],data["network"]["bytes_recv"]))conn.commit()conn.close()if __name__ == "__main__":# 首次运行初始化数据库init_db()try:while True:metrics = collect_system_metrics()save_metrics(metrics)print(f"Metrics collected at {metrics['timestamp']}")time.sleep(60) # 每分钟采集一次except KeyboardInterrupt:print("Monitoring stopped by user")
四、优化建议与注意事项
- 性能影响:高频采集(如<1秒间隔)可能影响系统性能,建议根据需求调整采样频率
- 权限问题:Linux下获取某些磁盘信息可能需要root权限
- 跨平台兼容:使用
psutil可最大限度保证代码跨平台性,但某些高级功能可能平台受限 - 数据旋转:长期运行需实现日志轮转,避免单个文件过大
- 异常处理:添加完善的异常捕获,特别是文件操作和网络接口
- 可视化建议:可将数据导入Grafana或Python的Matplotlib/Plotly进行可视化分析
五、扩展应用场景
- 自动化运维:集成到Ansible/SaltStack等自动化工具中
- 容器监控:在Docker/Kubernetes环境中监控容器资源使用
- 性能基准测试:记录系统在不同负载下的性能表现
- 异常检测:通过分析历史数据建立基线,检测异常资源使用
通过本文的实现方案,开发者可以快速构建一个轻量级的系统监控工具,既能满足即时性能分析需求,也可作为更复杂监控系统的基础组件。

发表评论
登录后可评论,请前往 登录 或 注册