Python monitoring && send mail folder

Directly on the code:

# 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 = ['[email protected]', ' [email protected] ' ] 

    MSG = MimeText ( ' the statistical server / dev / shm memory alarm ' , ' Plain ' , ' UTF-. 8 ' ) 
    MSG [ ' the From ' ] = from_addr 
    MSG [ ' the To ' ] = ' , ' .join (to_addrs) 
    MSG [ ' the Subject ' ] = Header ( ' online server alarm ' , ' UTF-. 8 ' ) .encode () 

    the 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')

 

References:

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

Reproduced in: https: //www.cnblogs.com/gattaca/p/6690781.html

Guess you like

Origin blog.csdn.net/weixin_33919950/article/details/93767168