Python program to monitor disk usage in EC2

Here we will write a Python program to monitor disk usage in AWS EC2 instance, you can use this to on any Linux flavor.

import os

def get_disk_usage():
    total, used, free = os.popen("df -h /").readlines()[1].split()[1:4]
    return {
        "total": total,
        "used": used,
        "free": free
    }

if __name__ == "__main__":
    usage = get_disk_usage()
    print("Disk usage:")
    print(f"Total: {usage['total']}")
    print(f"Used: {usage['used']}")
    print(f"Free: {usage['free']}")

EXPLANATION:

This script uses the df command to get information about the disk space usage on the root partition (“/”). The get_disk_usage() function runs the command and parses the output to extract the total, used, and free space in a human-readable format. The function returns a dictionary with these values.

The script then prints out the disk usage information. You can customize the script to monitor space usage for different partitions or directories by modifying the path passed to the df command. Additionally, you can add functionality to alert you when the disk usage exceeds a certain threshold.

Leave a Comment