Use this program to analyze errors or other error keywords in/var/log/message. And after the discovery of the collection, send mail operations management personnel.
You can define additional functions, such as obtaining the IP address of the server. Placed in the message content. Send an email together.
#!/usr/bin/env/python
#coding: UTF8
Import commands
Import Os,sys
Import datetime
Import time
#import file_seekwork
Import Urllib,urllib2
Import JSON
Today=datetime.date.today ()
month={
' Jan ': 1,
' Feb ': 2,
' Mar ': 3,
' APR ': 4,
' May ': 5,
' June ': 6,
' Jul ': 7,
' The ': 8,
' Sep ': 9,
' Oct ': 10,
' Nov ': 11,
' Dec ': 12
}
Def parse_file ():
Pass
#获取文件修改时间
def get_state (file):
File_mtime=os.stat (file). st_mtime
Return File_mtime
#查看 whether the/var/log/message has been modified in 10 minutes if it has been modified to return file.
def getenfile (file,nowtime):
If os.path.exists (file) and (Nowtime-get_stat (file))/60 < 10:
Return file
#
def parse_date (DATESTR):
Year=today.year
Month,day,yearandtime=datestr.split ("/")
Hour,minute,second = Yearandtime.split (":")
return datetime.datetime (int (year), Month[month],int (day), int (hour), int (minute))
#获取10分钟的日志, and analyze if there is a keyword nologmsg, and if so, then deposit in logmsg.
def get_msg_result (time_minutes_ago,file,nologmsg):
with open (file) as FD:
y = Fd.readlines ()
Logmsg=[]
Logerrmsg=[]
For line in Y:
Splited_line=line.split ()
Datestr = '/'. Join (Splited_line[:3])
#print ("Datestr qqqqqq:%s"%datestr)
Try
Date_str=parse_date (DATESTR)
#print ("Date_str:%s"%date_str)
Except
Continue
#date = Date_str.strftime ("%s")
#print Date_str,time_minutes_ago
If Date_str >= Time_minutes_ago:
Logmsg.append (line)
Else
Continue
For Ten_minutes_line in logmsg:
For I in Nologmsg:
If I not in line:
Continue
Else
Logerrmsg.append (Ten_minutes_line)
If logerrmsg:
Continue
#for Errline in Logerrmsg:
# Print Errline
Return logerrmsg
if __name__ = = ' __main__ ':
now = Datetime.datetime.now ()
#print now
D = Datetime.timedelta (minutes=10)
#print D
Time_minutes_ago=now-d
#print Time_minutes_ago
Keyword = [' ERROR ']
Log_file= '/root/qh/qh_test.txt '
retrust= Get_msg_result (Time_minutes_ago,log_file,keyword)
Print (112,retrust)
# Send mail
receiver = ' [email protected] '
Subject = '/var/log/messages error '
A= '. Join (Retrust)
Print a
#print type (a)
#a = "ADFASDFASDFASDF"
#os. System ('/usr/bin/perl/root/qh/send_msg.pl-t ' + receiver + '-s ' + subject + '-C ' + ' TEST_QH ')
Commands.getoutput ('/usr/bin/perl/root/qh/send_msg.pl-t%s-s '%s '-C '%s '% (receiver,subject,a))
This article from the "Linux Server" blog, reproduced please contact the author!
Parsing/var/log/message's Python script