debian

Debian如何自动化回收任务

小樊
42
2025-12-24 07:03:50
栏目: 智能运维

Debian自动化回收任务的实用方案

一 核心思路与工具

二 使用 cron 的自动化清理

#!/usr/bin/env bash
set -e

# 删除 /tmp 中超过 7 天未访问的文件(安全做法:仅文件,不递归删除 /tmp 本身)
find /tmp -mindepth 1 -type f -atime +7 -delete 2>/dev/null || true

# 清理 APT 缓存
apt-get clean

# 清理 systemd 日志(保留最近 7 天)
journalctl --vacuum-time=7d 2>/dev/null || true

# 如存在 Docker,清理无用资源(可选)
if command -v docker >/dev/null 2>&1; then
  docker system prune -af --volumes >/dev/null 2>&1 || true
fi
sudo chmod +x /usr/local/bin/cleanup.sh
sudo /usr/local/bin/cleanup.sh
sudo crontab -e
# 在打开的编辑器中加入:
0 2 * * * /usr/local/bin/cleanup.sh
grep CRON /var/log/syslog

三 使用 systemd 定时器的自动化清理

[Unit]
Description=Daily cleanup job

[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh
[Unit]
Description=Run cleanup daily at 02:00

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now cleanup.timer
sudo systemctl list-timers --all | grep cleanup

四 专项回收与最佳实践

/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 640 root adm
}
sudo apt-get install autotrash
autotrash -d 30
crontab -e
# 加入:
@daily /usr/bin/autotrash -d 30
sudo fstrim /mnt/your_mount_point
sudo crontab -e
# 加入:
0 3 * * 0 /usr/sbin/fstrim /mnt/your_mount_point
# 查找并删除大于 100MB 的文件(谨慎)
find /var -type f -size +100M -exec rm -f {} \; 2>/dev/null

# 查找并删除 .bak 文件
find /var -type f -name "*.bak" -delete 2>/dev/null

0
看了该问题的人还看了