本文目录导读:

我来为您编写一个系统一键优化脚本,以下是一个综合性的系统优化脚本,支持Linux系统和macOS:
Linux系统优化脚本
#!/bin/bash
# 系统一键优化脚本 (Linux版)
# 适用于: Ubuntu/Debian/CentOS/RHEL等主流Linux发行版
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 检查是否以root权限运行
check_root() {
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}请以root权限运行此脚本 (sudo bash optimize.sh)${NC}"
exit 1
fi
}
# 显示进度信息
log() {
echo -e "${GREEN}[INFO]${NC} $1"
}
warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# 检测系统类型
detect_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
VERSION=$VERSION_ID
else
OS=$(uname -s)
VERSION=$(uname -r)
fi
log "检测到系统: $OS $VERSION"
}
# 1. 更新系统包
update_system() {
log "正在更新系统包..."
case $OS in
ubuntu|debian)
apt-get update -y && apt-get upgrade -y
apt-get autoremove -y && apt-get autoclean
;;
centos|rhel|fedora)
yum update -y || dnf update -y
yum autoremove -y || dnf autoremove -y
;;
*)
warn "未能识别的系统类型,跳过系统更新"
;;
esac
}
# 2. 清理系统缓存和临时文件
clean_system() {
log "正在清理系统缓存和临时文件..."
# 清理临时文件
rm -rf /tmp/*
rm -rf /var/tmp/*
# 清理软件包缓存
case $OS in
ubuntu|debian)
apt-get clean
;;
centos|rhel|fedora)
yum clean all || dnf clean all
;;
esac
# 清理日志文件
find /var/log -type f -name "*.log" -mtime +30 -delete 2>/dev/null
# 清理旧内核
if command -v package-cleanup &> /dev/null; then
package-cleanup --oldkernels --count=1 -y
fi
log "系统缓存清理完成"
}
# 3. 优化系统配置
optimize_system() {
log "正在优化系统配置..."
# 优化内核参数
cat >> /etc/sysctl.conf << EOF
# 系统优化配置
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_syncookies = 1
vm.swappiness = 10
vm.vfs_cache_pressure = 50
EOF
# 应用配置
sysctl -p
log "内核参数优化完成"
}
# 4. 优化SSH配置
optimize_ssh() {
log "正在优化SSH配置..."
SSH_CONFIG="/etc/ssh/sshd_config"
if [ -f "$SSH_CONFIG" ]; then
# 备份原配置
cp "$SSH_CONFIG" "$SSH_CONFIG.bak"
# 优化配置
sed -i 's/#MaxSessions 10/MaxSessions 20/' "$SSH_CONFIG"
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' "$SSH_CONFIG"
# 重启SSH服务
systemctl restart sshd 2>/dev/null || service ssh restart 2>/dev/null
log "SSH配置优化完成"
else
warn "未找到SSH配置文件"
fi
}
# 5. 清理无用的服务
disable_unused_services() {
log "正在禁用不常用的服务..."
unused_services=("cups" "avahi-daemon" "bluetooth" "cups-browsed" "ModemManager")
for service in "${unused_services[@]}"; do
systemctl disable $service 2>/dev/null
systemctl stop $service 2>/dev/null
done
log "服务清理完成"
}
# 6. 优化内存使用
optimize_memory() {
log "正在优化内存使用..."
# 释放内存缓存
sync
echo 3 > /proc/sys/vm/drop_caches
# 显示内存使用情况
free -h
log "内存优化完成"
}
# 7. 优化磁盘使用
optimize_disk() {
log "正在优化磁盘使用..."
# 清理磁盘
df -h
# 清理孤儿文件
find / -type f -empty -delete 2>/dev/null
# 优化文件系统性能
if command -v tune2fs &> /dev/null; then
tune2fs -m 5 /dev/*a* 2>/dev/null || true
fi
log "磁盘优化完成"
}
# 8. 设置系统限制优化
optimize_limits() {
log "正在优化系统限制..."
# 增加文件描述符限制
cat >> /etc/security/limits.conf << EOF
# 系统优化配置
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
EOF
log "系统限制优化完成"
}
# 9. 显示优化报告
show_report() {
echo ""
echo "==============================="
echo " 系统优化报告"
echo "==============================="
echo ""
echo "系统运行时间: $(uptime -p)"
echo ""
echo "内存使用情况:"
free -h | awk 'NR<3'
echo ""
echo "磁盘使用情况:"
df -h | grep -E '^/'
echo ""
echo "CPU信息:"
grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2
echo "CPU核心数: $(nproc)"
echo ""
echo "==============================="
echo "优化完成!"
}
# 主函数
main() {
clear
echo "====================================="
echo " 系统一键优化脚本 v1.0"
echo "====================================="
echo ""
# 检查权限
check_root
# 检测系统
detect_os
# 显示开始信息
echo "开始优化系统,整个过程可能需要几分钟..."
echo ""
# 执行优化
update_system
clean_system
optimize_system
#optimize_ssh # 可选,默认跳过
disable_unused_services
optimize_memory
optimize_disk
optimize_limits
# 显示报告
show_report
}
# 执行主函数
main
Windows系统优化脚本 (PowerShell)
# Windows系统优化脚本
# 以管理员身份运行
Write-Host "═══════════════════════════════════════" -ForegroundColor Cyan
Write-Host " Windows 系统一键优化脚本 v1.0" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""
# 检查管理员权限
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host "请以管理员身份运行此脚本!" -ForegroundColor Red
exit 1
}
# 1. 清理系统垃圾文件
function Clear-JunkFiles {
Write-Host "清理临时文件..." -ForegroundColor Yellow
$paths = @(
"$env:TEMP",
"$env:SystemRoot\Temp",
"$env:SystemRoot\Prefetch",
"$env:SystemRoot\SoftwareDistribution\Download"
)
foreach ($path in $paths) {
if (Test-Path $path) {
try {
Remove-Item "$path\*" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "已清理: $path" -ForegroundColor Green
}
catch {
Write-Host "清理失败: $path" -ForegroundColor Red
}
}
}
}
# 2. 清理系统缓存
function Clear-SystemCache {
Write-Host "清理系统缓存..." -ForegroundColor Yellow
# 清理DNS缓存
ipconfig /flushdns | Out-Null
# 清理缩略图缓存
Remove-Item "$env:LOCALAPPDATA\Microsoft\Windows\Explorer\thumbcache_*" -Force -ErrorAction SilentlyContinue
Write-Host "系统缓存清理完成" -ForegroundColor Green
}
# 3. 优化系统服务
function Optimize-Services {
Write-Host "优化系统服务..." -ForegroundColor Yellow
$services = @(
"DiagTrack",
"dmwappushservice",
"WSearch"
)
foreach ($service in $services) {
try {
Set-Service -Name $service -StartupType Disabled -ErrorAction SilentlyContinue
Stop-Service -Name $service -Force -ErrorAction SilentlyContinue
Write-Host "已停用: $service" -ForegroundColor Green
}
catch {
Write-Host "操作失败: $service" -ForegroundColor Red
}
}
}
# 4. 优化系统设置
function Optimize-SystemSettings {
Write-Host "优化系统设置..." -ForegroundColor Yellow
# 关闭动画效果
Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "UserPreferencesMask" -Value ([byte[]](0x90,0x12,0x03,0x80,0x10,0x00,0x00,0x00)) -Type Binary
# 优化视觉效果
$visualEffects = @{
"TaskbarAnimations" = 0
"ListviewAlphaSelect" = 0
"ListviewShadow" = 0
"MenuAnimation" = 0
"MinimizeAnimation" = 0
"ComboBoxAnimation" = 0
"CursorShadow" = 0
}
$visualEffects.GetEnumerator() | ForEach-Object {
Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name $_.Key -Value $_.Value
}
Write-Host "系统设置优化完成" -ForegroundColor Green
}
# 5. 清理注册表
function Clean-Registry {
Write-Host "清理注册表冗余..." -ForegroundColor Yellow
# 备份注册表
reg export HKLM"\Software" "$env:USERPROFILE\Desktop\registry_backup.reg" /y | Out-Null
# 清理无效的启动项
Remove-Item "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Value "*" -ErrorAction SilentlyContinue
Write-Host "注册表备份已保存到桌面" -ForegroundColor Green
}
# 6. 定期执行磁盘清理
function Schedule-Cleanup {
Write-Host "设置自动化清理计划..." -ForegroundColor Yellow
$action = New-ScheduledTaskAction -Execute "cleanmgr.exe" -Argument "/sagerun:100"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 3am
Register-ScheduledTask -TaskName "SystemOptimization" -Action $action -Trigger $trigger -Force | Out-Null
Write-Host "已创建每周自动清理计划" -ForegroundColor Green
}
# 7. 系统优化报告
function Show-Report {
Write-Host ""
Write-Host "═══════════════════════════════════════" -ForegroundColor Cyan
Write-Host " 优化完成!" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""
Write-Host "系统运行时间: $(Get-Uptime)"
Write-Host ""
Write-Host "内存使用: " -NoNewline
$mem = Get-CimInstance Win32_OperatingSystem
$used = [math]::Round(($mem.TotalVisibleMemorySize - $mem.FreePhysicalMemory) / 1MB, 2)
$total = [math]::Round($mem.TotalVisibleMemorySize / 1MB, 2)
Write-Host "$used GB / $total GB" -ForegroundColor Yellow
Write-Host ""
Write-Host "磁盘使用情况:" -ForegroundColor Yellow
Get-PSDrive -PSProvider FileSystem | Where-Object {$_.Free -gt 0} | ForEach-Object {
$percent = [math]::Round((1 - $_.Free / $_.Used) * 100, 2)
Write-Host " $($_.Name): $percent% 已使用"
}
Write-Host ""
Write-Host "建议重启系统以应用所有优化" -ForegroundColor Cyan
}
# 执行优化
Write-Host "开始优化系统..." -ForegroundColor Cyan
Clear-JunkFiles
Clear-SystemCache
Optimize-Services
Optimize-SystemSettings
Clean-Registry
Schedule-Cleanup
Show-Report
# 询问是否重启
$restart = Read-Host "是否立即重启系统?(Y/N)"
if ($restart -eq "Y" -or $restart -eq "y") {
Restart-Computer -Force
}
使用说明
Linux使用:
# 保存脚本 sudo vim optimize.sh # 赋予执行权限 chmod +x optimize.sh # 运行脚本 sudo ./optimize.sh
Windows使用:
- 将上述PowerShell代码保存为
optimize.ps1 - 右键点击文件,选择"使用PowerShell运行"
- 或者以管理员身份打开PowerShell,执行:
Set-ExecutionPolicy Bypass -Scope Process ./optimize.ps1
注意事项
- 备份重要数据:运行优化前建议备份重要数据
- 谨慎操作:有些优化可能影响特定程序运行
- 系统兼容性:不同系统版本可能需要适当调整
- 测试环境:建议先在测试环境验证
这个脚本涵盖了大部分常见的系统优化任务,您可以根据实际需求添加或删除特定的优化步骤。