Created
May 21, 2024 11:41
-
-
Save jcopps/8ab5c2c7023f3eecebc78c430cf267b0 to your computer and use it in GitHub Desktop.
Collect RAM, CPU, Swap and Secondary Storage Utilisation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Dependency: psutil | |
pip3 install psutil | |
""" | |
import psutil | |
import time | |
import json | |
from datetime import datetime | |
def get_system_utilization(): | |
""" | |
Fetch CPU, RAM, and swap utilization. | |
Returns: | |
A dictionary with the following keys: | |
- 'timestamp': The current timestamp | |
- 'cpu_percent': CPU utilization as a percentage | |
- 'cpu_count': Number of CPU cores | |
- 'cpu_freq': Current CPU frequency in MHz | |
- 'ram_total': Total RAM in bytes | |
- 'ram_used': Used RAM in bytes | |
- 'ram_used_percent': RAM utilization as a percentage | |
- 'swap_total': Total swap space in bytes | |
- 'swap_used': Used swap space in bytes | |
- 'swap_used_percent': Swap utilization as a percentage | |
""" | |
timestamp = datetime.now().isoformat() | |
cpu_percent = psutil.cpu_percent(interval=1) | |
cpu_count = psutil.cpu_count() | |
cpu_freq = psutil.cpu_freq().current | |
ram = psutil.virtual_memory() | |
ram_total = ram.total | |
ram_used = ram.used | |
ram_used_percent = ram.percent | |
swap = psutil.swap_memory() | |
swap_total = swap.total | |
swap_used = swap.used | |
swap_used_percent = swap.percent | |
return { | |
'timestamp': timestamp, | |
'cpu_percent': cpu_percent, | |
'cpu_count': cpu_count, | |
'cpu_freq': cpu_freq, | |
'ram_total': ram_total, | |
'ram_used': ram_used, | |
'ram_used_percent': ram_used_percent, | |
'swap_total': swap_total, | |
'swap_used': swap_used, | |
'swap_used_percent': swap_used_percent | |
} | |
def get_disk_utilization(): | |
""" | |
Fetch the total, used, and available disk space. | |
Returns: | |
A dictionary with the following keys: | |
- 'disk_total': Total disk space in bytes | |
- 'disk_used': Used disk space in bytes | |
- 'disk_available': Available disk space in bytes | |
- 'disk_used_percent': Disk utilization as a percentage | |
""" | |
disk = psutil.disk_usage('/') | |
return { | |
'disk_total': disk.total, | |
'disk_used': disk.used, | |
'disk_available': disk.free, | |
'disk_used_percent': disk.percent | |
} | |
if __name__ == "__main__": | |
file_path = "system_utilization.txt" | |
try: | |
while True: | |
system_utilization = get_system_utilization() | |
disk_utilization = get_disk_utilization() | |
data = { | |
'system': system_utilization, | |
'disk': disk_utilization | |
} | |
with open(file_path, "a") as f: | |
f.write(json.dumps(data) + "\n") | |
time.sleep(1) | |
except KeyboardInterrupt: | |
print("\nScript stopped.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment