欢迎访问宙启技术站
智能推送

用Python编写一个简单的远程服务器监控程序

发布时间:2023-12-04 14:03:44

import psutil

import time

import smtplib

from email.mime.text import MIMEText

from email.header import Header

def send_email(server, port, sender, password, receiver, message):

    # 创建SMTP对象

    smtp_obj = smtplib.SMTP()

    # 连接到SMTP服务器

    smtp_obj.connect(server, port)

    # 登录SMTP服务器

    smtp_obj.login(sender, password)

    # 构造邮件内容

    msg = MIMEText(message, "plain", "utf-8")

    # 设置邮件标题和发件人、收件人

    msg["Subject"] = Header("服务器运行异常", "utf-8")

    msg["From"] = sender

    msg["To"] = receiver

    # 发送邮件

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

    # 关闭SMTP连接

    smtp_obj.quit()

def monitor_server(server_name, cpu_threshold, memory_threshold, monitor_interval, email_server, email_port, email_sender, email_password, email_receiver):

    while True:

        # 获取CPU使用率

        cpu_percent = psutil.cpu_percent()

        # 获取内存使用率

        memory_percent = psutil.virtual_memory().percent

        # 判断CPU和内存使用率是否超过阈值

        if cpu_percent > cpu_threshold or memory_percent > memory_threshold:

            message = f"服务器 {server_name} 的 CPU 使用率为 {cpu_percent}%,内存使用率为 {memory_percent}%,已超过阈值"

            # 发送邮件通知

            send_email(email_server, email_port, email_sender, email_password, email_receiver, message)

        

        # 休眠指定的时间间隔

        time.sleep(monitor_interval)

# 使用例子

if __name__ == "__main__":

    server_name = "Remote Server"

    cpu_threshold = 80  # 设置CPU使用率的阈值,超过80%会发送邮件通知

    memory_threshold = 90  # 设置内存使用率的阈值,超过90%会发送邮件通知

    monitor_interval = 60  # 监控间隔为60秒

    email_server = "smtp.example.com"  # 邮件服务器地址

    email_port = 25  # 邮件服务器端口

    email_sender = "sender@example.com"  # 发件人邮箱

    email_password = "password"  # 发件人邮箱密码

    email_receiver = "receiver@example.com"  # 收件人邮箱

    # 启动远程服务器监控程序

    monitor_server(server_name, cpu_threshold, memory_threshold, monitor_interval, email_server, email_port, email_sender, email_password, email_receiver)