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):
mail_host = "smtp.126.com"
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)
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)