定制 CentOS 清理策略
一 目标与总体思路
二 清理范围与推荐做法
三 自动化与定时执行
#!/bin/bash
set -e
# 0) 安全阈值
THRESHOLD=90
USAGE=$(df / | awk 'NR==2 {gsub("%",""); print $5}')
if [ "$USAGE" -lt "$THRESHOLD" ]; then
echo "磁盘使用率 ${USAGE}% < ${THRESHOLD}%,跳过清理"
exit 0
fi
# 1) 包管理
yum clean all || true
yum autoremove -y || true
if command -v package-cleanup >/dev/null 2>&1; then
package-cleanup --oldkernels --count=2 -y || true
fi
# 2) 临时文件(谨慎:确保无业务占用)
rm -rf /tmp/* /var/tmp/* 2>/dev/null || true
# 3) 日志:优先用 logrotate;如确需清理已轮转的旧日志
find /var/log -type f -name "*.gz" -mtime +30 -delete 2>/dev/null || true
find /var/log -type f -name "*.log" -mtime +30 -delete 2>/dev/null || true
# 4) 大文件巡检(仅输出,不删除)
echo "Top 10 largest dirs in /var:"
du -xh /var 2>/dev/null | sort -rh | head -n 10
# 5) 可选:清理内存页缓存(仅在必要时使用,生产慎用)
# sync
# echo 3 > /proc/sys/vm/drop_caches
0 2 * * * /usr/local/sbin/cleanup.sh >> /var/log/cleanup.log 2>&1
四 日志与临时文件的策略模板
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 root root
postrotate
/usr/bin/systemctl reload myapp.service >/dev/null 2>&1 || true
endscript
}
五 安全与运维建议