39-linux-cpu内存监控
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 HTML
line.render("show.html")
# Open the HTML file and add auto-refresh functionality
with open("show.html", "r") as file:
content = file.read()
# Add a meta tag to auto-refresh the page every 10 seconds
auto_refresh_content = f'''
<meta http-equiv="refresh" content="5">
{content}
'''
# Save the updated HTML with the refresh tag
with 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 = 1
for 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 support
httpd = 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 thread
import threading
server_thread = threading.Thread(target=run_server)
server_thread.daemon = True # Allow the server thread to exit when the main program exits
server_thread.start()
while True:
# Collect data and save it to Excel
collect_data()
# Generate the chart and HTML with auto-refresh
generate_html()
# Pause for some time to avoid infinite loop too fast and avoid server overload
time.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 usage
memory_usage = psutil.virtual_memory().percent # Memory usage
current_time = time.strftime("%H:%M:%S", time.localtime()) # Current time
# Append data to the CSV file
with 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 file
times, cpu_data, memory_data = [], [], []
with open("cpu_memory_data.csv", mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header
for row in reader:
times.append(row[0])
cpu_data.append(float(row[1]))
memory_data.append(float(row[2]))
# Generate the chart using pyecharts
line = (
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 file
line.render("index.html")
# Open the HTML file and add auto-refresh functionality
with open("index.html", "r") as file:
content = file.read()
# Add a meta tag to auto-refresh the page every 10 seconds
auto_refresh_content = f'''
<meta http-equiv="refresh" content="10">
{content}
'''
# Save the updated HTML with the refresh tag
with 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 support
httpd = 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 data
init_csv()
# Run the HTTP server in a separate thread
server_thread = threading.Thread(target=run_server)
server_thread.daemon = True # Allow the server thread to exit when the main program exits
server_thread.start()
while True:
# Collect data and save it to the CSV file
collect_data()
# Generate the chart and HTML with auto-refresh
generate_html()
# Pause for some time to avoid infinite loop too fast and avoid server overload
time.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
【励志篇】:
古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2020-01-15 Ubuntu 安装golang