怎么用脚本获取系统空闲内存

wen 实用脚本 1

本文目录导读:

怎么用脚本获取系统空闲内存

  1. Linux / macOS
  2. Windows
  3. 跨平台通用方案 (Node.js)
  4. 优化建议

这个需求很常见,我为你整理了不同平台下获取系统空闲内存的脚本方法。

Linux / macOS

Shell (最通用)

# 方法1: 使用 free 命令 (Linux)
free -h | grep Mem | awk '{print "空闲内存: "$7}'
# 或
free -m | awk 'NR==2{printf "可用内存: %.2f GB\n", $7/1024}'
# 方法2: 从 /proc/meminfo 读取 (Linux)
grep MemAvailable /proc/meminfo | awk '{printf "可用内存: %.2f GB\n", $2/1024/1024}'
# 方法3: macOS 使用 vm_stat
vm_stat | grep "Pages free" | awk '{print "空闲内存: " $3*4096/1024/1024 " MB"}'

Python (跨平台)

import os
import sys
def get_free_memory_linux():
    """Linux 系统"""
    with open('/proc/meminfo', 'r') as f:
        lines = f.readlines()
    meminfo = {}
    for line in lines:
        parts = line.split(':')
        meminfo[parts[0]] = int(parts[1].strip().split()[0])  # kB
    # MemAvailable 表示可用内存
    available_kb = meminfo.get('MemAvailable', 0)
    return available_kb / 1024 / 1024  # 转换为 GB
def get_free_memory_macos():
    """macOS 系统"""
    try:
        output = os.popen('vm_stat').read()
        for line in output.split('\n'):
            if 'Pages free' in line:
                pages_free = int(line.split(':')[1].strip().rstrip('.'))
                return pages_free * 4096 / 1024 / 1024  # GB
    except:
        return 0
# 判断系统类型
if sys.platform == 'linux':
    free_gb = get_free_memory_linux()
elif sys.platform == 'darwin':  # macOS
    free_gb = get_free_memory_macos()
else:
    free_gb = 0
print(f"系统空闲内存: {free_gb:.2f} GB")

Windows

PowerShell (最简单)

# 获取空闲内存
$os = Get-WmiObject -Class Win32_OperatingSystem
$freeMem = $os.FreePhysicalMemory / 1MB
Write-Host "空闲内存: $([math]::Round($freeMem, 2)) GB"
# 或使用较新的 cmdlet
$mem = Get-CimInstance Win32_OperatingSystem
Write-Host "空闲内存: $([math]::Round($mem.FreePhysicalMemory/1MB, 2)) GB"

Python (Windows)

import ctypes
import ctypes.wintypes
def get_free_memory_windows():
    """Windows 系统"""
    class MEMORYSTATUSEX(ctypes.Structure):
        _fields_ = [
            ("dwLength", ctypes.wintypes.DWORD),
            ("dwMemoryLoad", ctypes.wintypes.DWORD),
            ("ullTotalPhys", ctypes.c_ulonglong),
            ("ullAvailPhys", ctypes.c_ulonglong),
            ("ullTotalPageFile", ctypes.c_ulonglong),
            ("ullAvailPageFile", ctypes.c_ulonglong),
            ("ullTotalVirtual", ctypes.c_ulonglong),
            ("ullAvailVirtual", ctypes.c_ulonglong),
            ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
        ]
    memory_status = MEMORYSTATUSEX()
    memory_status.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(memory_status))
    # ullAvailPhys 是可用物理内存
    return memory_status.ullAvailPhys / 1024 / 1024 / 1024  # GB
print(f"系统空闲内存: {get_free_memory_windows():.2f} GB")

批处理 (Batch)

@echo off
wmic OS get FreePhysicalMemory /value

跨平台通用方案 (Node.js)

const os = require('os');
// 方法1: 直接获取
const freeMemory = os.freemem();
const totalMemory = os.totalmem();
console.log(`空闲内存: ${(freeMemory / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`总内存: ${(totalMemory / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log(`内存使用率: ${((1 - freeMemory / totalMemory) * 100).toFixed(1)}%`);
// 方法2: 更详细的信息
console.log('\n更多信息:');
console.log(process.memoryUsage());

优化建议

针对不同使用场景,我建议:

  1. 监控脚本:推荐使用 tophtop 附加参数

    top -b -n 1 | grep "KiB Mem" | awk '{print $6 " kB available"}'
  2. Web 监控页面:用 Python + Flask 或 Node.js + Express

  3. 定时任务:结合 cron (Linux) 或任务计划程序 (Windows)

选择哪种方式取决于:

  • 你的操作系统
  • 是否安装了解释器(Python/Node.js)
  • 脚本执行频率(频繁执行建议用轻量级 shell)

如果你需要更具体的场景(比如监控脚本配合告警),告诉我你的具体需求,我可以提供更针对性的方案。

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