怎么用脚本获取系统最大内存

wen 实用脚本 1

本文目录导读:

怎么用脚本获取系统最大内存

  1. Python 脚本(跨平台)
  2. Bash 脚本 (Linux/macOS)
  3. PowerShell 脚本 (Windows)
  4. 批处理脚本 (Windows CMD)
  5. Node.js 脚本 (跨平台)
  6. 使用建议

Python 脚本(跨平台)

import os
import platform
def get_total_memory():
    system = platform.system()
    if system == "Linux":
        with open('/proc/meminfo', 'r') as f:
            for line in f:
                if 'MemTotal' in line:
                    # 返回KB为单位的内存总量
                    total_kb = int(line.split()[1])
                    return total_kb  # KB
    elif system == "Windows":
        import ctypes
        kernel32 = ctypes.windll.kernel32
        class MEMORYSTATUSEX(ctypes.Structure):
            _fields_ = [
                ("dwLength", ctypes.c_ulong),
                ("dwMemoryLoad", ctypes.c_ulong),
                ("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)
        kernel32.GlobalMemoryStatusEx(ctypes.byref(memory_status))
        return memory_status.ullTotalPhys  # 字节
    elif system == "Darwin":  # macOS
        import subprocess
        output = subprocess.check_output(['sysctl', 'hw.memsize'])
        return int(output.split()[1])  # 字节
    return None
# 转换为人类可读格式
total_bytes = get_total_memory()
if total_bytes:
    if total_bytes < 1024*1024:  # 小于1MB
        print(f"总内存: {total_bytes} bytes")
    elif total_bytes < 1024*1024*1024:  # 小于1GB
        print(f"总内存: {total_bytes/1024/1024:.2f} MB")
    else:
        print(f"总内存: {total_bytes/1024/1024/1024:.2f} GB")

Bash 脚本 (Linux/macOS)

#!/bin/bash
# 方法1:使用 /proc/meminfo (Linux)
if [ -f /proc/meminfo ]; then
    total_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')
    echo "总内存: $(echo "scale=2; $total_kb/1024/1024" | bc) GB"
# 方法2:使用 sysctl (macOS)
elif [ "$(uname)" == "Darwin" ]; then
    total_bytes=$(sysctl -n hw.memsize)
    echo "总内存: $(echo "scale=2; $total_bytes/1024/1024/1024" | bc) GB"
# 方法3:使用 free 命令 (Linux)
elif command -v free &> /dev/null; then
    total_mb=$(free -m | grep Mem: | awk '{print $2}')
    echo "总内存: $(echo "scale=2; $total_mb/1024" | bc) GB"
fi

PowerShell 脚本 (Windows)

# 方法1:使用 CIM/WMI
$total_memory = (Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory
Write-Host "总内存: $([math]::Round($total_memory/1GB, 2)) GB"
# 方法2:使用 Get-Counter
$total_memory = (Get-Counter "\Memory\Available Bytes" -ErrorAction SilentlyContinue).CounterSamples.CookedValue
$total_memory = (Get-CimInstance Win32_OperatingSystem).TotalVisibleMemorySize * 1KB
Write-Host "总内存: $([math]::Round($total_memory/1GB, 2)) GB"

批处理脚本 (Windows CMD)

@echo off
REM 方法1:使用 wmic
for /f "tokens=2 delims==" %%a in ('wmic os get TotalVisibleMemorySize /value') do set total_mem=%%a
set /a total_mem_gb=%total_mem%/1048576
echo 总内存: %total_mem_gb% GB
REM 方法2:使用 systeminfo
for /f "tokens=2 delims=:" %%a in ('systeminfo ^| find "总物理内存"') do set total_mem=%%a
echo 总内存: %total_mem%

Node.js 脚本 (跨平台)

const os = require('os');
// 获取总内存(字节)
const totalMemoryBytes = os.totalmem();
// 转换为GB
const totalMemoryGB = totalMemoryBytes / 1024 / 1024 / 1024;
console.log(`总内存: ${totalMemoryGB.toFixed(2)} GB`);
// 也可以获取其他内存信息
console.log(`系统内存: ${(os.totalmem() / 1024 / 1024).toFixed(0)} MB`);
console.log(`系统架构: ${os.arch()}`);
console.log(`系统类型: ${os.type()}`);

使用建议

  • Linux: 优先使用 /proc/meminfofree 命令
  • Windows: 推荐使用 PowerShell 或 Python
  • macOS: 使用 sysctl hw.memsize
  • 跨平台: 使用 Python 或 Node.js

这些脚本都能获取系统的物理内存总量,而不是可用内存,如果需要获取当前可用内存,需要额外处理。

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