Files
vps/init/02-sysCleanup.sh

90 lines
3.0 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# chmod +x 02-sysCleanup.sh && ./02-sysCleanup.sh
# curl -sS -O https://gitea.tohub.top/Share/vps/raw/branch/main/init/02-sysCleanup.sh && chmod +x 02-sysCleanup.sh && ./02-sysCleanup.sh
# 错误处理:任何命令失败时退出
set -euo pipefail
# 日志函数
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"
}
log_error() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $*" >&2
}
log "========== 开始系统清理 =========="
# 检测操作系统类型
if [ -f "/etc/debian_version" ]; then
OS_TYPE="debian"
elif [ -f "/etc/redhat-release" ]; then
OS_TYPE="redhat"
else
log_error "不支持的操作系统"
exit 1
fi
if [ "$OS_TYPE" = "debian" ]; then
# 1. 清理无用的软件包
log "清理不再需要的软件包..."
apt autoremove --purge -y || log_error "autoremove 失败"
# 2. 清理 APT 缓存
log "清理 APT 缓存..."
apt clean -y || log_error "apt clean 失败"
apt autoclean -y || log_error "apt autoclean 失败"
# 3. 清理已卸载但配置文件残留的包(安全检查)
log "清理残留的配置文件..."
RC_PACKAGES=$(dpkg -l | awk '/^rc/ {print $2}' || true)
if [ -n "$RC_PACKAGES" ]; then
log "找到 $(echo "$RC_PACKAGES" | wc -l) 个残留配置包"
echo "$RC_PACKAGES" | xargs apt remove --purge -y || log_error "清理残留配置失败"
else
log "没有残留的配置文件需要清理"
fi
# 4. 清理旧内核(保留当前内核和最新的一个旧内核)
log "清理旧内核..."
CURRENT_KERNEL=$(uname -r | sed 's/-generic//;s/-amd64//')
log "当前内核: $CURRENT_KERNEL"
# 获取所有已安装的内核
OLD_KERNELS=$(dpkg -l | awk '/^ii linux-(image|headers)-[0-9]/{print $2}' | grep -v "$CURRENT_KERNEL" | sort -V | head -n -1 || true)
if [ -n "$OLD_KERNELS" ]; then
log "发现旧内核(将保留最新的一个旧内核作为备份):"
echo "$OLD_KERNELS"
echo "$OLD_KERNELS" | xargs apt remove --purge -y || log_error "清理旧内核失败"
log "旧内核清理完成"
else
log "没有需要清理的旧内核"
fi
elif [ "$OS_TYPE" = "redhat" ]; then
log "清理 YUM 缓存..."
yum clean all || log_error "yum clean 失败"
log "清理旧内核保留最新的2个内核..."
package-cleanup --oldkernels --count=2 -y || log_error "清理旧内核失败"
fi
# 5. 清理 journal 日志(保留最近 7 天或 500M
log "清理系统日志..."
if command -v journalctl &> /dev/null; then
journalctl --rotate || log_error "日志轮转失败"
journalctl --vacuum-time=7d || log_error "按时间清理日志失败"
journalctl --vacuum-size=500M || log_error "按大小清理日志失败"
log "日志清理完成"
else
log "journalctl 不可用,跳过日志清理"
fi
# 6. 显示清理后的磁盘使用情况
log "========== 磁盘使用情况 =========="
df -h / || true
log "========== 系统清理完成 =========="