编写监控程序读取磁盘监控文件/proc/diskstats,找出磁盘读的次数、写的次数,读字节数、磁盘写耗时;
时间: 2023-12-10 19:40:41 浏览: 131
以下是 Python 编写的监控程序,可以读取 /proc/diskstats 文件,并输出磁盘读写次数、读字节数、磁盘写耗时等信息:
```python
import time
def get_disk_stats():
with open('/proc/diskstats', 'r') as f:
data = f.readlines()
disk_stats = {}
for line in data:
fields = line.strip().split()
device_name = fields[2]
reads_completed = int(fields[3])
reads_merged = int(fields[4])
sectors_read = int(fields[5])
ms_spent_reading = int(fields[6])
writes_completed = int(fields[7])
writes_merged = int(fields[8])
sectors_written = int(fields[9])
ms_spent_writing = int(fields[10])
io_in_progress = int(fields[11])
ms_spent_io = int(fields[12])
if device_name.startswith('sd'):
disk_stats[device_name] = {
'reads_completed': reads_completed,
'reads_merged': reads_merged,
'sectors_read': sectors_read,
'ms_spent_reading': ms_spent_reading,
'writes_completed': writes_completed,
'writes_merged': writes_merged,
'sectors_written': sectors_written,
'ms_spent_writing': ms_spent_writing,
'io_in_progress': io_in_progress,
'ms_spent_io': ms_spent_io
}
return disk_stats
def print_disk_stats():
disk_stats_start = get_disk_stats()
time.sleep(1)
disk_stats_end = get_disk_stats()
for device_name, stats_start in disk_stats_start.items():
stats_end = disk_stats_end[device_name]
reads_completed = stats_end['reads_completed'] - stats_start['reads_completed']
writes_completed = stats_end['writes_completed'] - stats_start['writes_completed']
sectors_read = stats_end['sectors_read'] - stats_start['sectors_read']
sectors_written = stats_end['sectors_written'] - stats_start['sectors_written']
ms_spent_reading = stats_end['ms_spent_reading'] - stats_start['ms_spent_reading']
ms_spent_writing = stats_end['ms_spent_writing'] - stats_start['ms_spent_writing']
print(f'Device: {device_name}')
print(f'Reads completed: {reads_completed}')
print(f'Writes completed: {writes_completed}')
print(f'Sectors read: {sectors_read}')
print(f'Sectors written: {sectors_written}')
print(f'Milliseconds spent reading: {ms_spent_reading}')
print(f'Milliseconds spent writing: {ms_spent_writing}')
print('------------------------------------------')
while True:
print_disk_stats()
```
该程序会每秒钟输出一次磁盘读写相关的信息,直到程序被中断。
阅读全文