centos

如何定期自动清理centos

小樊
42
2025-09-07 21:40:51
栏目: 智能运维

定期自动清理CentOS系统可通过以下方式实现,核心方法包括使用cron定时任务、systemd定时器及系统自带工具:

一、使用cron定时任务(推荐)

  1. 创建清理脚本
    编写脚本(如/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

  2. 配置cron任务
    编辑crontab文件:sudo crontab -e,添加定时规则(如每天凌晨2点执行):
    0 2 * * * /usr/local/bin/cleanup.sh >> /var/log/cleanup.log 2>&1
    保存后可通过crontab -l查看任务。

二、使用systemd定时器(CentOS 7+)

  1. 创建服务单元文件
    编辑/etc/systemd/system/cleanup.service

    [Unit]
    Description=System Cleanup Service
    [Service]
    Type=oneshot
    ExecStart=/usr/local/bin/cleanup.sh
    ```。
    
    
  2. 创建定时器单元文件
    编辑/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

三、利用系统工具辅助清理

四、注意事项

以上方法可根据需求选择,cron适合通用场景,systemd适合需要精准控制的场景,系统工具则可简化特定清理操作。

0
看了该问题的人还看了