python 检查磁盘占用并发邮件告警

# coding=utf-8

import smtplib
from email.header import Header
from email.mime.text import MIMEText
import time
import psutil
import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(level=logging.DEBUG, filename='monitor.log', filemode='a',
                    format='%(lineno)d-%(asctime)s-%(name)s-%(message)s')

def send(title, content):
    # 第三方 SMTP 服务
    mail_host = "smtp.126.com"  # SMTP服务器
    mail_user = "[email protected]"  # 用户名
    mail_pass = "xxx"  # 密码(这里的密码不是登录邮箱密码,而是授权码)

    sender = '[email protected]'  # 发件人邮箱
    receivers = ['[email protected]']  # 接收人邮箱

    message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        logging.info("mail has been send successfully.")
    except smtplib.SMTPException as e:
        logging.error(e)


def check_disk_usage():
    du = psutil.disk_usage("/")
    free = du.free / (1024 * 1024 * 1024)
    total = du.total / (1024 * 1024 * 1024)
    usage = du.percent
    logging.info("磁盘使用情况:{:.2f}/{:.2f} GB ({:.2f}%)".format(free, total, usage))
    return usage


while (True):
    usage = check_disk_usage()
    if (usage > 50):
        send("Danger!! Server Disk Full", "Disk Usage: {:.2f}".format(usage))
    time.sleep(30)


你可能感兴趣的:(python,开发语言)