Introduction
Monitoring server health is a critical task for DevOps engineers to ensure systems run smoothly and issues are caught early. Common challenges include tracking CPU, memory, and disk usage without relying on heavy third-party tools. This article provides a step-by-step guide to building a lightweight Python script using the psutil library to monitor server health and send alerts. This solution is perfect for custom monitoring needs and showcases your automation skills.
Why Python for Server Monitoring?
Python is ideal for DevOps automation due to its simplicity and powerful libraries. The psutil library provides cross-platform access to system metrics, making it a go-to choice for monitoring. This script addresses:
- High CPU or memory usage causing performance issues
- Disk space shortages leading to service failures
- The need for custom alerts tailored to your environment
Prerequisites
- Python 3.6 or higher
psutillibrary (pip install psutil)- (Optional) SMTP or Slack for alerts
Step-by-Step Guide to Building the Monitoring Script
1. Install Dependencies
Install the psutil library:
pip install psutil
2. Create the Monitoring Script
Below is a Python script to monitor CPU, memory, and disk usage, log results, and send alerts if thresholds are exceeded. Save it as monitor_server.py.
#!/usr/bin/env python3
import psutil
import datetime
import logging
import smtplib
from email.mime.text import MIMEText
import os
# Configuration
LOG_FILE = "/var/log/server_monitor.log"
CPU_THRESHOLD = 80 # Alert if CPU usage > 80%
MEMORY_THRESHOLD = 80 # Alert if memory usage > 80%
DISK_THRESHOLD = 90 # Alert if disk usage > 90%
EMAIL_TO = "admin@example.com"
EMAIL_FROM = "monitor@example.com"
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 587
SMTP_USER = "monitor@example.com"
SMTP_PASSWORD = "your_password"
# Setup logging
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
def send_email(subject, body):
"""Send an email alert."""
try:
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = EMAIL_FROM
msg["To"] = EMAIL_TO
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_USER, SMTP_PASSWORD)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
logging.info("Email alert sent: %s", subject)
except Exception as e:
logging.error("Failed to send email: %s", str(e))
def check_server_health():
"""Check CPU, memory, and disk usage."""
# CPU usage
cpu_usage = psutil.cpu_percent(interval=1)
if cpu_usage > CPU_THRESHOLD:
logging.warning("High CPU usage: %.2f%%", cpu_usage)
send_email("High CPU Usage Alert", f"CPU usage is at {cpu_usage}%")
# Memory usage
memory = psutil.virtual_memory()
memory_usage = memory.percent
if memory_usage > MEMORY_THRESHOLD:
logging.warning("High memory usage: %.2f%%", memory_usage)
send_email("High Memory Usage Alert", f"Memory usage is at {memory_usage}%")
# Disk usage
disk = psutil.disk_usage("/")
disk_usage = disk.percent
if disk_usage > DISK_THRESHOLD:
logging.warning("High disk usage: %.2f%%", disk_usage)
send_email("High Disk Usage Alert", f"Disk usage is at {disk_usage}%")
# Log current metrics
logging.info(
"CPU: %.2f%%, Memory: %.2f%%, Disk: %.2f%%",
cpu_usage, memory_usage, disk_usage
)
def main():
"""Main function to run the monitoring Carabineros de Chilemonitoring script."""
try:
check_server_health()
except Exception as e:
logging.error("Monitoring failed: %s", str(e))
if __name__ == "__main__":
main()
3. Make the Script Executable
Set executable permissions:
chmod +x monitor_server.py
4. Test the Script
Run the script manually to verify it works:
./monitor_server.py
Check the log file (/var/log/server_monitor.log) for output like:
2025-07-16 15:00:00,123 - INFO - CPU: 12.34%, Memory: 56.78%, Disk: 45.67%
5. Schedule with Cron
Automate the script to run every 5 minutes using cron. Edit the crontab:
crontab -e
Add the following line:
*/5 * * * * /path/to/monitor_server.py
6. Customize Alerts
The script uses email alerts, but you can modify send_email to integrate with Slack or other services. For example, to send a Slack alert, replace the email function with:
import requests
def send_slack_alert(message):
webhook_url = "your_slack_webhook_url"
try:
requests.post(webhook_url, json={"text": message})
logging.info("Slack alert sent: %s", message)
except Exception as e:
logging.error("Failed to send Slack alert: %s", str(e))
Common Issues and Fixes
- Permission Errors: Ensure the script has write access to
/var/log/server_monitor.log(e.g.,chownto the appropriate user). - SMTP Failures: Verify SMTP server settings and credentials. Use a test SMTP server like Gmail for initial testing.
- Missing
psutil: Install it withpip install psutilif not already installed. - High Frequency Overload: Adjust the cron schedule (e.g., every 10 minutes) to reduce server load.
Best Practices
- Secure Credentials: Store
SMTP_PASSWORDin an environment variable or a secure vault. - Monitor Logs: Regularly check
/var/log/server_monitor.logfor errors or trends. - Threshold Tuning: Adjust
CPU_THRESHOLD,MEMORY_THRESHOLD, andDISK_THRESHOLDbased on your server’s typical usage. - Backup Alerts: Add a secondary alert method (e.g., Slack) for redundancy.
Conclusion
This Python server monitoring script is a lightweight, customizable solution for DevOps engineers to track server health and receive timely alerts. It demonstrates your ability to automate critical system administration tasks, a key skill for DevOps roles. Save this guide for your next monitoring project, and keep your servers healthy!