本文目录导读:

- Linux系统 (Shell脚本)
- Python脚本
- Windows系统 (PowerShell脚本)
- Windows系统 (批处理脚本.bat)
- macOS系统 (Shell脚本)
- Node.js脚本
- Perl脚本
- 选择建议
Linux系统 (Shell脚本)
#!/bin/bash
# 方法1:使用/proc/cpuinfo
cat /proc/cpuinfo | grep "model name" | head -1 | cut -d: -f2 | sed 's/^ //'
# 方法2:使用lscpu命令
lscpu | grep "Model name" | head -1 | awk -F: '{print $2}' | sed 's/^ //'
# 方法3:更简洁的方式
cat /proc/cpuinfo | grep -m1 "model name" | cut -d: -f2 | xargs
Python脚本
#!/usr/bin/env python3
import platform
import subprocess
# 方法1:使用platform模块
cpu_info = platform.processor()
print(f"CPU型号: {cpu_info}")
# 方法2:读取/proc/cpuinfo(Linux)
def get_cpu_model_linux():
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if 'model name' in line:
return line.split(':')[1].strip()
return "Unknown"
# 方法3:使用lscpu命令
def get_cpu_model_lscpu():
result = subprocess.run(['lscpu'], capture_output=True, text=True)
for line in result.stdout.split('\n'):
if 'Model name' in line:
return line.split(':')[1].strip()
return "Unknown"
print(f"Linux方法: {get_cpu_model_linux()}")
print(f"lscpu方法: {get_cpu_model_lscpu()}")
Windows系统 (PowerShell脚本)
# 方法1:使用WMI Get-WmiObject Win32_Processor | Select-Object -Property Name # 方法2:使用CIM Get-CimInstance Win32_Processor | Select-Object -Property Name # 方法3:获取详细信息 Get-WmiObject Win32_Processor | Format-List Name, Manufacturer, Description
Windows系统 (批处理脚本.bat)
@echo off wmic cpu get name
macOS系统 (Shell脚本)
#!/bin/bash
# 方法1:使用sysctl
sysctl -n machdep.cpu.brand_string
# 方法2:使用system_profiler
system_profiler SPHardwareDataType | grep "Processor Name" | awk -F: '{print $2}' | sed 's/^ //'
Node.js脚本
const os = require('os');
const { exec } = require('child_process');
// 方法1:使用os模块(跨平台)
console.log('CPU型号:', os.cpus()[0].model);
// 方法2:Linux系统使用命令
if (process.platform === 'linux') {
exec('cat /proc/cpuinfo | grep "model name" | head -1', (err, stdout) => {
if (!err) console.log('Linux CPU:', stdout.split(':')[1].trim());
});
}
Perl脚本
#!/usr/bin/perl
use strict;
use warnings;
# Linux系统
open(my $fh, '<', '/proc/cpuinfo') or die "Cannot open /proc/cpuinfo: $!";
while (my $line = <$fh>) {
if ($line =~ /^model name\s+:\s+(.*)$/) {
print "CPU型号: $1\n";
last;
}
}
close($fh);
选择建议
- 跨平台兼容性:使用Python或Node.js的os模块
- Linux系统:使用
/proc/cpuinfo或lscpu命令 - Windows系统:使用WMI或PowerShell
- macOS:使用
sysctl命令
这些脚本可以获取完整的CPU型号信息,包括架构、频率等详细参数。