smtplib报警模块

#!/usr/bin/env python
# coding:utf-8
import time
import subprocess
import smtplib
from email.mime.text import MIMEText

# ------------获取内存过载信息------------
cmd = "cd /data/scripts;rm -f mem.info;ps aux | sort -k6rn | head -20| awk '{print $2,$6/1024,$11}' > ./mem.info"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
time.sleep(3)
meminfo = []
i = 0
with open('mem.info') as obj:
    for line in obj.readlines():
        line = line.split()
        line[0] = int(line[0])
        line[1] = float(line[1])
        if line[1] > 1000:
            memmsg = "pid:%d mem:%dMB" % (line[0], line[1])
            meminfo.insert(i, memmsg)
            i = i + 1

getip = subprocess.Popen('curl ifconfig.me',stdout=subprocess.PIPE,shell=True)
ip = getip.stdout.read().strip()
meminfo.insert(0, ip)
meminfo_str = "\n".join(meminfo)

# -------------发送告警邮件---------------
len = len(meminfo)
if len > 1:
    from_addr = 'xx@163.com'
    passwd = '网易授权码'
    to_addr = 'xx@xx.com'
    smtphost = 'smtp.163.com'

    message = MIMEText(meminfo_str, 'plain', 'utf-8')
    message['subject'] = 'memery warning'
    message['from'] = from_addr
    message['to'] = to_addr
    server = smtplib.SMTP_SSL(smtphost, 465)
    server.login(from_addr, passwd)
    server.sendmail(from_addr, to_addr, message.as_string())
    server.quit()

 

使用subprocess.Popen调用shell cmd,把结果输出到文件

把文件的每行数据读出来,然后用split方法转化为列表,根据内存值这个元素进行判断。

把ip和符合条件的行合成一个列表。然后用"\n".join(),以换行符为分隔符转为字符串,目的是发送邮件。

判断列表的长度,大于1表示有ip以外的元素,启用邮件发送操作。

调用smtplib模块,登录网易的SMTP_SSL接口,发送邮件。

posted @ 2018-05-09 15:07  jabbok  阅读(184)  评论(0编辑  收藏  举报