温馨提示×

怎样自动化centos cleanup

小樊
44
2026-09-09 02:21:38
栏目: 智能运维

在 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

二、用 cron 做定时自动清理(推荐入门)

示例:每周日清理一次

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

三、使用 systemd timer(比 cron 更现代)

1. Service

/etc/systemd/system/centos-cleanup.service

[Unit]
Description=CentOS Cleanup

[Service]
Type=oneshot
ExecStart=/root/centos-cleanup.sh

2. Timer

/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

四、使用 logrotate(专门管日志)

CentOS 默认已启用,可自定义:

/etc/logrotate.d/custom

/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
}

五、进阶:自动化运维工具

Ansible(适合多台服务器)

- 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 天(合规需要)
✅ 重要数据先备份再清理


七、如果你愿意,我可以进一步帮你

你可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 是 单机还是集群
  • 主要想清理 磁盘 / 日志 / 容器 / Docker

我可以直接给你可复制的完整脚本或 Ansible Playbook。

0 踩