39-linux-cpu内存监控

news/2025/1/15 18:14:51/文章来源:https://www.cnblogs.com/tomtellyou/p/18673576

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/869719.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python Playwright学习笔记(一)

一、简介 1.1Playwright 是什么? 它是微软在 2020 年初开源的新一代自动化测试工具,其功能和 selenium 类似,都可以驱动浏览器进行各种自动化操作。 1.2、特点是什么支持当前所有的主流浏览器,包括 chrome、edge、firefox、safari; 支持跨平台多语言:支持Windows、Linux、…

智能驾驶数据采集回注测评工具 - ARS

在数据驱动智能驾驶的时代背景下,开发者们总结了一条适用于智能驾驶的数据闭环开发流程,这条开发线路大致包括实车数据采集->数据存储->数据处理->数据分析->数据标注->模型训练->仿真测试->实车测试->部署发布等关键环节,通过不断开发迭代,逐步完…

2025.1.15 学习

2025.1.15 学习 api开放平台 我们希望在后端使用Http请求调用接口,应该怎么做呢 可以用Hutool工具库中的Http请求工具类,使用如下: public class ApiClient {public String getNameByGet(String name){HashMap<String, Object> paramMap = new HashMap<>();para…

2024龙信年终技术考核

1. 分析手机备份文件,该机主的QQ号为?(标准格式:123) 看了下,备份里没有QQ,但是有微信,所以应该是微信绑定的QQ号(早期微信推广时可以用QQ直接注册登录)经过测试,对应的是这个结果为1203494553 2. 分析手机备份文件,该机主的微信号为?(标准格式:abcdefg)结果为…

Dex文件结构】ReadDex解析器实现

# APP加壳脱壳 # DEX文件结构 近期学习DEX文件结构为学习APP加壳脱壳打基础,自实现了一个简易的DEX解析器加深理解。DEX文件结构整体看不复杂,深究时发现DexCLassDef结构非常复杂,编码的数据结构,嵌套和指向关系。本文作为近期学习的一个阶段总结以及知识分享,后期再完…

记录---浏览器多窗口通信有效实践总结

🧑‍💻 写在开头 点赞 + 收藏 === 学会🤣🤣🤣如何跨越不同窗口通信 在现代 Web 开发中,多个窗口或标签页之间的通信成为了越来越常见的需求,尤其是在应用需要同步数据、共享状态或进行实时更新的场景中。不同窗口间的通信方式有很多种,选择合适的方式可以大大提高…

python 按时间戳删除3232数组的前2列和后9列

还是雨滴谱文件,这次尝试批量处理 首先处理1个单独的txt文件#!usr/bin/env python # -*- coding:utf-8 _*- """@author:Suyue @file:raindrop.py @time:2025/01/15 {DAY} @desc: """ import numpy as np import redef process_file(input_file,…

电源中TL431及光耦的实战运用

首先了解一下TL431的基本原理;由一个运放及三极管组成;运放的应用前文略有几笔,此处未加反馈,运放只需要同相端与反相端做差在输出对应电压即可,而三极管是电压驱动;当VREF>2.5V即同相端大于反相端,输出正电压,三极管导通,当VREF<2.5V即同相端小于反相端,输出负…

在OERV也可以玩MC(下)

话接上回,上期讲述了在OERV安装HMCL的历程,这期讲讲HMCL的打包。Show openEuler:24.09 / HMCL - 开源软件构建与测试。在这个网站里,可以看到有好几个文件,这些都跟HMCL打包有关。 第一个是_service文件,这个文件用于从特定仓库里面拉取代码文件到当前平台,可以看见每个文…

JS-38 对象概述

什么是对象?对象(object)是JavaScript语言的核心概念,也是最重要的数据类型 简单说,对象就是一组“键对值”(key-value)的合集,是一种无序的复合数据集合 var user={ name:zifuchuan, age:13 };对象的每一个键名又称为属性(property),它的“键值”可以是任何数据类型…

第八届工业信息安全技能大赛全国复赛snake_wp

pwn题 snake writeup多少有点不自信,太久没做题,看到题都有点怕怕的这个程序是一个贪食蛇游戏,主程序如下: __int64 __fastcall main_4015A5(__int64 a1, __int64 a2) {int v2; // edxint v3; // ecxint v4; // er8int v5; // er9int v7; // [rsp+Ch] [rbp-4h]sub_400B6D()…