一、清理前的准备工作
/etc、/home、数据库文件等),避免误删导致数据丢失。df -h查看磁盘使用率,du -sh /*分析各目录占用情况,确定清理优先级(如/var、/tmp等大目录)。二、常见清理任务清单
rm -rf /tmp/*find /var/tmp -type f -atime +7 -delete。find命令删除旧日志(如7天前的.log文件):find /var/log -type f -name "*.log" -mtime +7 -exec rm -f {} \;logrotate工具配置日志轮转(编辑/etc/logrotate.conf或创建自定义配置,如/etc/logrotate.d/myapp):/var/log/*.log {
daily
rotate 7
compress
missingok
notifempty
create 640 root adm
}
该配置表示日志每日轮转,保留7个压缩归档,空日志不处理。yum clean all && yum clean metadatadnf clean all && dnf clean metadata/var/cache/yum或/var/cache/dnf目录空间。yum autoremove(CentOS 7)或dnf autoremove(CentOS 8)yum list installed或dnf list installed查看已安装软件,卸载不需要的包(如yum remove firefox)。sync && echo 3 > /proc/sys/vm/drop_cachessync命令将缓存数据写入磁盘,避免数据丢失。package-cleanup工具删除旧内核(仅保留1个最新内核):package-cleanup --oldkernels --count=1/boot分区空间,过多会导致无法升级内核。find /path/to/search -type f -size +100M -exec ls -lh {} \;find /path/to/search -type f -mtime +30 -exec rm -f {} \;/path/to/search为目标目录(如/home、/var)。三、自动化清理计划配置
sudo crontab -e添加定时任务(以下为示例):# 每天凌晨2点清理/tmp
0 2 * * * rm -rf /tmp/*
# 每周日2点清理/var/tmp超过7天的文件
0 2 * * 0 find /var/tmp -type f -atime +7 -delete
# 每天3点清理日志(调用logrotate)
0 3 * * * logrotate -f /etc/logrotate.conf
# 每周一3点清理包缓存
0 3 * * 1 yum clean all && dnf clean all
# 每月1号4点清理旧内核
0 4 1 * * package-cleanup --oldkernels --count=1
日志会输出到/var/log/cron,可通过tail -f /var/log/cron查看执行情况。/etc/systemd/system/cleanup.service):[Unit]
Description=CentOS System Cleanup Service
[Service]
Type=oneshot
ExecStart=/bin/bash -c "rm -rf /tmp/* && find /var/tmp -type f -atime +7 -delete && yum clean all && dnf clean all && package-cleanup --oldkernels --count=1"
/etc/systemd/system/cleanup.timer):[Unit]
Description=Run cleanup daily at 2 AM
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable cleanup.timer && sudo systemctl start cleanup.timersystemctl list-timers查看定时器状态。四、注意事项
rm -rf /tmp/*),确认不会误删重要文件。df -h),避免新文件占满空间。weekly,大文件清理可改为每月一次)。bleachbit(sudo yum install bleachbit)图形化清理系统垃圾,适合不熟悉命令的用户。