定期自动清理CentOS系统可通过以下方式实现,核心方法包括使用cron
定时任务、systemd
定时器及系统自带工具:
cron
定时任务(推荐)创建清理脚本
编写脚本(如/usr/local/bin/cleanup.sh
),包含清理逻辑,例如:
#!/bin/bash
# 清理临时文件
rm -rf /tmp/*
rm -rf /var/tmp/*
# 清理7天前的日志
find /var/log -type f -name "*.log" -mtime +7 -exec rm -f {} \;
# 清理包管理器缓存
yum clean all # 或 dnf clean all
赋予执行权限:chmod +x /usr/local/bin/cleanup.sh
。
配置cron
任务
编辑crontab
文件:sudo crontab -e
,添加定时规则(如每天凌晨2点执行):
0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
保存后可通过crontab -l
查看任务。
systemd
定时器(CentOS 7+)创建服务单元文件
编辑/etc/systemd/system/cleanup.service
:
[Unit]
Description=System Cleanup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh
```。
创建定时器单元文件
编辑/etc/systemd/system/cleanup.timer
:
[Unit]
Description=Run Cleanup Daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
启用并启动定时器:
sudo systemctl enable --now cleanup.timer
。
logrotate
管理日志
编辑/etc/logrotate.conf
或创建自定义配置(如/etc/logrotate.d/myapp
),设置日志轮转和压缩策略,例如:
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
}
手动测试:logrotate -f /etc/logrotate.conf
。
清理YUM/DNF缓存
执行命令:sudo yum clean all
(或dnf clean all
),可结合cron
定期运行。
truncate
清空日志或通过find
按时间删除。/var/log/cleanup.log
确认任务执行情况。以上方法可根据需求选择,cron
适合通用场景,systemd
适合需要精准控制的场景,系统工具则可简化特定清理操作。