在 CentOS(以及 RHEL 系)上做“自动化 cleanup”通常包括:日志清理、包缓存清理、临时文件清理、旧内核清理、磁盘空间监控等。下面按「从简单到专业」给你几种可行方案。
# 清理 yum/dnf 缓存
sudo yum clean all
# 或
sudo dnf clean all
# 删除旧内核(保留当前和上一个)
sudo package-cleanup --oldkernels --count=2
# 清理 /tmp
sudo rm -rf /tmp/*
# 清理日志
sudo journalctl --vacuum-time=7d
# 查看大文件
du -sh /* 2>/dev/null
sudo crontab -e
添加:
0 3 * * 0 /root/centos-cleanup.sh
/root/centos-cleanup.sh#!/bin/bash
# centos-cleanup.sh
# 清理包缓存
yum clean all
# 保留最近2个内核
package-cleanup --oldkernels --count=2 -y
# 清理 systemd 日志
journalctl --vacuum-time=7d
# 清理 /tmp(超过7天)
find /tmp -type f -mtime +7 -delete
# 清理 audit 日志
truncate -s 0 /var/log/audit/audit.log
# 磁盘使用记录
df -h > /var/log/disk-usage.log
chmod +x /root/centos-cleanup.sh
/etc/systemd/system/centos-cleanup.service
[Unit]
Description=CentOS Cleanup
[Service]
Type=oneshot
ExecStart=/root/centos-cleanup.sh
/etc/systemd/system/centos-cleanup.timer
[Unit]
Description=Run CentOS cleanup weekly
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
systemctl enable --now centos-cleanup.timer
CentOS 默认已启用,可自定义:
/etc/logrotate.d/custom
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
}
- name: CentOS cleanup
hosts: all
tasks:
- name: Clean yum cache
yum:
clean: all
- name: Remove old kernels
command: package-cleanup --oldkernels --count=2 -y
✅ 不要删 /var/lib、/etc
✅ 内核至少保留 2 个
✅ 日志保留周期 ≥ 7 天(合规需要)
✅ 重要数据先备份再清理
你可以告诉我:
我可以直接给你可复制的完整脚本或 Ansible Playbook。