Introduction
Monitoring your server's health in real time is essential to prevent issues before they escalate. In this article, we’ll create a Python script that:
collects system data: memory, CPU, and disk usage,
sends a performance report by email every minute to a system administrator,
runs automatically on an Amazon EC2 instance using cron.
Prerequisites
Before we start, make sure you have:
An Amazon EC2 instance running Amazon Linux 2
Python 3 installed (python3 --version)
- A Gmail account with two-factor authentication enabled
- An app password generated (explained below)
The Python Monitoring Script
Create a file called monitoring.py:
!/usr/bin/env python3
import psutil
import shutil
import smtplib
import os
from email.message import EmailMessage
Collect system stats
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
disk = shutil.disk_usage("/")
Format the message
message = f"""
[Server Monitoring Report]
CPU Usage: {cpu_percent}%
Memory Usage: {memory.percent}%
Available Storage: {disk.free // (2*30)} GB / {disk.total // (2*30)} GB
"""
Email setup
email = EmailMessage()
email.set_content(message)
email["Subject"] = "Server Performance Report"
email["From"] = os.getenv("EMAIL_SENDER")
email["To"] = "testemail@gmail.com"
Send the email
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
smtp.login(os.getenv("EMAIL_SENDER"), os.getenv("EMAIL_PASSWORD"))
smtp.send_message(email)
🔒 Secure Your Credentials with Environment Variables
Never hard-code your credentials into your scripts. Instead, add them to your ~/.bashrc or ~/.bash_profile:
export EMAIL_SENDER="your.email@gmail.com"
export EMAIL_PASSWORD="your_app_password"
Then reload the file:
Automate with Cron
- Install Cron (if not already installed):
sudo yum install cronie -y
sudo systemctl start crond
sudo systemctl enable crond
- Create a Cron Job
Edit your crontab:
crontab -e
Add the following line to run the script every minute:
- * * * * /usr/bin/python3 /home/ec2-user/monitoring.py Adjust the path as necessary.
Output
Every minute, you’ll receive an email like this:
[Server Monitoring Report]
CPU Usage: 12.3%
Memory Usage: 55.7%
Available Storage: 19 GB / 40 GB
Conclusion
With this simple project, you’ve learned how to:
monitor a server using Python, send emails programmatically using SMTP, automate tasks with cron on Amazon Linux. This script can easily be extended to alert you when thresholds are exceeded, monitor multiple servers, or log performance stats to a database.
Top comments (0)