一、编写自动化清理脚本
首先创建一个包含常用清理任务的Bash脚本,覆盖系统日志、临时文件、APT缓存、旧内核等关键区域。示例如下:
#!/bin/bash
# 清理系统日志(保留最近2周)
echo "Cleaning system logs..."
sudo journalctl --vacuum-time=2weeks
# 清理临时文件(/tmp和/var/tmp)
echo "Cleaning temporary files..."
sudo rm -rf /tmp/* /var/tmp/*
# 清理APT包缓存(删除已下载的包文件)
echo "Cleaning APT package cache..."
sudo apt-get clean
# 清理旧的内核版本(保留最新的2个内核)
echo "Cleaning old kernels..."
dpkg --list | grep '^ii' | sed -n '/linux-image-/p' | awk '{print $2}' | sort -V | uniq | tail -n +3 | xargs sudo apt-get -y purge --auto-remove
# 清理孤立的无用软件包
echo "Cleaning orphaned packages..."
sudo apt-get autoremove --purge -y
echo "Cleanup completed."
将脚本保存为/usr/local/bin/debian_cleanup.sh,并赋予执行权限:
sudo chmod +x /usr/local/bin/debian_cleanup.sh
二、使用Cron设置定时任务
通过Cron定时调用上述脚本,实现定期自动清理。编辑root用户的crontab文件:
sudo crontab -e
添加以下行(例如每天凌晨2点执行):
0 2 * * * /usr/local/bin/debian_cleanup.sh >> /var/log/debian_cleanup.log 2>&1
说明:
0 2 * * *:表示每天凌晨2点执行;>> /var/log/debian_cleanup.log 2>&1:将脚本输出(包括错误信息)追加到日志文件,便于后续查看。三、利用Systemd定时器(可选)
若系统使用systemd,可通过创建服务单元和定时器单元实现更灵活的定时任务。步骤如下:
/etc/systemd/system/debian-cleanup.service):[Unit]
Description=Debian System Cleanup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/debian_cleanup.sh
/etc/systemd/system/debian-cleanup.timer):[Unit]
Description=Run Debian cleanup daily at 2 AM
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable --now debian-cleanup.timer
通过systemctl list-timers可查看定时器状态。
四、借助现有工具增强清理
sudo apt install bleachbit
sudo bleachbit --clean system.cache system.tmp system.logs
/etc/logrotate.d/myapp):/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
create 640 root adm
}
此配置表示每天轮转日志,保留最近7天的压缩日志。
五、注意事项
/home、/etc等关键目录,避免误删。df -h查看磁盘使用情况,确保清理效果。