# Disk Usage Monitor

This utility monitors the disk usage of a specific path (e.g., `/` or `C:\`) and sends an email alert if the free space falls below a defined threshold (percentage).

**Modules Used:**
*   [[programming/python/modules/shutil-module|shutil]]: To check disk usage statistics.
*   [[programming/python/modules/smtplib-module|smtplib]]: To send email alerts.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.
*   [[programming/python/modules/python-dotenv-module|python-dotenv]]: To securely manage email credentials.

## Setup

Create a `.env` file in your project directory:
```text
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_app_password
ALERT_RECEIVER=admin@example.com
```

## The Code

Save this as `disk_monitor.py`.

```python
import shutil
import smtplib
import argparse
import os
from dotenv import load_dotenv
from email.message import EmailMessage

# Load Config
load_dotenv()

def send_alert(path, free_percent, free_gb):
    """Sends an email alert about low disk space."""
    msg = EmailMessage()
    msg.set_content(f"WARNING: Low disk space on '{path}'!\n\nFree Space: {free_percent:.2f}%\nAvailable: {free_gb:.2f} GB")
    msg['Subject'] = f"Disk Space Alert: {path}"
    msg['From'] = os.getenv("EMAIL_USER")
    msg['To'] = os.getenv("ALERT_RECEIVER")

    try:
        # Using Gmail SMTP server as an example
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login(os.getenv("EMAIL_USER"), os.getenv("EMAIL_PASS"))
            server.send_message(msg)
        print(f"Alert email sent to {os.getenv('ALERT_RECEIVER')}")
    except Exception as e:
        print(f"Failed to send alert: {e}")

def check_disk_usage(path, threshold):
    try:
        total, used, free = shutil.disk_usage(path)
        
        free_percent = (free / total) * 100
        free_gb = free / (2**30) # Convert bytes to GB
        
        print(f"Disk Usage for '{path}':")
        print(f"  Total: {total / (2**30):.2f} GB")
        print(f"  Used:  {used / (2**30):.2f} GB")
        print(f"  Free:  {free_gb:.2f} GB ({free_percent:.2f}%)")
        
        if free_percent < threshold:
            print(f"\n[!] Free space is below {threshold}%. Sending alert...")
            send_alert(path, free_percent, free_gb)
        else:
            print("\nStatus: OK")
            
    except FileNotFoundError:
        print(f"Error: Path '{path}' not found.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Disk Usage Monitor")
    parser.add_argument("path", help="Path to monitor (e.g., / or C:\\)")
    parser.add_argument("--threshold", type=float, default=20.0, help="Free space threshold percentage (default: 20)")
    
    args = parser.parse_args()
    
    check_disk_usage(args.path, args.threshold)
```

## Usage

```bash
# Check root directory, alert if free space < 15%
python disk_monitor.py / --threshold 15
```

[[programming/python/python]]