温馨提示×

怎样自动cleanup debian系统

小樊
38
2026-10-27 13:07:30
栏目: 智能运维

在 Debian 系统上做“自动 cleanup(自动清理)”通常指:自动删除不再需要的包、缓存、日志、旧内核等,以释放磁盘空间并保持系统整洁。下面按「安全 → 进阶 → 自动化」给你一套常用方案。


一、最基础 & 安全的手动清理命令

1. 删除无用依赖

sudo apt autoremove

删除“曾经被依赖、现在没人用的包”。

2. 清理下载缓存

sudo apt clean

清空 /var/cache/apt/archives/

sudo apt autoclean

只删掉旧版本的 deb 缓存(更安全)

3. 删除旧内核(非常重要)

Debian 不会自动删内核,时间久了 /boot 会满。

sudo apt autoremove --purge

通常会自动移除最旧的内核(保留当前+上一个)。


二、日志 & 临时文件清理

1. systemd 日志限制

sudo journalctl --vacuum-time=7d

或永久限制大小:

sudo nano /etc/systemd/journald.conf
SystemMaxUse=200M

然后:

sudo systemctl restart systemd-journald

2. 临时文件

sudo rm -rf /tmp/*

(重启也会自动清)


三、使用工具自动 cleanup(推荐)

✅ 1. unattended-upgrades(自动安全更新 + 清理)

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

编辑:

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

确保包含:

Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";

它会 自动 apt autoremove。


✅ 2. apticron(可选,邮件提醒)

sudo apt install apticron

✅ 3. 使用 debian-goodies 找残留

sudo apt install debian-goodies
dpigs

四、定时自动 cleanup(cron / systemd timer)

方法 A:cron 每天自动清理

sudo crontab -e

添加:

0 3 * * * apt autoremove -y && apt autoclean -y

方法 B:systemd timer(更现代)

创建:

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

[Service]
Type=oneshot
ExecStart=/usr/bin/apt autoremove -y
ExecStart=/usr/bin/apt autoclean -y
sudo nano /etc/systemd/system/cleanup.timer
[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

启用:

sudo systemctl enable --now cleanup.timer

五、进阶(谨慎使用)

删除“手动安装但不再需要”的包

⚠️ 有风险,先看列表:

apt list --installed | grep -v debian

使用 ncdu 查大文件

sudo apt install ncdu
sudo ncdu /

推荐“最小安全自动方案”

✅ unattended-upgrades + apt autoremove + journalctl 限制

如果你告诉我:

  • 是 服务器 / 桌面 / 容器
  • Debian 版本(11/12)
  • 是否 生产环境

我可以给你一套完全可复制的配置文件。

0 踩