自动清理内存缓存的脚本怎么写

wen 实用脚本 1

本文目录导读:

自动清理内存缓存的脚本怎么写

  1. Linux 系统脚本
  2. Windows 系统脚本
  3. macOS 系统脚本
  4. 通用Python脚本 (跨平台)
  5. 使用示例和注意事项

Linux 系统脚本

基础版本 (清理页缓存、目录项和inode)

#!/bin/bash
# 文件名: clean_memory_cache.sh
echo "当前内存使用情况:"
free -h
# 清理之前需要同步文件系统,确保数据写入磁盘
sync
# 清理页缓存 (PageCache)
echo 1 > /proc/sys/vm/drop_caches
# 清理目录项和inode
echo 2 > /proc/sys/vm/drop_caches
# 清理所有缓存 (页缓存、目录项、inode)
echo 3 > /proc/sys/vm/drop_caches
echo "缓存已清理完成!"
echo "清理后内存使用情况:"
free -h

安全版本 (带权限检查和日志)

#!/bin/bash
# 文件名: safe_clean_cache.sh
LOG_FILE="/var/log/clean_cache.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
  echo "$DATE - 错误: 请使用root权限运行此脚本" | tee -a $LOG_FILE
  exit 1
fi
# 获取清理前的内存使用
echo "$DATE - 开始清理缓存" | tee -a $LOG_FILE
BEFORE=$(free -h | grep Mem)
echo "清理前: $BEFORE" | tee -a $LOG_FILE
# 同步并清理
sync
echo 3 > /proc/sys/vm/drop_caches
# 获取清理后的内存使用
AFTER=$(free -h | grep Mem)
echo "清理后: $AFTER" | tee -a $LOG_FILE
echo "$DATE - 缓存清理完成" | tee -a $LOG_FILE

自动定时清理 (添加到crontab)

#!/bin/bash
# 每天凌晨2点自动清理
# 添加到 crontab: crontab -e
# 0 2 * * * /root/scripts/safe_clean_cache.sh
# 或者使用此脚本自动设置crontab
CRON_JOB="0 2 * * * /root/scripts/safe_clean_cache.sh"
(crontab -l 2>/dev/null | grep -v "$CRON_JOB"; echo "$CRON_JOB") | crontab -
echo "已设置每天凌晨2点自动清理缓存"

Windows 系统脚本

PowerShell 脚本

# 文件名: Clean-MemoryCache.ps1
Write-Host "正在清理内存缓存..." -ForegroundColor Green
# 方法1: 使用系统API清理
$Method = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# 方法2: 使用WMI清理工作集
$Processes = Get-Process
foreach ($Process in $Processes) {
    try {
        $Process.Refresh()
        [System.GC]::Collect()
    } catch {
        # 忽略无法访问的进程
    }
}
# 方法3: 清理专用工作集
$OS = Get-WmiObject Win32_OperatingSystem
$OS.FreePhysicalMemory
Write-Host "内存缓存清理完成!" -ForegroundColor Green
Write-Host "当前可用内存: $(Get-WmiObject Win32_OperatingSystem | Select-Object FreePhysicalMemory)" -ForegroundColor Cyan

批处理脚本 (.bat)

@echo off内存缓存清理工具
echo 正在清理Windows内存缓存...
echo.
:: 清理内存工作集
powershell -Command "& {[System.GC]::Collect(); [System.GC]::WaitForPendingFinalizers(); Write-Host '缓存清理完成!' -ForegroundColor Green}"
:: 显示内存信息
wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /format:table
echo.
echo 清理完成!
pause

macOS 系统脚本

#!/bin/bash
# 文件名: clean_mac_cache.sh
echo "当前内存使用情况:"
vm_stat
# 清理内存缓存 (需要root权限)
sudo purge
echo "缓存已清理完成!"
echo "清理后内存使用情况:"
vm_stat | head -10

通用Python脚本 (跨平台)

#!/usr/bin/env python3
# 文件名: clean_cache.py
import os
import platform
import subprocess
import sys
def clean_linux_cache():
    """清理Linux系统缓存"""
    if os.geteuid() != 0:
        print("错误: 需要root权限")
        return False
    os.system('sync')
    os.system('echo 3 > /proc/sys/vm/drop_caches')
    print("Linux缓存清理完成")
    return True
def clean_windows_cache():
    """清理Windows系统缓存"""
    import ctypes
    # 使用Windows API清理
    try:
        ctypes.windll.kernel32.SetProcessWorkingSetSize(
            ctypes.windll.kernel32.GetCurrentProcess(), -1, -1
        )
        print("Windows缓存清理完成")
        return True
    except Exception as e:
        print(f"清理失败: {e}")
        return False
def clean_mac_cache():
    """清理macOS系统缓存"""
    try:
        subprocess.run(['sudo', 'purge'], check=True)
        print("macOS缓存清理完成")
        return True
    except subprocess.CalledProcessError:
        print("清理失败,需要root权限")
        return False
def main():
    system = platform.system()
    if system == "Linux":
        clean_linux_cache()
    elif system == "Windows":
        clean_windows_cache()
    elif system == "Darwin":  # macOS
        clean_mac_cache()
    else:
        print(f"不支持的操作系统: {system}")
        sys.exit(1)
if __name__ == "__main__":
    main()

使用示例和注意事项

Linux脚本使用:

# 赋予执行权限
chmod +x safe_clean_cache.sh
# 使用root运行
sudo ./safe_clean_cache.sh

重要提示:

  1. Linux清理缓存:Linux的drop_caches功能是安全的,不会删除程序数据,只会释放未使用的缓存
  2. Windows清理:Windows没有直接的命令行清理缓存工具,上述脚本通过.NET内存管理和进程优化来实现
  3. 权限要求:Linux和macOS需要root/sudo权限
  4. 频率控制:不建议过于频繁清理,可能影响性能,建议每天1-2次
  5. 服务器环境:如果是生产服务器,谨慎使用,可能需要评估对数据库等应用的影响

选择合适的脚本,根据您的操作系统和需求进行使用。

抱歉,评论功能暂时关闭!