标签:服务器 ip地址 message python import
使用该程序分析/var/log/message中有error或者其他错误关键字。并在发现后搜集,发送邮件运维管理人员。
可以再定义一下辅助的函数,比如说获取服务器的ip地址。放在邮件内容中。一起发邮件。
#!/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,
‘Jun‘:6,
‘Jul‘:7,
‘Aug‘: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
#查看/var/log/message 是否在10分钟之内修改过,如果修改过返回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分钟的日志,并分析是否存在关键字nologmsg,如果有,便存入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)
# 发邮件
receiver = ‘xxx@xxx.xxx‘
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))
本文出自 “linux服务器” 博客,转载请与作者联系!
标签:服务器 ip地址 message python import
原文地址:http://sailq21.blog.51cto.com/6111337/1893324