环境:
Centos7
前情:
有台临时存储日志的服务器磁盘经常爆满,使用python 和 crontab 配合自动删除早期的文件。
0x01 直接上代码,有注释
import os, time
import psutildef rm_run(dir_path):# 开启循环while True:# 查看 当前 磁盘或分区的使用率usage_percent = psutil.disk_usage("/service").percent# 当使用率大于 90% 的时候则触发清理操作if usage_percent > 90:# 获取 1 小时之前的时间one_hour_time = time.time() - 3600# 遍历 目录下的文件路径for c in os.listdir(dir_path):# 获取 文件 时间属性,方便后期对比file_ctime = os.stat("%s/%s" % (dir_path, c)).st_ctime# 判断 文件时间 是否小于 one_hour_timeif one_hour_time > file_ctime:# 使用os.popen 执行删除命令res = os.popen("rm -rf %s/%s" % (dir_path, c))# 打印处理结果print(res.read())else:# 如果 文件时间 大于 one_hour_time,则 passpasselse:# 使用率不超过90% ,则 passpassif __name__ == "__main__":dir_path = "/service"rm_run(dir_path)