相关知识点:
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 importos3 importre4 importsmtplib5 importdatetime6 importlogging7 from email.mime.text importMIMEText8
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 defsend_mail(to_list,sub,content):20 me =mail_user21 msg = MIMEText(content, 'html', 'utf-8')22 msg['Subject'] =sub23 msg['From'] =me24 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 returnTrue32 exceptException, e:33 #print str(e)
34 returnFalse35
36 defget_hostname():37 get_hostname_info = os.popen('hostname').readline().strip()38 returnget_hostname_info39
40 defcheck_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 printErrorInfo47 returnErrorInfo48 re_obj = re.compile(r'[^\s]+\s+(?P\d+)%\s+(?P.+)')49 hp_use ={}50 for line infp:51 match =re_obj.search(line)52 if match is notNone:53 hp_use[match.groupdict()['mount']] = match.groupdict()['used']54 fp.close()55 returnhp_use56
57 defdict_trans_str(a):58 x=zip(a.values(),a.keys())59 y=sorted(x,reverse=True)60 stra=""
61 for i iny:62 stra += str(i[0])+":"+i[1]+"
"
63 returnstra64
65 defhd_use_alarm():66 globalH67 globalalert_hp_use68 alert_count_p=069 H=get_hostname()70 alert_hp_use ={}71 for k,v incheck_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 79
8081 System Partition Monitor Warning
82 Hostname:  %s
83 Overload partition number:  %s
84 Partition Use:
85 %s86
93 deflogger_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 returnlogger105 if __name__ == '__main__':106 hd_use_alarm()107 logger = logger_config(log_path=logfile, logging_name=str(alert_hp_use))108 logger.info(H)
效果截图: