CentOS 自动清理垃圾文件的实用方案
一 核心清理项与推荐做法
二 自动化方案一 systemd 定时器清理 journal
[Unit]
Description=Clean up journal logs
After=systemd-journald.service
[Service]
Type=oneshot
ExecStart=/usr/bin/journalctl --vacuum-time=1w
ExecStart=/usr/bin/journalctl --vacuum-size=500M
[Unit]
Description=Run journal cleanup daily
Requires=journal-cleanup.service
[Timer]
OnCalendar=daily
AccuracySec=1h
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now journal-cleanup.timer
systemctl list-timers journal-cleanup.timer
journalctl --disk-usage
该方案由 systemd 托管,稳定可靠,适合长期自动运行。
三 自动化方案二 Shell 脚本 + cron 定时任务
#!/bin/bash
set -e
# 仅允许 root 执行
[ "$(id -u)" -ne 0 ] && { echo "请使用 root 执行"; exit 1; }
# 1) 清理 YUM/DNF 缓存
if command -v dnf >/dev/null 2>&1; then
dnf clean all
elif command -v yum >/dev/null 2>&1; then
yum clean all
fi
# 2) 清理临时文件(谨慎:确保无业务正在使用)
rm -rf /tmp/*
rm -rf /var/tmp/*
# 3) 清理旧日志(示例:/var/log 下 30 天前的 *.log)
find /var/log -type f -name "*.log" -mtime +30 -delete 2>/dev/null || true
# 4) 清理过大的 nohup.out(示例:超过 100MB 则清空内容)
find /data /root /home /mnt -name 'nohup.out' -type f -size +100M -exec sh -c '
[ -s "{}" ] && echo "" > "{}"
' \; 2>/dev/null || true
# 5) 清理旧内核(保留最新 1 个)
if command -v package-cleanup >/dev/null 2>&1; then
package-cleanup --oldkernels --count=1 || true
fi
# 6) 清理孤立包
if command -v package-cleanup >/dev/null 2>&1; then
package-cleanup --quiet --leaves --exclude-bin || true
fi
# 7) 可选:清理用户回收站(多用户环境按需启用)
# find /home -path '*/.local/share/Trash/*' -delete 2>/dev/null || true
exit 0
chmod +x /usr/local/sbin/cleanup.sh
crontab -e
# 添加一行:
0 3 * * * /usr/local/sbin/cleanup.sh >> /var/log/cleanup.log 2>&1
crontab -l
systemctl status crond
tail -f /var/log/cleanup.log
该方案灵活可扩展,适合需要自定义清理策略的场景。
四 安全与验证要点