释放双眼,带上耳机,听听看~!
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 1#!/usr/bin/env python
2#-*-coding:utf-8-*-
3#CreateDate:2017/04/14
4#Author:Eivll0m
5#ScriptName:monitor-log.py
6#Crontab:*/5 * * * * /app/sbin/monitor-log.py &>/dev/null
7
8
9import os
10import time
11import stat
12import socket
13import smtplib
14from email.mime.text import MIMEText
15#from email.mime.multipart import MIMEMultipart
16from email.header import Header
17from email.utils import parseaddr, formataddr
18
19def formatAddr(s):
20 name, addr = parseaddr(s)
21 return formataddr((Header(name, 'utf-8').encode(), addr))
22def sendMail(body,subject):
23 smtp_server = 'smtp.exmail.qq.com'
24 from_mail = 'xxx@xxxx.com'
25 mail_pass = 'password'
26 to_mail = ['aaa@xxx.com','bbb@xxx.com','ccc@xxx.com']
27 cc_mail = ['ddd@xxx.com','eee@xxx.com','fff@xxx.com','ggg@xxx.com','hhh@xxx.com']
28 msg = MIMEText(body,'html','utf-8')
29 msg['From'] = formatAddr('日志监控 <%s>' % from_mail).encode()
30 msg['To'] = ','.join(to_mail)
31 msg['Cc'] = ','.join(cc_mail)
32 msg['Subject'] = Header(subject, 'utf-8').encode()
33 try:
34 s = smtplib.SMTP()
35 s.connect(smtp_server, "25")
36 s.login(from_mail, mail_pass)
37 s.sendmail(from_mail, to_mail+cc_mail, msg.as_string())
38 s.quit()
39 except smtplib.SMTPException as e:
40 print "Error: %s" % e
41
42
43def GetText(file):
44 cmd = "awk -vf='%s' 'BEGIN{while(getline < f){j++;if(/ERROR/)i=j}}NR>=i' %s" %(file,file)
45 text = os.popen(cmd).readlines()
46 return ''.join(text)
47
48
49def CheckFileStat(file):
50 FileStats = os.stat(file)
51 ModifyTime = time.mktime(time.strptime(time.ctime(FileStats[stat.ST_MTIME]),"%a %b %d %H:%M:%S %Y")) + 300
52 LocalTime = time.time()
53 if LocalTime < ModifyTime:
54 return True
55 else:
56 return False
57
58if __name__ == "__main__":
59 logs = ['/app/log/channelmanage/channelerror.log','/app/log/assetmanage/error.log']
60 LocalIP = socket.gethostbyname(socket.gethostname())
61 for log in logs:
62 if CheckFileStat(log):
63 sj = log.split('/')[3] + '日志报错' + '【主机IP:' + LocalIP + '】'
64 body = GetText(log)
65 sendMail(body,sj)
66
监控邮件: