温馨提示×

如何自动执行debian cleanup

小樊
31
2026-09-03 22:20:17
栏目: 智能运维

在 Debian 系统中,“cleanup”通常指清理 apt 缓存、旧内核、无用依赖、日志等。下面按常用方式 + 自动执行方案说明。


一、手动清理(先了解在做什么)

1. 清理 apt 缓存

sudo apt clean
sudo apt autoclean

2. 删除无用依赖

sudo apt autoremove --purge

3. 删除旧内核(保留当前运行内核)

sudo apt purge $(dpkg -l | awk '/linux-image-[0-9]/{print $2}' | grep -v $(uname -r))

4. 清理系统日志(journald)

sudo journalctl --vacuum-time=7d

5. 清理用户缓存

rm -rf ~/.cache/*

二、自动执行(推荐方式)

✅ 方式 1:systemd 定时器(Debian 默认支持)

1. 创建清理脚本

sudo nano /usr/local/sbin/debian-cleanup.sh

内容示例:

#!/bin/bash
apt clean
apt autoremove --purge -y
journalctl --vacuum-time=7d
rm -rf /tmp/*

赋予执行权限:

sudo chmod +x /usr/local/sbin/debian-cleanup.sh

2. 创建 systemd service

sudo nano /etc/systemd/system/debian-cleanup.service
[Unit]
Description=Debian Cleanup

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/debian-cleanup.sh

3. 创建 timer

sudo nano /etc/systemd/system/debian-cleanup.timer
[Unit]
Description=Run Debian Cleanup Weekly

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

4. 启用

sudo systemctl enable --now debian-cleanup.timer

查看状态:

systemctl list-timers

✅ 方式 2:cron(传统方式)

sudo crontab -e

每周日 3 点执行:

0 3 * * 0 /usr/local/sbin/debian-cleanup.sh

✅ 方式 3: unattended-upgrades(仅更新+清理)

Debian 自带:

sudo apt install unattended-upgrades

启用自动清理:

sudo dpkg-reconfigure unattended-upgrades

配置文件:

/etc/apt/apt.conf.d/50unattended-upgrades

确保包含:

APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";

三、安全建议

  • ✅ 保留当前内核
  • ✅ 生产服务器建议 weekly 而不是 daily
  • ✅ 脚本中加入日志:
logger "Debian cleanup executed"

如果你告诉我:

  • 桌面 / 服务器
  • 是否 生产环境
  • 想清理哪些内容(内核 / 日志 / Docker 等)

我可以给你一份更精确的自动清理方案

0