linux cpu内存监控
(1.)使用python脚本实现,启动后访问http://localhost:8000/即可查看cpu和内存使用情况
import psutil
import os
import xlwt
import xlrd
import time
from pyecharts.charts import Line
from http.server import SimpleHTTPRequestHandler
from socketserver import ThreadingTCPServer# 获取当前运行的pid
p1 = psutil.Process(os.getpid())# Function to generate the HTML file and add auto-refresh
def generate_html():# 获取折线图需要绘制的数据信息;data = xlrd.open_workbook("CPU.xls")table = data.sheets()[0]print(table.ncols)row1data = table.row_values(0)print(row1data) # ['列1', '列2', '列3', '列4']x = []y1 = []y2 = []for i in range(1, table.nrows):print(table.row_values(i))x.append(table.row_values(i)[0])y1.append(table.row_values(i)[1])y2.append(table.row_values(i)[2])# 实例化Line类为line对象, 并添加x和y对应的点;line = (Line().add_xaxis(x).add_yaxis("Cpu占有率散点图", y1).add_yaxis("内存占有率散点图", y2)# .set_global_opts(title_opts=opts.TitleOpts(title="Cpu占有率散点图")))# Render the chart to HTMLline.render("show.html")# Open the HTML file and add auto-refresh functionalitywith open("show.html", "r") as file:content = file.read()# Add a meta tag to auto-refresh the page every 10 secondsauto_refresh_content = f'''<meta http-equiv="refresh" content="5">{content}'''# Save the updated HTML with the refresh tagwith open("show.html", "w") as file:file.write(auto_refresh_content)# 获取当前数据并保存到Excel
def collect_data():myxls = xlwt.Workbook()sheet1 = myxls.add_sheet(u'CPU')sheet1.write(0, 0, '当前时间')sheet1.write(0, 1, 'cpu占用率')sheet1.write(0, 2, '内存占用率')i = 1for i in range(1, 10):b = psutil.cpu_percent(interval=1.0) # cpu占用率a = psutil.virtual_memory().percent # 内存占用率nowtime = time.strftime("%H:%M:%S", time.localtime())sheet1.write(i, 0, nowtime)print(nowtime)sheet1.write(i, 1, b)print(b)sheet1.write(i, 2, a)myxls.save('CPU.xls')i += 1# HTTP server to serve the show.html file
def run_server():handler = SimpleHTTPRequestHandler# Use ThreadingTCPServer for multi-threading supporthttpd = ThreadingTCPServer(('0.0.0.0', 8000), handler)print("Serving at http://localhost:8000")httpd.serve_forever()# Main loop
if __name__ == "__main__":# Run the HTTP server in a separate threadimport threadingserver_thread = threading.Thread(target=run_server)server_thread.daemon = True # Allow the server thread to exit when the main program exitsserver_thread.start()while True:# Collect data and save it to Excelcollect_data()# Generate the chart and HTML with auto-refreshgenerate_html()# Pause for some time to avoid infinite loop too fast and avoid server overloadtime.sleep(5) # adjust the sleep time as needed
(2.)改进版本,记录历史数据,并绘制折线图
import psutil
import os
import csv
import time
from pyecharts.charts import Line
from http.server import SimpleHTTPRequestHandler
from socketserver import ThreadingTCPServer
import threading# Create a CSV file to store all data
def init_csv():with open("cpu_memory_data.csv", mode='w', newline='') as file:writer = csv.writer(file)writer.writerow(["时间", "CPU占用率", "内存占用率"])# Function to record the data and append it to the CSV file
def collect_data():cpu_usage = psutil.cpu_percent(interval=1.0) # CPU usagememory_usage = psutil.virtual_memory().percent # Memory usagecurrent_time = time.strftime("%H:%M:%S", time.localtime()) # Current time# Append data to the CSV filewith open("cpu_memory_data.csv", mode='a', newline='') as file:writer = csv.writer(file)writer.writerow([current_time, cpu_usage, memory_usage])return current_time, cpu_usage, memory_usage# Function to generate the HTML file and add auto-refresh
def generate_html():# Read data from the CSV filetimes, cpu_data, memory_data = [], [], []with open("cpu_memory_data.csv", mode='r') as file:reader = csv.reader(file)next(reader) # Skip the headerfor row in reader:times.append(row[0])cpu_data.append(float(row[1]))memory_data.append(float(row[2]))# Generate the chart using pyechartsline = (Line().add_xaxis(times).add_yaxis("CPU占有率", cpu_data).add_yaxis("内存占有率", memory_data).set_global_opts(title_opts={"text": "CPU和内存占有率"}))# Render the chart to an HTML fileline.render("index.html")# Open the HTML file and add auto-refresh functionalitywith open("index.html", "r") as file:content = file.read()# Add a meta tag to auto-refresh the page every 10 secondsauto_refresh_content = f'''<meta http-equiv="refresh" content="10">{content}'''# Save the updated HTML with the refresh tagwith open("index.html", "w") as file:file.write(auto_refresh_content)# HTTP server to serve the index.html file
def run_server():handler = SimpleHTTPRequestHandler# Use ThreadingTCPServer for multi-threading supporthttpd = ThreadingTCPServer(('0.0.0.0', 8000), handler)print("Serving at http://127.0.0.1:8000/index.html")httpd.serve_forever()# Main loop
if __name__ == "__main__":# Initialize CSV file for storing datainit_csv()# Run the HTTP server in a separate threadserver_thread = threading.Thread(target=run_server)server_thread.daemon = True # Allow the server thread to exit when the main program exitsserver_thread.start()while True:# Collect data and save it to the CSV filecollect_data()# Generate the chart and HTML with auto-refreshgenerate_html()# Pause for some time to avoid infinite loop too fast and avoid server overloadtime.sleep(1) # adjust the sleep time as needed
(3.)使用easyNmon,推荐使用
https://github.com/mzky/easyNmon/releases // ./easyNmon & 启动
https://mzky.cc/post/9.html // 使用说明,安装后访问http://localhost:9999
(4.)使用原生的nmon写文件,使用web解析文件
./nmon -f -s 5 -c 60 -C -m // 采集数据,并写为文件// 下载release文件,访问http://localhost:10001/nmon/,上传文件解析
https://github.com/electricbubble/nmon-analyser-releases
参考链接
https://blog.csdn.net/weixin_42069644/article/details/104953486
https://archlinuxarm.org/packages/aarch64/nmon
https://nmon.sourceforge.io/pmwiki.php?n=Site.Download
https://www.cnblogs.com/titanstorm/p/14725029.html
https://github.com/aguther/nmonchart
https://github.com/nmonvisualizer/nmonvisualizer
https://www.cnblogs.com/arnoldlu/p/9462221.html
https://www.cnblogs.com/seamy/p/15649508.html
https://www.cnblogs.com/SunshineKimi/p/12182865.html