w3resource

Monitor and Alert System Resource usage with Python

Write a Python tool for monitoring and alerting system resource usage.

The task involves writing a Python tool to monitor system resource usage, such as CPU, memory, and disk utilization, and to send alerts when usage exceeds predefined thresholds. The tool uses the "psutil" library to fetch resource usage data and "smtplib" to send email notifications. It runs continuously, periodically checking the system's resource status and triggering alerts if any thresholds are breached. This tool helps in proactive system management by notifying administrators of potential issues before they become critical.

Sample Solution:

Python Code :

# Import necessary libraries
# Import psutil for system resource monitoring
import psutil
# Import smtplib for sending emails
import smtplib
# Import MIMEText for creating email content
from email.mime.text import MIMEText
# Import MIMEMultipart for handling email attachments
from email.mime.multipart import MIMEMultipart
# Import time for delay management
import time
# Import socket for network operations
import socket

# Define thresholds
# Set the CPU usage threshold
CPU_THRESHOLD = 80  # in percentage
# Set the memory usage threshold
MEMORY_THRESHOLD = 80  # in percentage
# Set the disk usage threshold
DISK_THRESHOLD = 80  # in percentage

# Email settings
# Set the email address to send alerts from
EMAIL_ADDRESS = '[email protected]'
# Set the email password
EMAIL_PASSWORD = 'your_password'
# Set the recipient email address for alerts
ALERT_EMAIL = '[email protected]'
# Set the SMTP server for sending emails
SMTP_SERVER = 'smtp.gmail.com'  # Update to your SMTP server
# Set the SMTP server port
SMTP_PORT = 587

# Function to send an email alert
def send_alert(subject, body):
    # Create a multipart email message
    msg = MIMEMultipart()
    # Set the sender email address
    msg['From'] = EMAIL_ADDRESS
    # Set the recipient email address
    msg['To'] = ALERT_EMAIL
    # Set the email subject
    msg['Subject'] = subject

    # Attach the email body to the message
    msg.attach(MIMEText(body, 'plain'))

    try:
        # Connect to the SMTP server
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        # Start TLS for security
        server.starttls()
        # Log in to the SMTP server
        server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        # Convert the message to a string
        text = msg.as_string()
        # Send the email
        server.sendmail(EMAIL_ADDRESS, ALERT_EMAIL, text)
        # Close the connection to the SMTP server
        server.quit()
        # Print success message
        print(f'Alert sent: {subject}')
    except Exception as e:
        # Print failure message
        print(f'Failed to send alert: {e}')

# Function to check CPU usage
def check_cpu_usage():
    # Get the current CPU usage percentage
    cpu_usage = psutil.cpu_percent(interval=1)
    # If CPU usage exceeds the threshold, send an alert
    if cpu_usage > CPU_THRESHOLD:
        send_alert('CPU Usage Alert', f'CPU usage is at {cpu_usage}%')
    # Return the current CPU usage
    return cpu_usage

# Function to check memory usage
def check_memory_usage():
    # Get memory usage information
    memory_info = psutil.virtual_memory()
    # Get the current memory usage percentage
    memory_usage = memory_info.percent
    # If memory usage exceeds the threshold, send an alert
    if memory_usage > MEMORY_THRESHOLD:
        send_alert('Memory Usage Alert', f'Memory usage is at {memory_usage}%')
    # Return the current memory usage
    return memory_usage

# Function to check disk usage
def check_disk_usage():
    # Get disk usage information
    disk_info = psutil.disk_usage('/')
    # Get the current disk usage percentage
    disk_usage = disk_info.percent
    # If disk usage exceeds the threshold, send an alert
    if disk_usage > DISK_THRESHOLD:
        send_alert('Disk Usage Alert', f'Disk usage is at {disk_usage}%')
    # Return the current disk usage
    return disk_usage

# Function to test DNS resolution
def test_dns_resolution(server):
    try:
        # Attempt to resolve the DNS for the given server
        socket.gethostbyname(server)
        # Print success message if DNS resolution is successful
        print(f'DNS resolution for {server} succeeded.')
    except socket.error as err:
        # Print failure message if DNS resolution fails
        print(f'DNS resolution for {server} failed: {err}')

# Main function to monitor system resources
def monitor_system(interval=60):
    # Test DNS resolution before starting the monitoring loop
    test_dns_resolution(SMTP_SERVER)
    
    # Continuously monitor system resources
    while True:
        # Check and log CPU usage
        cpu_usage = check_cpu_usage()
        # Check and log memory usage
        memory_usage = check_memory_usage()
        # Check and log disk usage
        disk_usage = check_disk_usage()
        
        # Print current usage statistics
        print(f'CPU usage: {cpu_usage}%, Memory usage: {memory_usage}%, Disk usage: {disk_usage}%')
        
        # Wait for the specified interval before checking again
        time.sleep(interval)

# Run the monitoring tool
if __name__ == '__main__':
    # Start monitoring system resources
    monitor_system()

Note:

Before running the script, make sure:

Replace [email protected] and your_password with your actual email and password.

If you are using Gmail, you might need to enable "Less secure app access" or create an App Password if you have 2-step verification enabled.

Output:

DNS resolution for smtp.gmail.com succeeded.
Failed to send alert: (535, b'5.7.8 Username and Password not accepted. For more information, go to\n5.7.8  https://support.google.com/mail/?p=BadCredentials 98e67ed59e1d1-2b628ca53cesm22117151a91.44 - gsmtp')
CPU usage: 4.1%, Memory usage: 35.9%, Disk usage: 92.7%

Explanation:

  • Imports:
  • psutil: Used for monitoring system resources such as CPU, memory, and disk usage.
  • smtplib: Utilized for sending emails through SMTP.
  • MIMEText and MIMEMultipart: Classes from the "email" package to construct the email content and handle attachments.
  • time: Used to introduce delays in the monitoring loop.
  • socket: Employed to test DNS resolution.
  • Thresholds and Email Settings:
  • Defines thresholds for CPU, memory, and disk usage (all set to 80%).
  • Specifies email settings including the sender's email, password, recipient's email, SMTP server, and port.
  • send_alert Function:
  • Constructs an email message using the provided subject and body.
  • Connects to the SMTP server, logs in, and sends the email.
  • Handles exceptions and prints error messages if sending fails.
  • check_cpu_usage Function:
  • Measures the current CPU usage.
  • Sends an alert if the CPU usage exceeds the predefined threshold.
  • Returns the current CPU usage percentage.
  • check_memory_usage Function:
  • Measures the current memory usage.
  • Sends an alert if memory usage exceeds the predefined threshold.
  • Returns the current memory usage percentage.
  • check_disk_usage Function:
  • Measures the current disk usage.
  • Sends an alert if disk usage exceeds the predefined threshold.
  • Returns the current disk usage percentage.
  • test_dns_resolution Function:
  • Attempts to resolve the DNS for the given SMTP server.
  • Prints a success or failure message based on the result of the DNS resolution.
  • monitor_system Function:
  • Tests DNS resolution for the SMTP server before starting the monitoring loop.
  • Enters a loop where it continuously checks CPU, memory, and disk usage.
  • Logs the current resource usage and prints it.
  • Sleeps for a specified interval (default is 60 seconds) before repeating the checks.
  • Main Execution:
  • The "monitor_system()" function is called if the script is run directly.
  • This initiates the continuous monitoring of system resources.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Time Series Forecasting with ARIMA and Pandas.
Next: Building a Rule-Based Chatbot with Python and Regular Expressions

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/advanced/python-tool-for-monitoring-and-alerting-system-resource-usage.php