一个监控未释放已删除文件空间的脚本

具体需求:

1、 需要分析出是视频/data分区个类文件占比(实际文件占比多少,一般实际文件小于占比70%以下大多为已删除文件单未释放磁盘空间)。

2、 需要统计已删除文件但未释放空间的大小(可参考lsof命令)。

3、 根据1和2最终分析结果拿出占比较大的服务列表(针对服务列表建议支持白名单),针对服务列表对已在摆明单内的服务进行重启释放存储空间,未在白名单内的可进行列表打印。

#!/usr/bin/python
#coding:utf-8

import os
import subprocess
import types

#文件占比
data_top10 = "du -sk /* |sort -n  -t ' ' -k 1"
#已删除未释放
data_used = "lsof |grep delete|awk -F ' ' '{print $1,$8}'"
#目前占比
data_now = " df -h |grep /dev/vda1 |awk -F ' '  '{print $5}'|awk -F '%' '{print $1}'"
def subprocess_caller(cmd):
    try:
        p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
        output, error = p.communicate()
    except OSError, e:
        print 'SUBPROCEEE_CALLER function: execute command failed, message is %s' % e
        return dict(output = [], error = [], code = 1)
    else:
        return dict(output = output, error = error, code = 0)

gele = {}
used = {}
dic = {}

#lsof查看没有释放的文件
def lsof_look():
    #获得字符串将其转换成列表
    temp2 = []
    str2 = ''
    for memeda in used['output']:
        if memeda !=' ' and memeda !='
':
            str2 += memeda
        else:
            temp2.append(str2)
            str2 = ''

    #print len(temp2)

    #lsof的列表,列表的拆分
    list3 = []
    list4 = []
    for i in range(len(temp2)):
        if i%2 == 0:
            list3.append(temp2[i])
        else:
            list4.append(temp2[i])

    #为了解决最后一个不能匹配的问题
    list3.append('test')
    list4.append('0')

    #解决统计服务与大小的问题
    list5 = []

    summ = 0
    for i in range(len(list3)-1):
        if list3[i] == list3[i+1]:

            summ += float(list4[i])/1024
            #print summ
        else:
            summ += float(list4[i])/1024
            if dic.has_key(list3[i]):
                dic[list3[i]] += summ
            else:
                dic[list3[i]] = summ
            summ = 0


    for key in dic:
        print '服务:'+key,'所占的空间为(kb):',(dic[key])

#分析十个使用量最高的目录与文件情况
def filerate():
    #将字符串转成列表
    temp = []
    str = ''
    f_dict = {}

    for memeda in gele['output']:
        if memeda != '	' and  memeda != '
':
            str += memeda
        else:
            temp.append(str)
            str = ''

    #将两个列表合成字典
    list1=[]
    list2=[]
    for i in range(len(temp)):
        if i % 2 == 0:
           # if "K" in temp[i]:
            temp[i]=float(temp[i])
           # elif 'M' in temp[i]:
                #temp[i]=float(temp[i].strip('M'))*1024
           # else:
                #temp[i]=float(temp[i].strip('G'))*1024*1024
            list1.append(temp[i])
        else:
            list2.append(temp[i])

    f_dict = dict(zip(list2,list1))
    sss = 0
    for key in f_dict:
        t = f_dict[key]/41943040.0*100
        sss += t
        print '目录:'+key,'所占实际百分比为:%.2f%%' % (t)
    print '=================总占实际比为:%.2f%%'%(sss)
    #print sss
    return sss




if __name__ == '__main__':
    # 各类文件的使用大小情况
    gele = subprocess_caller(data_top10)
    #print gele["output"]
    used = subprocess_caller(data_used)
    #print used['output']
    #df -h 所显示的磁盘占比,这个不是正常的,将其转化为70%的状态
    now = subprocess_caller(data_now)
    now_dick_used = float(now['output'])*0.7
    #print now_dick_used

    k = filerate()
    print("
")
    lsof_look()
    print("
")

    #不可删除的服务名单
    immobilization_list = ['mylala','apache']
    
    flag = 0
    #获取服务字典里面的键值
    key = dic.keys()
    if k<now_dick_used:
        for the_key in key:
            if the_key in immobilization_list:
                continue
            else:
                #cmd = "killall " + the_key
                #os.system(cmd)
                print "33[1;35m已经杀死该服务:33[0m",the_key
                flag = 1
    if flag == 0:
        print "33[1;35m系统状态正常!33[0m"

  

原文地址:https://www.cnblogs.com/bill2014/p/8124292.html