温馨提示×

centos cleanup如何自动化

小樊
38
2026-08-19 04:12:03
栏目: 智能运维

CentOS 上实现 自动清理(cleanup),通常从 日志、YUM/DNF 缓存、临时文件、旧内核、Docker 等方面入手。下面给你一套 可自动化、可生产使用 的方案。


一、CentOS 自动清理常见目标

类型 内容
日志 /var/log
包管理器缓存 yum / dnf cache
临时文件 /tmp/var/tmp
旧内核 防止 /boot
Docker 镜像 / 容器 / 卷
自定义目录 日志、缓存、备份

二、使用 systemd 定时器(推荐 ✅)

1️⃣ 创建清理脚本

sudo vi /usr/local/bin/centos-cleanup.sh
#!/bin/bash
# centos-cleanup.sh

echo "=== Clean YUM/DNF cache ==="
yum clean all
dnf clean all 2>/dev/null

echo "=== Remove old kernels (keep 2) ==="
if command -v package-cleanup &>/dev/null; then
  package-cleanup --oldkernels --count=2 -y
fi

echo "=== Clean /tmp & /var/tmp ==="
find /tmp -type f -atime +7 -delete
find /var/tmp -type f -atime +7 -delete

echo "=== Clean journal logs (keep 7 days) ==="
journalctl --vacuum-time=7d

echo "=== Clean log files > 100M ==="
find /var/log -type f -name "*.log" -size +100M -exec truncate -s 0 {} \;

echo "=== Done ==="
sudo chmod +x /usr/local/bin/centos-cleanup.sh

2️⃣ 创建 systemd 服务

sudo vi /etc/systemd/system/centos-cleanup.service
[Unit]
Description=CentOS Cleanup Service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/centos-cleanup.sh

3️⃣ 创建定时器(每天凌晨 2 点)

sudo vi /etc/systemd/system/centos-cleanup.timer
[Unit]
Description=Run CentOS cleanup daily

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

4️⃣ 启用并启动

sudo systemctl daemon-reload
sudo systemctl enable centos-cleanup.timer
sudo systemctl start centos-cleanup.timer

查看状态:

systemctl list-timers centos-cleanup.timer

这是最推荐的方式(比 cron 更稳定)


三、使用 cron(传统方式)

sudo crontab -e
0 2 * * * /usr/local/bin/centos-cleanup.sh >> /var/log/centos-cleanup.log 2>&1

四、Docker 自动清理(如适用)

手动清理

docker system prune -af --volumes

自动清理(定时)

docker system prune -af --volumes

加入 systemd 或 cron 即可。


五、磁盘空间监控(可选)

df -h
du -sh /* | sort -h

可配合 Prometheus / Zabbix / 脚本报警


六、生产环境建议 ✅

✅ 只清理 7 天以上 文件
✅ 保留 2 个内核
✅ 日志用 truncate 而不是 rm
✅ 清理前先测试脚本
✅ 做好备份策略


如果你愿意,我可以帮你:

  • ✅ 定制 CentOS 7 / 8 / Stream 专用脚本
  • ✅ 针对 服务器 / 容器 / 桌面 优化
  • ✅ 加入 磁盘超过 80% 自动清理

只要告诉我你的 CentOS 版本 + 使用场景 即可。

0