[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.

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.