直接上代码:
# 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')
参考资料: