python监控磁盘分区使用情况并发送告警邮件

相关知识点:

1.邮件发送功能模块 smtplib,MIMEText

2.日志功能模块 logging

 

解释引用:

1. logger 与 handlers 区分

  logger是第一级过滤,然后才能到handler,我们可以给logger和handler同时设置level,但是需要注意的是

Logger is also the first to filter the message based on a level — if you set the logger to INFO,
and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected
by the logger itself.
If you set logger to DEBUG, but all handlers to INFO,
you won't receive any DEBUG messages either — because while the logger says "ok, process this",
the handlers reject it (DEBUG < INFO).

 

函数备注:

1> check_hp_use() 返回名为hp_use的字典,存放分区挂载点与使用百分比的 key-value.

2> dict_trans_str(a) 先将字典转换成元组,然后根据value倒序生成value-key 的字符串并带html换行符。

3> hd_use_alarm() 删选字典中value 值满足告警大小的key-value.

4> logger_config() 定义两个handler可以分别将日志存入文件或前端打印,可以同时存在.

5> 定义两个全局变量H和alert_hp_use,以便主函数调用。

 

Code:

  1 #coding:utf-8
  2 import os
  3 import re
  4 import smtplib
  5 import datetime
  6 import logging
  7 from email.mime.text import MIMEText
  8 
  9 hd_usage_rate_threshold = 80
 10 
 11 mailto_list=["mailto@***.com"]
 12 
 13 mail_host="smtp.qq.com"
 14 mail_user="qq-number@qq.com"
 15 mail_pass="password"
 16 
 17 logfile = '/tmp/diskcheck.log'
 18 
 19 def send_mail(to_list,sub,content):
 20 me = mail_user
 21 msg = MIMEText(content, 'html', 'utf-8')
 22 msg['Subject'] = sub
 23 msg['From'] = me
 24 msg['To'] = ";".join(to_list)
 25 try:
 26 s = smtplib.SMTP()
 27 s.connect(mail_host)
 28 s.login(mail_user,mail_pass)
 29 s.sendmail(me, to_list, msg.as_string())
 30 s.close()
 31 return True
 32 except Exception, e:
 33 # print str(e)
 34 return False
 35 
 36 def get_hostname():
 37 get_hostname_info = os.popen('hostname').readline().strip()
 38 return get_hostname_info
 39 
 40 def check_hp_use():
 41 cmd_get_hp_use = '/bin/df'
 42 try:
 43 fp = os.popen(cmd_get_hp_use)
 44 except:
 45 ErrorInfo = r'get_hp_use_error'
 46 print ErrorInfo
 47 return ErrorInfo
 48 re_obj = re.compile(r'[^\s]+\s+(?P<used>\d+)%\s+(?P<mount>.+)')
 49 hp_use = {}
 50 for line in fp:
 51 match = re_obj.search(line)
 52 if match is not None:
 53 hp_use[match.groupdict()['mount']] = match.groupdict()['used']
 54 fp.close()
 55 return hp_use
 56 
 57 def dict_trans_str(a):
 58 x=zip(a.values(),a.keys())
 59 y=sorted(x,reverse=True)
 60 stra=""
 61 for i in y:
 62 stra += str(i[0])+":"+i[1]+"<br>"
 63 return stra
 64 
 65 def hd_use_alarm():
 66 global H
 67 global alert_hp_use
 68 alert_count_p=0
 69 H=get_hostname()
 70 alert_hp_use = {}
 71 for k,v in check_hp_use().items():
 72 if int(v) > hd_usage_rate_threshold:
 73 alert_count_p+=1
 74 alert_hp_use[k] = int(v)
 75 str_alert_hp_use = dict_trans_str(alert_hp_use)
 76 if alert_count_p > 0:
 77 Content = """\
 78 <html>
 79 <body>
 80 <p>
 81 System Partition Monitor Warning<br>
 82 Hostname: &nbsp%s<br>
 83 Overload partition number: &nbsp%s<br>
 84 Partition Use: <br>
 85 %s
 86 </p>
 87 </body>
 88 </html>
 89 """% (H,alert_count_p,str_alert_hp_use)
 90 Sub="System Disk Monitor On "+H
 91 send_mail(mailto_list,Sub,Content)
 92 
 93 def logger_config(log_path,logging_name):
 94 logger = logging.getLogger(logging_name)
 95 logger.setLevel(level=logging.DEBUG)
 96 handler1 = logging.FileHandler(log_path)
 97 handler1.setLevel(logging.INFO)
 98 #handler2 = logging.StreamHandler() 
 99 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
100 handler1.setFormatter(formatter)
101 #handler2.setFormatter(formatter)
102 logger.addHandler(handler1)
103 #logger.addHandler(handler2)
104 return logger
105 if __name__ == '__main__':
106 hd_use_alarm()
107 logger = logger_config(log_path=logfile, logging_name=str(alert_hp_use))
108 logger.info(H)

 效果截图:

posted @ 2021-01-04 14:13  随风拂面  阅读(110)  评论(0)    收藏  举报