在 CentOS 上“定时 cleanup”通常指定期清理日志、缓存、临时文件、旧内核等。下面按最常用、最安全的方式给你一套方案。
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
crontab -e
例如每周日凌晨 3 点执行:
0 3 * * 0 /root/cleanup.sh
查看任务:
crontab -l
vi /etc/systemd/system/cleanup.service
[Unit]
Description=CentOS Cleanup
[Service]
Type=oneshot
ExecStart=/root/cleanup.sh
vi /etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup weekly
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now cleanup.timer
查看状态:
systemctl list-timers
| 项目 | 命令 |
|---|---|
| yum 缓存 | yum clean all |
| 日志 | journalctl --vacuum-time=7d |
| 临时文件 | rm -rf /tmp/* |
| 旧内核 | package-cleanup --oldkernels |
| Docker | docker system prune -f |
rm -rf />> /var/log/cleanup.log 2>&1
如果你说的是 Docker / Nginx / 特定目录 / 磁盘满了,告诉我具体场景,我给你定制脚本。