本文目录导读:

我来为您提供监控内存使用率的脚本方案,支持Windows和Linux系统。
Linux 系统监控脚本
Bash 版本
#!/bin/bash
# 内存监控脚本
# 用法: ./memory_monitor.sh [阈值百分比]
THRESHOLD=${1:-80} # 默认阈值80%
while true; do
# 获取内存使用率(不包含缓存/buffer)
mem_usage=$(free | grep Mem | awk '{printf "%.2f", $3/$2 * 100}')
# 获取总内存和已用内存(GB)
total_mem=$(free -h | grep Mem | awk '{print $2}')
used_mem=$(free -h | grep Mem | awk '{print $3}')
# 当前时间
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$timestamp] 内存使用率: ${mem_usage}%"
echo "总内存: $total_mem, 已用: $used_mem"
# 超过阈值则报警
if (( $(echo "$mem_usage > $THRESHOLD" | bc -l) )); then
echo "⚠️ 警告: 内存使用率超过 ${THRESHOLD}%!"
# 获取占用内存前5的进程
echo "占用内存最多的进程:"
ps aux --sort=-%mem | head -6
# 可选:发送警报(需要配置邮件)
# echo "内存警报: 使用率 ${mem_usage}%" | mail -s "内存警报" admin@example.com
fi
echo "----------------------------------------"
sleep 5 # 每5秒检查一次
done
Python 版本(推荐)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import psutil
import time
import logging
from datetime import datetime
class MemoryMonitor:
def __init__(self, threshold=80, log_file=None):
self.threshold = threshold
self.setup_logging(log_file)
def setup_logging(self, log_file):
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file or 'memory_monitor.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def get_memory_info(self):
memory = psutil.virtual_memory()
return {
'total': memory.total,
'available': memory.available,
'used': memory.used,
'percent': memory.percent,
'total_gb': memory.total / (1024**3),
'used_gb': memory.used / (1024**3),
'available_gb': memory.available / (1024**3)
}
def get_top_processes(self, n=5):
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_percent']):
try:
processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
processes.sort(key=lambda x: x['memory_percent'], reverse=True)
return processes[:n]
def monitor(self, interval=5):
self.logger.info(f"内存监控启动 (阈值: {self.threshold}%)")
while True:
mem_info = self.get_memory_info()
# 记录当前状态
self.logger.info(
f"内存使用: {mem_info['percent']:.1f}% | "
f"已用: {mem_info['used_gb']:.2f}GB / {mem_info['total_gb']:.2f}GB | "
f"可用: {mem_info['available_gb']:.2f}GB"
)
# 检查是否超过阈值
if mem_info['percent'] > self.threshold:
self.logger.warning(f"⚠️ 内存警告: 使用率 {mem_info['percent']:.1f}% 超过阈值 {self.threshold}%")
# 获取占用内存最高的进程
top_procs = self.get_top_processes()
self.logger.warning("占用内存最高的进程:")
for proc in top_procs:
self.logger.warning(f" PID: {proc['pid']}, Name: {proc['name']}, Memory: {proc['memory_percent']:.1f}%")
time.sleep(interval)
if __name__ == "__main__":
# 使用示例
monitor = MemoryMonitor(threshold=80) # 设置阈值80%
monitor.monitor(interval=5) # 每5秒检查一次
Windows 系统监控脚本
PowerShell 版本
# Windows内存监控脚本
# 保存为 memory_monitor.ps1
param(
[int]$Threshold = 80,
[int]$Interval = 5
)
function Get-MemoryUsage {
$os = Get-CimInstance Win32_OperatingSystem
$totalMemory = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
$freeMemory = [math]::Round($os.FreePhysicalMemory / 1MB, 2)
$usedMemory = $totalMemory - $freeMemory
$percentUsed = [math]::Round(($usedMemory / $totalMemory) * 100, 2)
return @{
TotalGB = $totalMemory
UsedGB = $usedMemory
FreeGB = $freeMemory
PercentUsed = $percentUsed
}
}
function Get-TopProcesses {
param([int]$Count = 5)
Get-Process | Sort-Object WorkingSet64 -Descending |
Select-Object -First $Count |
Select-Object Id, ProcessName, @{Name="MemoryMB";Expression={[math]::Round($_.WorkingSet64 / 1MB, 2)}}
}
# 主循环
Write-Host "内存监控启动 (阈值: ${Threshold}%)" -ForegroundColor Green
while ($true) {
$memInfo = Get-MemoryUsage
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$timestamp] 内存使用率: $($memInfo.PercentUsed)%"
Write-Host "总内存: $($memInfo.TotalGB)GB, 已用: $($memInfo.UsedGB)GB, 可用: $($memInfo.FreeGB)GB"
if ($memInfo.PercentUsed -gt $Threshold) {
Write-Host "⚠️ 警告: 内存使用率超过 ${Threshold}%!" -ForegroundColor Red
Write-Host "占用内存最多的进程:" -ForegroundColor Yellow
Get-TopProcesses | Format-Table -AutoSize
}
Write-Host "----------------------------------------"
Start-Sleep -Seconds $Interval
}
Python + psutil 版本(跨平台)
"""
跨平台内存监控脚本
支持: Windows, Linux, macOS
"""
import psutil
import time
import platform
import logging
from datetime import datetime
class CrossPlatformMemoryMonitor:
def __init__(self, threshold=80, log_file=None):
self.threshold = threshold
self.os_type = platform.system()
self.setup_logging(log_file)
def setup_logging(self, log_file):
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file or f'memory_monitor_{self.os_type}.log'),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def monitor(self, interval=5):
self.logger.info(f"内存监控启动 (系统: {self.os_type}, 阈值: {self.threshold}%)")
while True:
# 获取内存信息
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# 格式化输出
mem_info = (
f"内存使用: {memory.percent:.1f}% | "
f"已用: {memory.used / (1024**3):.2f}GB / {memory.total / (1024**3):.2f}GB | "
f"可用: {memory.available / (1024**3):.2f}GB"
)
swap_info = (
f"交换内存: {swap.percent:.1f}% | "
f"已用: {swap.used / (1024**3):.2f}GB / {swap.total / (1024**3):.2f}GB"
)
self.logger.info(mem_info)
self.logger.info(swap_info)
# 检查阈值
if memory.percent > self.threshold:
self.logger.warning(f"⚠️ 内存使用率 {memory.percent:.1f}% 超过阈值 {self.threshold}%!")
# 获取占用内存最多的进程
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_percent']):
try:
processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
processes.sort(key=lambda x: x['memory_percent'], reverse=True)
self.logger.warning("Top 5 内存占用进程:")
for proc in processes[:5]:
self.logger.warning(f" PID: {proc['pid']}, Name: {proc['name']}, Memory: {proc['memory_percent']:.1f}%")
time.sleep(interval)
if __name__ == "__main__":
# 配置
monitor = CrossPlatformMemoryMonitor(
threshold=80, # 阈值
log_file='memory_monitor.log' # 日志文件
)
try:
monitor.monitor(interval=5) # 每5秒检查一次
except KeyboardInterrupt:
print("\n监控已停止")
安装和使用说明
Linux 系统
# 安装依赖 sudo apt-get install bc # 用于浮点数计算 # 赋予执行权限 chmod +x memory_monitor.sh # 运行 ./memory_monitor.sh 90 # 设置阈值为90% # 后台运行 nohup ./memory_monitor.sh > memory_output.log 2>&1 &
Python 版本安装
# 安装 psutil pip install psutil # 运行 python memory_monitor.py
Windows PowerShell
# 设置执行策略(如果需要) Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser # 运行 .\memory_monitor.ps1 -Threshold 90 -Interval 10 # 后台运行(后台作业) Start-Job -FilePath .\memory_monitor.ps1 -ArgumentList 90, 10
功能特点
- ✅ 实时监控:持续监控内存使用率
- ✅ 阈值报警:超过设定阈值自动报警
- ✅ 进程分析:显示占用内存最多的进程
- ✅ 日志记录:保存监控数据到日志文件
- ✅ 跨平台:支持 Windows、Linux、macOS
- ✅ 灵活配置:可调整监控间隔和阈值
- ✅ 错误处理:完善的异常处理机制
扩展建议
- 邮件/微信通知:添加警报通知功能
- 图表显示:使用 matplotlib 绘制内存使用趋势
- 自动清理:当内存过高时自动清理缓存
- Web界面:使用 Flask 搭建 Web 监控界面
- 数据库存储:保存历史数据到数据库
这个监控脚本可以作为系统运维的得力工具,根据实际需求选择适合的版本。