温馨提示×

centos cleanup如何自动执行

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

在 CentOS 中让“清理(cleanup)”自动执行,常见做法有 cron 定时任务、systemd timer、日志轮转+自动清理 等。下面按使用场景给你一套实用方案。


一、用 cron 定时自动执行清理(最常用)

1. 编写清理脚本

例如:/opt/scripts/cleanup.sh

#!/bin/bash
# 清理 yum 缓存
yum clean all

# 删除 /tmp 下 7 天未访问的文件
find /tmp -type f -atime +7 -delete

# 清理 journal 日志(保留最近 3 天)
journalctl --vacuum-time=3d

# 删除旧的核心转储
find /var/crash -type f -mtime +7 -delete

赋予执行权限:

chmod +x /opt/scripts/cleanup.sh

2. 加入 cron 定时任务

crontab -e

示例(每天凌晨 2 点执行):

0 2 * * * /opt/scripts/cleanup.sh >> /var/log/cleanup.log 2>&1

二、用 systemd timer(CentOS 7+ 推荐)

1. 创建 service

/etc/systemd/system/cleanup.service

[Unit]
Description=CentOS Cleanup

[Service]
Type=oneshot
ExecStart=/opt/scripts/cleanup.sh

2. 创建 timer

/etc/systemd/system/cleanup.timer

[Unit]
Description=Run cleanup daily

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

[Install]
WantedBy=timers.target

3. 启用

systemctl daemon-reload
systemctl enable --now cleanup.timer

查看状态:

systemctl list-timers

三、自动清理日志(避免磁盘爆满)

1. 配置 logrotate(系统自带)

编辑:

/etc/logrotate.conf

示例:

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

手动测试:

logrotate -d /etc/logrotate.conf

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

docker system prune -af

可加入 cron:

0 3 * * * docker system prune -af

五、常见清理项建议

  • /tmp、/var/tmp
  • yum cache
  • journalctl
  • 旧内核(CentOS 可保留 2–3 个)
package-cleanup --oldkernels --count=2

如果你能说明具体想清理什么(磁盘 / 日志 / 缓存 / Docker / 定时任务),我可以直接给你一份可复制的脚本和配置。

0 踩