用python监控服务器的cpu,磁盘空间,内存,超过邮件

1. Introduction

Monitoring the CPU, disk space, and memory of a server is crucial for ensuring its smooth performance. In this article, we will explore how to use Python to monitor these resources and send an email notification when they exceed certain thresholds. We will cover each aspect in detail, including the code snippets and explanations.

2. Monitoring CPU Usage

2.1 Installing Required Libraries

To monitor CPU usage, we need to install the psutil library. It provides an easy way to retrieve system information, including CPU usage.

pip install psutil

2.2 Retrieving CPU Usage

Once the psutil library is installed, we can use it to retrieve the CPU usage. The following code snippet demonstrates how to get the current CPU usage:

import psutil

cpu_usage = psutil.cpu_percent(interval=1)

print(f"Current CPU Usage: {cpu_usage}%")

In the above code, we import the psutil library and use the cpu_percent() method to retrieve the CPU usage. The interval parameter specifies the time interval in seconds to measure the CPU usage. In this example, we set it to 1 second.

2.3 Setting Threshold and Sending Email Notification

After retrieving the CPU usage, we can compare it with a threshold value to determine if it is exceeding the limit. If it exceeds, an email notification can be sent. Let's see the code snippet below:

import smtplib

from email.mime.text import MIMEText

def send_email(subject, message):

# email configuration

sender = 'your_email@example.com'

receiver = 'recipient_email@example.com'

password = 'your_password'

# create message object

msg = MIMEText(message)

msg['Subject'] = subject

msg['From'] = sender

msg['To'] = receiver

# send the email

try:

server = smtplib.SMTP('smtp.gmail.com', 587)

server.starttls()

server.login(sender, password)

server.sendmail(sender, receiver, msg.as_string())

server.quit()

print("Email sent successfully!")

except Exception as e:

print(f"Failed to send email: {e}")

threshold = 80 # set the threshold here

if cpu_usage > threshold:

subject = "CPU Usage Exceeded Threshold"

message = f"The CPU usage ({cpu_usage}%) has exceeded the threshold of {threshold}%."

send_email(subject, message)

In the above code, we define a function send_email() to send an email using the smtplib library. We set the email configuration, including the sender's and receiver's email addresses and the password. The MIMEText class is used to create the message object.

We set a threshold value, and if the CPU usage exceeds this threshold, an email notification is sent with the subject and message. This is just a basic implementation, and you can customize it further to suit your needs.

3. Monitoring Disk Space

(以下内容和CPU监控基本相同,穷切籍??)

后端开发标签