最近项目需求,做统计磁盘使用情况的自动运行脚本,该脚本还需将统计结果更新到数据库中。我面对两个需要解决的问题,首先为统计磁盘,其次为插入数据库,两件事分开做没什么大的难度,但要求统计并将结果存入数据库却也不是很轻易的事情,忙活了2天终于使用python将其搞定,以下将分享本人解决该问题的心得。
首先解决统计的问题,google后找到解决方案,贴代码
来自 http://stackoverflow.com/questions/4260116/disk-usage-in-linux-using-python
//导入库
import os
from collections import namedtuple
disk_ntuple = namedtuple('partition', 'device mountpoint fstype')
usage_ntuple = namedtuple('usage', 'total used free percent')
//获取当前操作系统下所有磁盘
def disk_partitions(all=False):
"""Return all mountd partitions as a nameduple.
If all == False return phyisical partitions only.
"""
phydevs = []
f = open("/proc/filesystems", "r")
for line in f:
if not line.startswith("nodev"):
phydevs.append(line.strip())
retlist = []
f = open('/etc/mtab', "r")
for line in f:
if not all and line.startswith('none'):
continue
fields = line.split()
device = fields[0]
mountpoint = fields[1]
fstype = fields[2]
if not all and fstype not in phydevs:
continue
if device == 'none':
device = ''
ntuple = disk_ntuple(device, mountpoint, fstype)
retlist.append(ntuple)
return retlist
//统计某磁盘使用情况,返回对象
def disk_usage(path):
"""Return disk usage associated with path."""
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)
total = (st.f_blocks * st.f_frsize)
used = (st.f_blocks - st.f_bfree) * st.f_frsize
try:
percent = ret = (float(used) / total) * 100
except ZeroDivisionError:
percent = 0
# NB: the percentage is -5% than what shown by df due to
# reserved blocks that we are currently not considering:
# http://goo.gl/sWGbH
return usage_ntuple(total, used, free, round(percent, 1))
我将 disk_partitions 函数的返回数组中每个值循环传入 disk_usage,就能获得磁盘的诸如总容量,已使用容量和剩余容量,由于计算原因,有5%的误差。
当然,如果不想获取所有的磁盘,而仅仅获取特定的磁盘,可调用python的函数disk_ntuple(device, mountpoint, fstype),三个参数分别为,设备路径,比如/dev/sda1,第二个参数为挂载路径,如/home ,第三个参数为磁盘的文件系统类型,返回值的属性mountpoint可以作为disk_usage的参数来获得磁盘使用情况,比如返回值为a,可以这样调用disk_usage(a.mountpoint)。