To monitor the CPU load and send an email if it exceeds a certain threshold, we can write a Python program that utilizes the psutil
library to track the CPU load and the smtplib
library to send an email. Below is a basic implementation:
Step 1: Install necessary libraries
Before running the code, you need to install the required libraries:
pip install psutil
Step 2: The Python Program
import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Configuration
CPU_THRESHOLD = 80 # Set the CPU load threshold to trigger the email alert (in percentage)
EMAIL_SENDER = "your_email@gmail.com"
EMAIL_RECEIVER = "receiver_email@gmail.com"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL_PASSWORD = "your_email_password" # Consider using environment variables for better security
SUBJECT = "CPU Load Alert"
BODY = "Warning! CPU load has exceeded the threshold."
# Function to send email
def send_email(subject, body, receiver_email):
msg = MIMEMultipart()
msg['From'] = EMAIL_SENDER
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
try:
# Set up the server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls() # Use TLS for security
server.login(EMAIL_SENDER, EMAIL_PASSWORD)
# Send the email
text = msg.as_string()
server.sendmail(EMAIL_SENDER, receiver_email, text)
print("Email sent successfully!")
server.quit()
except Exception as e:
print(f"Error sending email: {e}")
# Function to check CPU load
def check_cpu_load():
cpu_load = psutil.cpu_percent(interval=1) # Get CPU usage over 1 second
print(f"Current CPU load: {cpu_load}%")
if cpu_load > CPU_THRESHOLD:
print(f"CPU load exceeded the threshold of {CPU_THRESHOLD}%")
send_email(SUBJECT, BODY, EMAIL_RECEIVER)
if __name__ == "__main__":
check_cpu_load()
Explanation of the Code:
-
Imports:
psutil
: This library is used to retrieve system and CPU-related information, including CPU load.smtplib
: Used for sending emails via SMTP.email.mime.text
andemail.mime.multipart
: Used to format the email content.
-
Configuration:
CPU_THRESHOLD
: Set the threshold for CPU load (e.g., 80%).- Email details (
EMAIL_SENDER
,EMAIL_RECEIVER
, SMTP settings): Set these to your sender's and receiver's email addresses, along with the SMTP server and port for sending emails. For Gmail, the server issmtp.gmail.com
and port is 587. - The email body and subject are predefined but can be customized.
-
send_email Function:
- Composes the email and sends it using the SMTP protocol.
- Uses TLS for secure communication with the mail server.
-
check_cpu_load Function:
- Fetches the current CPU load using
psutil.cpu_percent()
. - If the CPU load exceeds the threshold, it calls
send_email()
to notify the user.
- Fetches the current CPU load using
-
Main Program:
- Runs
check_cpu_load()
to monitor the CPU load and trigger an email alert if needed.
- Runs
Step 3: Setting up Gmail for SMTP (if using Gmail)
If you're using Gmail to send the email, ensure that you have allowed access for less secure apps or use an "App Password" (if 2-factor authentication is enabled). You can set up App Passwords from Google Account settings.
Step 4: Running the Program
Run the Python script by executing the following command:
python cpu_load_monitor.py
Step 5: Automating the Script
To continuously monitor the CPU load, you can either:
- Set it to run at regular intervals using a cron job (Linux/Mac) or Task Scheduler (Windows).
- Add a loop inside the script to keep checking at regular intervals.
Here's a simple way to keep checking every 10 seconds:
import time
if __name__ == "__main__":
while True:
check_cpu_load()
time.sleep(10) # Wait for 10 seconds before checking again
This will continuously monitor the CPU load and send an email whenever the threshold is exceeded.