linux监控服务器磁盘、内存空间使用率到达90%发送邮件脚本

以下是一个使用Python编写的Linux监控服务器磁盘、内存空间使用率并在达到90%时发送邮件的脚本:

import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 设置阈值
DISK_THRESHOLD = 90
MEMORY_THRESHOLD = 90

# 获取磁盘使用率
def get_disk_usage():
    disk = os.statvfs("/")
    total = disk.f_blocks * disk.f_frsize
    used = (disk.f_blocks - disk.f_bfree) * disk.f_frsize
    usage = int(used / total * 100)
    return usage

# 获取内存使用率
def get_memory_usage():
    with open('/proc/meminfo', 'r') as mem:
        free_memory = 0
        total_memory = 0
        for i in mem:
            sline = i.split()
            if str(sline[0]) == 'MemTotal:':
                total_memory = int(sline[1])
            elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                free_memory += int(sline[1])
        used_memory = total_memory - free_memory
        usage = int(used_memory / total_memory * 100)
        return usage

# 发送邮件
def send_email(subject, content):
    sender = 'your_email@example.com'
    receivers = ['receiver_email@example.com']
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header("Server Monitor", 'utf-8')
    message['To'] = Header("Admin", 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

# 主函数
def main():
    disk_usage = get_disk_usage()
    memory_usage = get_memory_usage()

    if disk_usage >= DISK_THRESHOLD or memory_usage >= MEMORY_THRESHOLD:
        subject = "服务器资源告警"
        content = f"磁盘使用率:{disk_usage}%,内存使用率:{memory_usage}%"
        send_email(subject, content)

if __name__ == '__main__':
    main()

请将your_email@example.com替换为您的发件人邮箱地址,将receiver_email@example.com替换为收件人邮箱地址。此外,您需要配置本地SMTP服务器以使邮件发送功能正常工作。如果您使用的是Gmail,可以参考这个教程来配置SMTP服务器。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 23:26:07       4 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 23:26:07       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 23:26:07       4 阅读
  4. Python语言-面向对象

    2024-07-10 23:26:07       4 阅读

热门阅读

  1. 2024百度之星第三场第一题 数星星

    2024-07-10 23:26:07       10 阅读
  2. 【安卓学习】复选框CheckBox

    2024-07-10 23:26:07       9 阅读
  3. 人机交互中信息之间的距离

    2024-07-10 23:26:07       10 阅读
  4. xml_woarchive undefined symbol

    2024-07-10 23:26:07       10 阅读
  5. 基于深度学习的安全帽检测

    2024-07-10 23:26:07       10 阅读
  6. swift获取app网络和本地网络权限

    2024-07-10 23:26:07       10 阅读
  7. C语言获取当前时间

    2024-07-10 23:26:07       12 阅读
  8. Unity3D项目中如何正确使用Lua详解

    2024-07-10 23:26:07       9 阅读
  9. WPF更新UI线程实现进度条功能

    2024-07-10 23:26:07       12 阅读
  10. mysql 导出导入 数据库

    2024-07-10 23:26:07       9 阅读