python编写linux内存监控发送邮件

# _*_ coding: utf-8 _*_
# auther = 林深见鹿,海蓝见鲸


import subprocess
import datetime


def time_stamp():
    now_time = datetime.datetime.now()
    print(now_time)


def main():
    cmd = ['df', '-h']

    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    p.wait()
    res = p.stdout.read()
    result = res.decode("utf-8")
    a = result.split()
    print(a)
    list = ['95%', '96%', '97%', '98%', '99%', '100%']
    for i in a:
        if i in list:
            try:
                send_mail()
                time_stamp()
            except:
                print("邮件发送失败".center(50, "-"))
                time_stamp()
        else:
            pass


def send_mail():
    print("---------------开始发送邮件---------------")
    print("开始发送邮件".center(50, "-"))
    import smtplib
    from email.mime.text import MIMEText  # 正文
    from email.header import Header  # 邮件头

    email_username = ' '
    email_password = ' '
    eamil_address = ' '
    email_port = 465

    '''
    登录邮箱服务器
    '''
    smtp_obj = smtplib.SMTP_SSL(eamil_address, email_port)
    smtp_obj.login(email_username, email_password)

    mail_body = '磁盘空间不足,当前磁盘使用率少于5%'
    msg = MIMEText(mail_body, "plain", "utf-8")
    msg["Form"] = Header("发件人", "utf-8")  # 发送者
    msg["To"] = Header("收件人", "utf-8")  # 接受者
    msg["Subject"] = Header("磁盘空间不足", "utf-8")  # 主题

    '''
    发送
    '''
    smtp_obj.sendmail("xxx@cmbc.com.cn", ["xxx@cmbc.com.cn"], msg.as_string())


if __name__ == '__main__':
    main()

 

posted @ 2022-03-11 20:16  林深见鹿,海蓝见鲸  阅读(61)  评论(0编辑  收藏  举报