您的位置:首页 > 编程语言 > Python开发

python实现监控磁盘情况,并邮件报警

2017-01-25 09:50 851 查看
#coding:utf-8
import os
import re
import smtplib
import datetime
import shelve
from email.mime.text import MIMEText

# 硬盘使用率报警阀值
hd_usage_rate_threshold = 80

# 要发给谁
mailto_list=["******@17guagua.com","******@17guagua.com"]

# 设置服务器,用户名、口令以及邮箱的后缀
mail_host="smtp.17guagua.com"
mail_user="******@17guagua.com"
mail_pass="******"
mail_postfix="17guagua.com"

# 日志偏移
log_offset = shelve.open('log_offset')

# 取当天日期
log_path_suffix=(datetime.date.today()).strftime('%Y-%m-%d')

# 当前日期key
cur_time = 'cur_time'

# 日志路径
app_info = {}
app_info['event'] = ['/opt/log/guagua_web_event_extends/event-ext-'+log_path_suffix+'.log',['失败','异常'],[]]

# 处理日志
def analysis_log(appName ,appInfo):
cur_time_val = get_shelve_value(cur_time)
if cur_time_val == -1:
set_shelve_value(cur_time, log_path_suffix)
elif log_path_suffix != cur_time_val:
set_shelve_value(appName, 0)
set_shelve_value(cur_time, log_path_suffix)

f1 = file(appInfo[0], "r")
offset = get_shelve_value(appName)
if offset != -1:
f1.seek(offset,1)
else:
set_shelve_value(appName, 0)
count = 0
exceptionStr = ""
for s in f1.readlines():
searchKey = appInfo[1]
if len(searchKey) > 0:
for i in searchKey:
li = re.findall(i, s)
if len(li) > 0:
count = count + li.count(i)
exceptionStr = exceptionStr + " " + s
else:
li = re.findall('Exception', s)
if len(li) > 0:
count = count + li.count('Exception')
exceptionStr = exceptionStr + " " + s
set_shelve_value(appName, f1.tell())
print appName + " 异常数量为 " + str(count)
return [count, "---------------------------------" + appName + " ----------------------------- \n " + exceptionStr]

#shelve 处理
def set_shelve_value(key, value):
log_offset[key] = value

def get_shelve_value(key):
if log_offset.has_key(key):
return log_offset[key]
else:
return -1

def del_shelve_value(key):
if log_offset.has_key(key):
del log_offset[key]

# 发送邮件
def send_mail(to_list,sub,content):
me = mail_user + "<"+ mail_user + "@" + mail_postfix + ">"
msg = MIMEText(content, 'html', 'utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
return False

# 获得外网ip
def get_wan_ip():
cmd_get_ip = "/sbin/ifconfig |grep 'inet addr'|awk -F\: '{print $2}'|awk '{print $1}' | grep -v '^127' | grep -v '192'"
get_ip_info = os.popen(cmd_get_ip).readline().strip()
return get_ip_info

# 检测硬盘使用
def check_hd_use():
cmd_get_hd_use = '/bin/df'
try:
fp = os.popen(cmd_get_hd_use)
except:
ErrorInfo = r'get_hd_use_error'
print ErrorInfo
return ErrorInfo
re_obj = re.compile(r'^/dev/.+\s+(?P<used>\d+)%\s+(?P<mount>.+)')
hd_use = {}
for line in fp:
match = re_obj.search(line)
if match is not None:
hd_use[match.groupdict()['mount']] = match.groupdict()['used']
fp.close()
return  hd_use

# 硬盘使用报警
def hd_use_alarm():
for v in check_hd_use().values():
if int(v) > hd_usage_rate_threshold:
if send_mail(mailto_list,
'System Disk Monitor',
'nSystem Ip:%s\nSystem Disk Use:%s'
% (get_wan_ip(),check_hd_use())):
print  "sendmail success!!!!!"
else:
print "disk not mail"

if __name__ == '__main__':
hd_use_alarm()
exceptionCount = 0
exceptionContents = "";
for key in app_info:
exceptionContent = analysis_log(key, app_info[key])
exceptionCount += exceptionContent[0]
exceptionContents += exceptionContent[1]
exceptionContents = exceptionContents + "*********************************************** \n"

print exceptionCount
if exceptionCount > 0:
if send_mail(mailto_list, get_wan_ip() + " 日志报警",exceptionContents):
print "发送成功"
else:
print "发送失败"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: