温馨提示×

centos cleanup能自动执行吗

小樊
33
2026-09-03 01:02:22
栏目: 智能运维

CentOS 里,“cleanup”(清理)本身不是一条固定命令,而是泛指一类操作(比如清理 yum 缓存、日志、临时文件、旧内核等)。这些清理操作是可以自动执行的,常见方式有下面几种:


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

你可以把清理命令写成脚本,然后用 cron 定时跑。

示例:自动清理脚本

#!/bin/bash
# /root/cleanup.sh

# 清理 yum 缓存
yum clean all

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

# 清理 /tmp 下 7 天未访问文件
find /tmp -type f -atime +7 -delete

# 清理日志
journalctl --vacuum-time=7d

赋予执行权限:

chmod +x /root/cleanup.sh

加入 cron(每天凌晨 3 点执行):

crontab -e
0 3 * * * /root/cleanup.sh

二、使用系统自带工具(半自动)

1. yum-autoupdate / dnf-automatic

CentOS 7/8 可自动更新并清理:

yum install dnf-automatic -y
systemctl enable --now dnf-automatic.timer

2. logrotate

日志清理是默认自动的(/etc/logrotate.conf)


三、使用 systemd timer(CentOS 7+ 推荐)

比 cron 更现代:

# /etc/systemd/system/cleanup.service
[Unit]
Description=Cleanup Job

[Service]
Type=oneshot
ExecStart=/root/cleanup.sh
# /etc/systemd/system/cleanup.timer
[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

启用:

systemctl enable --now cleanup.timer

四、注意事项

  • 不要盲目删文件(尤其是 /, /var
  • 内核清理建议保留至少 1–2 个
  • 生产环境先用测试机验证脚本

如果你能说明:

  • CentOS 版本(6 / 7 / 8 / Stream)
  • 想清理什么(日志 / 缓存 / 磁盘 / 内核)

我可以给你更精确可直接用的自动清理方案

0