背景:现在很多的公司的服务器都或多或少可以通过堡垒机上传一些离线文件,记录服务器各项指标的也有很多监控,例如Prometheus、Zabbix,Grafana、等等等。但是也有很多公司服务器只能限制内网访问,不能穿透,也不能代理。如果你是属于后者,你可以尝试用下面的代码来帮助你记录服务器在压测的时候的各项指标,并且写在excel里面。
注意:这里的CPU的使用率,我一直没有研究明白为啥和实际相差那么大,如果有大佬知道原因,请在文章末尾地方不吝赐教!
直接上代码吧!
# -*- coding: utf-8 -*-
# File: test_file.py
# Author: 1147127099@qq.com
# Date: 2024/6/21
import psutil
from openpyxl import Workbook
from time import sleep
import datetime
# 创建一个新的Excel工作簿和工作表
from openpyxl.styles import PatternFill
wb = Workbook()
ws = wb.active
ws.title = "System Monitoring"
# 写入标题行
headers = ["Time", "CPU Usage (%)", "Memory Used (%)", "Memory Free (%)", "Disk Read (MB/s)", "Disk Write (MB/s)",
"Network Sent (MB/s)", "Network Received (MB/s)"]
ws.append(headers)
# 设置标头的底色为橙色
fill = PatternFill(start_color="FFA500", end_color="FFA500", fill_type="solid")
for cell in ws[1]:
cell.fill = fill
# 初始化统计数据
disk_io_prev = psutil.disk_io_counters()
net_io_prev = psutil.net_io_counters()
# 记录开始时间
# start_time = datetime.datetime.now()
# 定义记录数据的函数
def record_system_stats():
global disk_io_prev, net_io_prev
# 获取系统当前时间
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 获取CPU使用率
cpu_usage = psutil.cpu_percent(interval=1)
# 获取内存使用情况
memory_info = psutil.virtual_memory()
memory_used = memory_info.used / (1024 ** 3)
memory_free = memory_info.free / (1024 ** 3)
memory_used_per = memory_used / memory_free
memory_free_per = 1 - memory_used_per
# 获取磁盘I/O情况
disk_io_current = psutil.disk_io_counters()
disk_read = (disk_io_current.read_bytes - disk_io_prev.read_bytes) / (1024 ** 2)
disk_write = (disk_io_current.write_bytes - disk_io_prev.write_bytes) / (1024 ** 2)
disk_io_prev = disk_io_current
# 获取网络I/O情况
net_io_current = psutil.net_io_counters()
net_sent = (net_io_current.bytes_sent - net_io_prev.bytes_sent) / (1024 ** 2)
net_recv = (net_io_current.bytes_recv - net_io_prev.bytes_recv) / (1024 ** 2)
net_io_prev = net_io_current
# 将数据添加到Excel表格
ws.append(
[str(current_time), f"{cpu_usage:.2f}" + " %", f"{memory_used_per * 100:.2f}" + " %",
f"{memory_free_per * 100:.2f}" + " %",
f"{disk_read*100:.2f}" + " MB/s", f"{disk_write*100:.2f}" + " MB/s", f"{net_sent*100:.2f}" + " MB/s",
f"{net_recv*100:.2f}" + " MB/s"])
# 循环记录系统状态信息,每秒一次
try:
while True:
record_system_stats()
wb.save("./system_monitoring.xlsx")
sleep(10)
except KeyboardInterrupt:
print("监控已停止,并保存数据到 system_monitoring.xlsx")
if __name__ == '__main__':
record_system_stats()
这里运行之后的结果打开之后,如下:
Time | CPU Usage (%) | Memory Used (%) | Memory Free (%) | Disk Read (MB/s) | Disk Write (MB/s) | Network Sent (MB/s) | Network Received (MB/s) |
2024-06-21 21:56:09 | 2.90 % | 46.23 % | 53.77 % | 0.00 MB/s | 20.70 MB/s | 46.20 MB/s | 1.11 MB/s |
2024-06-21 21:56:20 | 4.00 % | 46.46 % | 53.54 % | 105.86 MB/s | 601.56 MB/s | 151.17 MB/s | 23.06 MB/s |
2024-06-21 21:56:31 | 1.90 % | 46.41 % | 53.59 % | 31.25 MB/s | 208.59 MB/s | 198.50 MB/s | 43.11 MB/s |
2024-06-21 21:56:42 | 2.00 % |