温馨提示×

怎样自动化linux cleanup任务

小樊
37
2026-10-02 11:29:51
栏目: 智能运维

在 Linux 上“自动化 cleanup 任务”通常分三步:确定要清理什么 → 写好清理脚本 → 用调度器自动执行。下面按常见场景给你一套可落地的做法。


一、常见需要清理的内容

  • 日志文件(/var/log)
  • 临时文件(/tmp、/var/tmp)
  • 旧内核
  • 包缓存(apt/yum/dnf)
  • 用户家目录垃圾(~/.cache)
  • Docker 无用镜像/容器(如果用 Docker)

二、写一个 cleanup 脚本(示例)

示例:通用清理脚本 /usr/local/bin/cleanup.sh

#!/bin/bash

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

# 清理日志(保留最近 30 天)
find /var/log -type f -name "*.log" -mtime +30 -delete

# 清理 apt 缓存(Debian/Ubuntu)
apt-get clean

# 清理 yum 缓存(CentOS/RHEL)
# yum clean all

# 删除旧内核(Ubuntu 示例)
# apt-get autoremove --purge -y

# Docker 清理(可选)
# docker system prune -af

赋予执行权限:

chmod +x /usr/local/bin/cleanup.sh

三、用 cron 自动执行(最常用)

每天凌晨 2 点执行

crontab -e

添加:

0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1

四、用 systemd timer(更现代)

1. 创建 service

/etc/systemd/system/cleanup.service

[Unit]
Description=Linux Cleanup Task

[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh

2. 创建 timer

/etc/systemd/system/cleanup.timer

[Unit]
Description=Run cleanup daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

3. 启用

systemctl enable --now cleanup.timer

查看状态:

systemctl list-timers

五、更安全的高级做法

  • 用 logrotate 管理日志(不要手动删)
  • 清理前先 echo 模拟:
find /tmp -type f -atime +7 -print
  • 用 nice / ionice 降低清理对系统影响
  • 重要服务器建议先备份再清理

六、如果你用的是特定环境

可以告诉我:

  • 发行版(Ubuntu / CentOS / Arch)
  • 是否用 Docker / Kubernetes
  • 是服务器还是桌面

我可以给你更精确的自动化方案。

0 踩