温馨提示×

CentOS清理无用文件步骤

小樊
80
2025-11-29 21:32:31
栏目: 智能运维

CentOS 清理无用文件步骤

一 准备与风险

  • 以具有 sudo 权限的账户操作,先确认磁盘占用:df -h,定位大目录:du -sh / | sort -h*。
  • 清理前对重要数据做备份,并在变更窗口内执行,避免影响线上业务。
  • 谨慎删除正在被进程使用的文件,必要时先停止相关服务或安排在维护时段执行。

二 标准清理流程

  1. 清理临时文件
    • 手动清理:sudo rm -rf /tmp/ /var/tmp/**。
    • 使用 systemd-tmpfiles:sudo systemd-tmpfiles --clean(按配置清理 /tmp、/var/tmp 等)。
    • 按时间清理旧临时文件:sudo find /tmp -type f -mtime +7 -delete 与 sudo find /var/tmp -type f -mtime +7 -delete。
  2. 清理包管理器缓存
    • sudo yum clean all(CentOS 7)。
    • sudo dnf clean all(CentOS 8+)。
  3. 清理日志与 journald
    • 查看日志占用:sudo du -sh /var/log/ | sort -h*。
    • 按时间收缩 journal:sudo journalctl --vacuum-time=30d(保留最近 30 天)。
    • 按大小收缩 journal:sudo journalctl --vacuum-size=500M。
    • 轮转并压缩旧日志:sudo logrotate -f /etc/logrotate.conf。
  4. 删除无用依赖与旧内核
    • 移除孤立包:sudo yum autoremove -y。
    • 查看当前内核:uname -r。
    • 删除旧内核(保留最近 2 个):sudo package-cleanup --oldkernels --count=2。
  5. 清理用户级缓存与回收站
    • 用户缓存:rm -rf ~/.cache/ ~/.local/share/Trash/ ~/.mozilla/firefox//Cache/ ~/.config/google-chrome/Default/Cache/*(按需)**。
  6. 可选 清理文件系统缓存(仅当内存紧张且可接受短时性能波动时)
    • 执行:sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches(仅清理页面/目录项/inode 缓存,不影响持久数据)。

三 定位大文件与目录

  • 快速查看各目录占用:sudo du -sh / | sort -h*。
  • 查找大于 100MB 的文件:sudo find / -type f -size +100M -exec ls -lh {} ; 2>/dev/null。
  • 交互式分析工具:sudo yum install -y ncdu && sudo ncdu /(方向键导航,d 删除)。

四 自动化与维护

  • 定时清理临时文件与缓存(示例每天 02:00 执行):
    • 新建脚本 /usr/local/bin/cleanup.sh:
      #!/bin/bash
      systemd-tmpfiles --clean
      find /tmp -type f -mtime +7 -delete
      find /var/tmp -type f -mtime +7 -delete
      yum clean all 2>/dev/null || dnf clean all 2>/dev/null
      journalctl --vacuum-time=30d
      logrotate -f /etc/logrotate.conf
      
    • 赋权并加入 cron:sudo chmod +x /usr/local/bin/cleanup.sh && sudo crontab -e,添加:
      0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
      
  • 建议保留至少 2 个可用内核,避免回滚失败;变更前在测试环境验证脚本。

0 踩