Python监控文件夹 && 发送邮件

直接上代码:

# python3
# -*- coding: utf-8 -*-
# 2017/06/16 by luohan

from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib
import time

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size / (1024 * 1024 * 1024)

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

def send_mail():
    from_addr = '**@**.com'
    passwd = '***'
    to_addrs = ['123@qq.com', '234@qq.com']

    msg = MIMEText('统计服务器/dev/shm内存报警', 'plain', 'utf-8')
    msg['From'] = from_addr
    msg['To'] = ','.join(to_addrs)
    msg['Subject'] = Header('线上服务器报警', 'utf-8').encode()

    try:
        smtp_server = 'smtp.exmail.qq.com'
        server = smtplib.SMTP_SSL(smtp_server, 465)
        server.login(from_addr, passwd)
        server.sendmail(from_addr, to_addrs, msg.as_string())
        with open('/home/jobs/mail.log', 'a') as f:
            print('{}: send success'.format(time.time()), file=f)
    except smtplib.SMTPException as e:
        with open('/home/jobs/mailerr.log', 'a') as f:
            print('{}: send failed, {}'.format(time.time(), e), file=f)
    finally:
        server.quit()

def check_dir_size(target_dir):
    dirsize = get_size(target_dir)
    # 超过12G,总大小16G
    if dirsize > 12:
        send_mail()

check_dir_size('/dev/shm')

 

参考资料:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432005226355aadb8d4b2f3f42f6b1d6f2c5bd8d5263000

posted @ 2017-04-10 20:33  Sawyer Ford  阅读(469)  评论(0编辑  收藏  举报