Python监控Linux磁盘写次数

注:部分内容来自书籍或者网络,如有侵权,请联系删除。

/proc/diskstats文件中记录了磁盘的读写次数,读写字节数以及读写延迟等信息。

[root@Ansible Python]# cat /proc/diskstats
8 0 sda 5070 1 235009 43491 2897 172 27879 2177 0 18213 45546
8 1 sda1 1999 0 13163 724 2049 0 4096 548 0 1268 1270
8 2 sda2 3040 1 218502 42737 848 172 23783 1629 0 17377 44246
11 0 sr0 18 0 2056 32 0 0 0 0 0 26 32
253 0 dm-0 2868 0 209334 42693 1020 0 23783 2029 0 17343 44722
253 1 dm-1 91 0 4928 15 0 0 0 0 0 11 15

共14个字段,各个字段的含义如下:

1 - major number
2 - minor mumber
3 - device name
4 - reads completed successfully
5 - reads merged
6 - sectors read
7 - time spent reading (ms)
8 - writes completed
9 - writes merged
10 - sectors written
11 - time spent writing (ms)
12 - I/Os currently in progress
13 - time spent doing I/Os (ms)
14 - weighted time spent doing I/Os (ms)

脚本重点:命名元组namedtuple

#!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import print_function
from colletions import namedtuple

Disk = namedtuple('Disk', 'major_number minor_number device_name'
                  ' read_count read_merged_count read_sections'
                  ' time_spent_reading write_count write_merged_count'
                  ' write_sections time_spent_reading io_requests'
                  ' time_spent_doing_io weighted_time_spent_doing_io')
             
def get_disk_info(device):
    with open("/proc/diskstats") as f:
        for line in f:
            if line.split()[2] == device:
                return Disk(*(line.split()))
    raise RuntimeError("device ({0}) not found".format(device))
 
def main():
    disk_info = get_disk_info('sda')

    print(disk_info)
    print("磁盘写次数:{0}".format(disk_info.write_count))
    print("磁盘写字节数:{0}".format(int(disk_info.write_sections) * 512))
    print("磁盘写延迟:{0}".format(disk_info.time_spent_write))

if __name__ == '__main__':
    main()


「 文章如果对你有帮助,请点个赞哦^^ 」 

0