DEV Community

Emmanuel Onesime
Emmanuel Onesime

Posted on

🔧 Monitoring Server Health with a Python Script That Runs Every Minute

Introduction
In any production environment, monitoring server performance is essential for maintaining availability and preventing system failures. For system administrators, real-time information about memory, CPU, and disk usage is crucial to ensure that infrastructure remains healthy.
In this article, we'll walk through creating a Python script that runs every minute, collects server health metrics, and sends a report via email to a system administrator. We'll also log each execution and use tail -f to monitor logs in real-time.
Steps to Follow:
Prepare Your Environment

1.1 First, create a Python virtual environment:

Image description
1.2 install the required packages:

Image description

  1. Create a .env File for Your Secrets In your home directory, create the file /home/emma/.env with the following content (replace with your actual credentials):

Image description
Notice: The EMAIL_PASSWORD is your Google App Password, not your real Gmail password.

  1. Write the Python Script Create the file /home/emma/server_health_report.py with the following code:

Image description

  1. Schedule the Script to Run Every Minute 4.1 Edit your crontab:

Image description
4.2 Add the following line:
****/home/emma/env/bin/python3/home/emma/server_health_report.y

Image description

  1. Monitor the Log in Real-Time

Image description

Image description
Conclusion
By following these steps, you've built an automated monitoring system using Python that runs every minute, gathers key server metrics, logs the results, and sends real-time performance data via email. This setup enhances visibility and helps system administrators react promptly to any issues - improving reliability and efficiency in server management.

Top comments (0)