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

转载于:https://www.cnblogs.com/gattaca/p/6690781.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值