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),确认无误后再启用自动化。