main.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import subprocess
  2. import re
  3. import time
  4. disks = ['sda', 'sdb', 'sdc', 'sdd'] # List of disks to monitor
  5. while True:
  6. cmd = "iostat -xk 1 2 " + " ".join(disks)
  7. process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  8. output, _ = process.communicate()
  9. lines = output.decode().split('\n')
  10. disk_info = {}
  11. current_disk = ''
  12. for line in lines:
  13. if line.startswith('Device'):
  14. headers = re.findall(r'\S+', line)
  15. elif line.startswith(tuple(disks)):
  16. io_data = re.findall(r'\S+', line)
  17. if len(io_data) >= len(headers):
  18. current_disk = io_data[0]
  19. disk_info[current_disk] = {headers[i]: io_data[i] for i in range(1, len(headers))}
  20. for disk in disks:
  21. if disk in disk_info:
  22. read_bytes = disk_info[disk].get('rkB/s', '0.00')
  23. write_bytes = disk_info[disk].get('wkB/s', '0.00')
  24. if float(read_bytes) > 0 or float(write_bytes) > 0:
  25. print(f"R/W activity detected on /dev/{disk}:")
  26. print(f"Read bytes: {read_bytes}, Write bytes: {write_bytes}")
  27. time.sleep(1) # Adjust the frequency of checking disk activity (1 second in this example)