1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import subprocess
def check_disk_usage(threshold=80,top_n=5): try: result=subprocess.run(['df','-h'],text=True,capture_output=True,check=True) output=result.stdout # 磁盘使用情况 print("磁盘使用情况:\n",output) # 检查磁盘使用率 lines=output.splitlines() for line in lines[1:]: # 将每行进行切割,返回一个列表 columes=line.split() # 将列表索引4(利用率)提取出来,并且去掉末尾的% percent_userd=int(columes[4].rstrip('%')) # 对比利用率与前面设定的阈值 if percent_userd > threshold: print(f"磁盘使用率超过阈值:{line}") # 获取目录最大文件 result=subprocess.run(['du','-ahx','/'],capture_output=True,text=True,check=True) output=result.stdout lines=output.splitlines() dir_usage={} for line in lines: # 只切割一次,分别赋给size和path size,path=line.split(maxsplit=1) dir_usage[path]=size # 找出使用磁盘最多的目录(size最大的path) sorted_dir=sorted(dir_usage.items(),key=lambda x:x[1],reverse=True) print("占用空间最大的目录:") for path,size in sorted_dir[:top_n]: print(f'{path}:{size}') except subprocess.CalledProcessError as e: print(f"命令执行失败:{e}") except Exception as e: print(f"发生异常:{e}")
check_disk_usage()
|