Project: Python Resource Monitor
In this project, you will build a production-grade server watchdog script. This tool monitors CPU and RAM usage and sends an automated email alert if any resource exceeds a defined threshold.
Prerequisites
- Python 3.x installed.
- psutil: A library for retrieving information on running processes and system utilization.
- smtplib: Python's built-in library for sending emails via SMTP.
- App Password: Required if you're using Gmail or similar providers for security.
Step 1: Install Dependencies
Open your terminal and install the psutil library.
pip install psutilStep 2: Create the Watchdog Script
Create a file named resource_monitor.py and add the following logic.
import psutil
import smtplib
import time
import logging
# --- CONFIGURATION ---
CPU_THRESHOLD = 80 # Trigger alert if > 80%
RAM_THRESHOLD = 75 # Trigger alert if > 75%
CHECK_INTERVAL = 60 # Seconds between checks
# Email Settings (Use Environment Variables for Production!)
EMAIL_FROM = "your-email@gmail.com"
EMAIL_TO = "admin@example.com"
EMAIL_PW = "your-app-password" # App-specific password
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
def send_alert(message):
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(EMAIL_FROM, EMAIL_PW)
server.sendmail(EMAIL_FROM, EMAIL_TO, f"Subject: SERVER ALERT!\n\n{message}")
print("âś… Alert email sent successfully.")
except Exception as e:
print(f"❌ Failed to send email: {e}")
while True:
cpu_usage = psutil.cpu_percent(interval=1)
ram_usage = psutil.virtual_memory().percent
print(f"[{time.ctime()}] CPU: {cpu_usage}% | RAM: {ram_usage}%")
if cpu_usage > CPU_THRESHOLD or ram_usage > RAM_THRESHOLD:
alert_msg = f"Warning: Resource usage exceeded threshold. CPU: {cpu_usage}%, RAM: {ram_usage}%"
send_alert(alert_msg)
time.sleep(CHECK_INTERVAL)Step 3: Security Basics (App Passwords)
Modern email providers (like Gmail) do not allow basic login for scripts. You must create an App Password:
- Go to your Google Account settings.
- Search for App Passwords.
- Select "Other" and name it "Python Monitor".
- Use the generated 16-character code in your
EMAIL_PWvariable.
Step 4: Run and Test
Execute your script in the background or a terminal session:
python3 resource_monitor.pyHow to Verify
To test the alert logic, you can temporarily lower your thresholds to 10% inside the script. This will trigger an alert based on your normal background activity.
Summary of Logic
| Component | Responsibility |
|---|---|
| psutil | Fetches real-time system metrics. |
| smtplib | Handles the SMTP handshake and email delivery. |
| While Loop | Keeps the watchdog running 24/7. |
| Conditionals | Decides if an alert is necessary. |
[!CAUTION] Hardcoded Passwords Never commit your email passwords to Git. For production systems, use environment variables (
os.environ.get('EMAIL_PW')) or a secrets manager.