温馨提示×

如何定时centos cleanup

小樊
41
2026-09-09 02:31:39
栏目: 智能运维

在 CentOS 上“定时 cleanup”通常指定期清理日志、缓存、临时文件、旧内核等。下面按最常用、最安全的方式给你一套方案。


一、使用 cron 定时任务(推荐)

1. 编写清理脚本

vi /root/cleanup.sh

示例脚本(按需修改):

#!/bin/bash

# 清理 yum 缓存
yum clean all

# 清理临时文件
rm -rf /tmp/*
rm -rf /var/tmp/*

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

# 清理旧内核(保留最近 2 个)
package-cleanup --oldkernels --count=2 -y

# 清理日志
find /var/log -type f -name "*.log" -mtime +30 -delete
find /var/log -type f -name "*.gz" -mtime +30 -delete

赋予执行权限:

chmod +x /root/cleanup.sh

2. 添加定时任务

crontab -e

例如每周日凌晨 3 点执行

0 3 * * 0 /root/cleanup.sh

查看任务:

crontab -l

二、使用 systemd timer(CentOS 7/8 推荐)

1. 创建 service

vi /etc/systemd/system/cleanup.service
[Unit]
Description=CentOS Cleanup

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

2. 创建 timer

vi /etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup weekly

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

3. 启用

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

查看状态:

systemctl list-timers

三、常见 cleanup 项目说明

项目 命令
yum 缓存 yum clean all
日志 journalctl --vacuum-time=7d
临时文件 rm -rf /tmp/*
旧内核 package-cleanup --oldkernels
Docker docker system prune -f

四、注意事项

  • ❗ 不要随意 rm -rf /
  • 内核至少保留 1–2 个
  • 生产环境建议先测试脚本
  • 可加日志:
>> /var/log/cleanup.log 2>&1

如果你说的是 Docker / Nginx / 特定目录 / 磁盘满了,告诉我具体场景,我给你定制脚本。

0