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

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

bash 复制代码
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 = '[email protected]'
    receivers = ['[email protected]']
    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()

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

相关推荐
煤灰2421 分钟前
Linux上的网络编程-初探
linux·网络
马志远的生信笔记19 分钟前
质控脚本来喽
linux·数据分析
✿ ༺ ོIT技术༻25 分钟前
Linux:深入理解网络层
运维·服务器·网络
刃神太酷啦1 小时前
类和对象(1)--《Hello C++ Wrold!》(3)--(C/C++)
java·c语言·c++·git·算法·leetcode·github
在下千玦1 小时前
#在 CentOS 7 中手动编译安装软件操作及原理
linux
Penguido1 小时前
基于 Nexus 在 Dockerfile 配置 yum, conda, pip 仓库的方法和参考
linux·docker·centos·conda·pip
浩~~1 小时前
HTML5 中实现盒子水平垂直居中的方法
java·服务器·前端
互联网搬砖老肖2 小时前
Web 架构之故障自愈方案
前端·架构·github
天上掉下来个程小白2 小时前
添加购物车-02.代码开发
java·服务器·前端·后端·spring·微信小程序·苍穹外卖
网络空间小黑2 小时前
WEB渗透测试----信息收集
服务器·前端·网络·安全·web安全·网络安全