使用python-SMTP功能实现用短信接受服务器告警

简介

昨天写了一个监控服务器温度的脚本,觉得不够完善,所以改良了一下

优点

使用python-SMTP功能实现用短信接受服务器的告警信息

代码

import subprocess
import re
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

# 发件人邮箱账号
my_sender='[email protected]'
my_pass = 'xxxxxx520'
# 收件人邮箱账号
my_user='[email protected]'

def monitoring():
        cheild = subprocess.check_output('ipmitool -H 192.168.30.101 -U root -P sjj123@ sdr type "0x01"',shell=True,universal_newlines=True)
        a = re.findall(r'\d+ degrees C',cheild)
        b = re.findall(r'\d+',str(a))
        qw = b[0]
        if int(qw) > 40:
            dangerous(qw)
            subprocess.check_output('ipmitool -H 192.168.30.101 -U root -P sjj123@ raw 0x30 0x30 0x02 0xff 0x40',shell=True,universal_newlines=True)


def dangerous(temperature):
    try:
        # 邮件内容
        msg=MIMEText('cpu温度过高:'+temperature,'plain','utf-8')
        # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['From']=formataddr(["你爸爸",my_sender])
        # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['To']=formataddr(["nicai",my_user])
        # 邮件的主题
        msg['Subject']="服务器温度监控系统"

        # SMTP服务器,腾讯企业邮箱端口是465,腾讯邮箱支持SSL(不强制), 不支持TLS
        server=smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
        # 登录服务器,括号中对应的是发件人邮箱账号、邮箱密码
        server.login(my_sender, my_pass)
        # 发送邮件,括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.sendmail(my_sender,[my_user,],msg.as_string())
        # 关闭连接
        server.quit()
        # 如果 try 中的语句没有执行,则会执行下面的 ret=False
    except Exception:
        return 'cuowu'

monitoring()

猜你喜欢

转载自blog.csdn.net/weixin_33995481/article/details/87575554
今日推荐