[How To] Disk Space Sensor

Hi community,

I’d like to share a small script which you can use to report on the (remaining) disk space of any folder on any system to Home Assistant.

To illustrate, I run a Jellyfin media server next to HA, and I want to be able to see how much disk space there is left on the external HDD that stores my movies/series. The script allows me to present this information nicely in a HA dashboard using a custom sensor, and create an automation that sends a push notification to my phone when the disk space runs low.

# media-disk-space.py

import os
import requests
import shutil

from dotenv import load_dotenv

load_dotenv()

HA_API_KEY = os.getenv('HA_API_KEY')
HA_API_SENSOR_URL = "http(s)://YOUR-HA-URL:8123/api/states/sensor.XYZ_disk_usage"

PATH = "/path/to/your/folder"

GB_DENOMINATOR = 10 ** 9
GIB_DENOMINATOR = 2 ** 30

total, used, free = shutil.disk_usage(PATH)
used_percentage = round((total - free) / total * 100)

headers = {"Authorization": f"Bearer {HA_API_KEY}"}

json = {
    "state": used_percentage,
    "attributes": {
        "friendly_name": "XYZ Disk Usage",
        "used_percentage": used_percentage,
        "total_gb": total // GB_DENOMINATOR,
        "used_gb": used // GB_DENOMINATOR,
        "free_gb": free // GB_DENOMINATOR,
    }
}

response = requests.post(HA_API_SENSOR_URL, headers=headers, json=json)

# print(response.status_code, response.text)

I call the script every 5 minutes using a cronjob, e.g. use crontab -e and then add the following line:

*/5 * * * * <absolute path to your Python executable> <absolute path to media-disk-space.py>

That’s it, hope it may be of use for anybody here.

1 Like

Or use the systemmonitor integration :+1:

I believe using the systemmonitor integration is not possible in my case, because Home Assistant runs within a VM, and the media server does not.

True unless it’s mounted on the HA-server and then it could get that information.

Hi Thijmen.
I’m pretty new in HA and not very familiar with python.
Your script is exactly what I want to do with HA.
What does ```
HA_API_KEY = os.getenv(‘HA_API_KEY’)

Do I have to use the dotenv extension?

Thanks for your reply.

It reads the environment variable HA_API_KEY from your environment variables. In this way, it is not possible for your API key to leak into your GitHub (for example). If you want to go this route, you should find a way to store your Home Assistant API key in your environment variables before executing the Python script.

However, if you do not store your scripts in a GitHub repository, you could just as well hardcode the API key in the Python script.