CentOS Cleanup可以通過多種方式實現自動化運行,以下是常見的幾種方法,覆蓋系統自帶工具與自定義腳本場景:
systemd定時器是更靈活、精準的定時任務管理工具,適合需要精細控制執行時間的場景。
/etc/systemd/system/centos-cleanup.service,內容如下(以清理YUM緩存為例):[Unit]
Description=CentOS Cleanup Service
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/centos-cleanup --enablerepo=updates --nocleanall
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
/etc/systemd/system/centos-cleanup.timer,定義執行頻率(如每周一次,系統啟動后5分鐘首次運行):[Unit]
Description=Run CentOS Cleanup Service periodically
[Timer]
OnBootSec=5min
OnUnitActiveSec=1week
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable centos-cleanup.timer
sudo systemctl start centos-cleanup.timer
sudo systemctl list-timers --all # 查看所有定時器
sudo systemctl status centos-cleanup.timer # 查看指定定時器狀態
該方法無需額外安裝工具,且支持依賴管理和精準調度。cron是CentOS默認的時間調度工具,適合簡單的周期性任務(如每天、每小時執行)。
/usr/local/bin/cleanup.sh,添加清理邏輯(如清理/tmp、日志、YUM緩存):#!/bin/bash
echo "Cleaning /tmp directory..."
rm -rf /tmp/*
echo "Cleaning old log files..."
find /var/log -type f -name "*.log" -mtime +7 -exec rm -f {} \;
echo "Cleaning YUM cache..."
yum clean all
echo "Cleanup completed at $(date)" >> /var/log/cleanup.log
chmod +x /usr/local/bin/cleanup.sh
crontab -e,添加一行(如每天凌晨2點執行):0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
該方法兼容性好,適合大多數CentOS版本。CentOS提供了一些內置工具,可自動化處理特定清理任務,無需手動編寫腳本:
sudo yum install -y yum-cron
sudo systemctl start yum-cron
sudo systemctl enable yum-cron
編輯/etc/yum/yum-cron.conf,設置clean_requirements_on_remove=yes以自動清理無用依賴。/etc/logrotate.conf或創建自定義配置(如/etc/logrotate.d/myapp):/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
create 640 root adm
}
該工具會自動壓縮、刪除舊日志,避免日志文件占用過多空間。若需要更全面的清理功能(如清理內存、舊內核、用戶緩存),可使用第三方工具如BleachBit:
sudo yum install -y bleachbit
bleachbit-cli)選擇清理項目(如“系統臨時文件”“瀏覽器緩存”),并設置定時任務。注意事項:
/home、/etc),避免誤刪。sudo /usr/local/bin/cleanup.sh),確認無誤后再啟用自動化。