Debian自动化回收的实用方案
一 核心思路与总体架构
二 方案一 使用 cron 定时回收
0 2 * * * /usr/bin/apt-get update && /usr/bin/apt-get autoremove --purge -y && /usr/bin/apt-get autoclean && /usr/bin/apt-get clean
0 3 * * 0 /usr/bin/journalctl --vacuum-time=2weeks
0 4 * * * /usr/sbin/tmpwatch 7d /tmp
0 2 * * 0 /sbin/fstrim -v /
三 方案二 使用 systemd timer 回收
sudo tee /etc/systemd/system/apt-clean.service >/dev/null <<'EOF'
[Unit]
Description=Apt Cache Cleaner
[Service]
Type=oneshot
ExecStart=/usr/bin/apt-get clean
EOF
sudo tee /etc/systemd/system/apt-clean.timer >/dev/null <<'EOF'
[Unit]
Description=Apt Cache Cleaner Timer
[Timer]
OnCalendar=*-*-* *:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now apt-clean.timer
sudo systemctl list-timers --all | grep apt-clean
四 日志与临时文件的自动化管理
# 保留最近2周
sudo journalctl --vacuum-time=2weeks
# 或限制总大小
sudo journalctl --vacuum-size=100M
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 640 root adm
}
# 可手动强制执行一次
sudo logrotate -f /etc/logrotate.conf
sudo tmpwatch 7d /tmp
五 可选增强与注意事项
sudo apt-get install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
# 示例脚本片段(不建议高频)
sync
echo 3 > /proc/sys/vm/drop_caches
如需定时,请低频执行并充分测试,避免影响性能与稳定性。