温馨提示×

能否自动进行ubuntu cleanup

小樊
45
2026-09-17 20:20:06
栏目: 智能运维

可以的。Ubuntu 可以自动进行 cleanup(清理),常见做法有几种,从“系统自带自动清理”到“定时任务自动清理”都可以。下面按由简到实用的方式给你说明。


一、Ubuntu 自带的自动清理机制(最省心)

1. apt 自动清理旧包(推荐开启)

Ubuntu 默认会保留已下载的 .deb 缓存,但可以自动删除不用的版本:

sudo apt install unattended-upgrades

然后确保以下配置存在(/etc/apt/apt.conf.d/50unattended-upgrades):

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

✅ 效果:

  • 自动安装安全更新
  • 自动删除无用依赖
  • 不需要你手动 apt autoremove

二、使用 systemd 定时器(现代方式,推荐)

2. 自动执行 cleanup(示例)

你可以创建一个 systemd timer,比如每周清理一次。

创建 service

sudo nano /etc/systemd/system/ubuntu-cleanup.service

内容:

[Unit]
Description=Ubuntu Cleanup

[Service]
Type=oneshot
ExecStart=/usr/bin/apt-get autoremove -y
ExecStart=/usr/bin/apt-get autoclean -y
ExecStart=/bin/journalctl --vacuum-time=7d

创建 timer

sudo nano /etc/systemd/system/ubuntu-cleanup.timer

内容:

[Unit]
Description=Run Ubuntu Cleanup Weekly

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

启用:

sudo systemctl enable --now ubuntu-cleanup.timer

✅ 每周自动:

  • 删除无用包
  • 清理 apt 缓存
  • 清理旧日志

三、使用 cron(传统方式)

如果你更习惯 cron:

sudo crontab -e

添加:

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

意思是:每周日 3 点自动清理


四、可额外自动清理的内容

你可以根据需求加入:

# 清理缩略图
rm -rf ~/.cache/thumbnails/*

# 清理旧内核(谨慎)
apt-get autoremove --purge

# 清理 snap 旧版本
snap list --all | awk '/disabled/{print $1, $3}' | while read snap rev; do snap remove "$snap" --revision="$rev"; done

五、不推荐“全自动 rm -rf”的原因

⚠️ 避免写:

rm -rf /var/log/*

容易造成:

  • 系统无法启动
  • 日志丢失,难以排查问题

总结(最简单方案)

✅ 新手推荐:

  • 开启 unattended-upgrades
  • 开启 Remove-Ununused-Dependencies

✅ 进阶推荐:

  • systemd timer 每周 cleanup

如果你愿意,我可以:

  • 给你一份可直接复制的脚本
  • 或针对 服务器 / 桌面版 给你定制方案

0 踩