温馨提示×

如何自动化ubuntu清理

小樊
48
2026-09-02 15:29:07
栏目: 智能运维

在 Ubuntu 上做“自动化清理”通常分三层:临时/缓存清理、日志清理、包与系统清理,再通过 cron / systemd timer 实现自动化。下面给你一套实用方案。


一、手动可用的清理命令(先了解)

1. apt 包清理(最常见)

sudo apt autoremove -y
sudo apt autoclean -y
sudo apt clean -y

2. 用户缓存

rm -rf ~/.cache/*

3. 系统日志

sudo journalctl --vacuum-time=7d
sudo find /var/log -type f -name "*.log" -mtime +7 -delete

4. 旧内核(谨慎)

sudo apt purge $(dpkg -l | grep 'linux-image' | awk '{print $2}' | grep -v `uname -r`)

二、自动化方式一:cron(最简单)

示例:每周日 3 点清理

sudo crontab -e

添加:

0 3 * * 0 apt autoremove -y && apt autoclean -y && journalctl --vacuum-time=7d

✅ 适合:个人服务器、轻量 VPS


三、自动化方式二:systemd timer(推荐)

1. 创建清理脚本

sudo nano /usr/local/bin/ubuntu-clean.sh

内容:

#!/bin/bash
apt autoremove -y
apt autoclean -y
journalctl --vacuum-time=7d
rm -rf /tmp/*
sudo chmod +x /usr/local/bin/ubuntu-clean.sh

2. 创建 service

sudo nano /etc/systemd/system/ubuntu-clean.service
[Unit]
Description=Ubuntu Cleanup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/ubuntu-clean.sh

3. 创建 timer

sudo nano /etc/systemd/system/ubuntu-clean.timer
[Unit]
Description=Weekly Ubuntu Cleanup

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

4. 启用

sudo systemctl enable --now ubuntu-clean.timer

查看:

systemctl list-timers

✅ 适合:生产环境、服务器


四、更省事的工具(可选)

1. bleachbit(GUI + CLI)

sudo apt install bleachbit
sudo bleachbit --clean apt.cache

2. unattended-upgrades(自动安全更新)

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

五、建议策略(实战)

项目 频率
apt autoremove 每周
journalctl 7 天
/tmp 重启或每周
日志 7–30 天
内核 手动或脚本判断

如果你愿意,我可以:

  • 给你 Docker / 云服务器专用清理脚本
  • 帮你写 安全不误删的自动化脚本
  • 针对 Ubuntu 20/22/24 做差异说明

你主要用在什么环境?

0