#!/usr/bin/env python # coding:utf-8 import re import os import sys import logging logging.basicConfig(level=logging.DEBUG, # 定义输出到文件的log级别,大于此级别的都被输出 format='%(asctime)s %(filename)s : %(levelname)s %(message)s', # 定义输出log的格式 datefmt='%Y-%m-%d %H:%M:%S', # 时间 filename='/etc/zabbix/scripts/check_log/check.log', # log文件名 filemode='a+') logfile=sys.argv[1] keyword=sys.argv[2] statfile='/tmp/logfilestat.txt' logging.info("======================================================Start======================================================") logging.info('log_file: {0}, keyword: {1} '.format(logfile, keyword)) try: f = open(statfile, 'r') # 获取文件读取的offset offset = f.readlines() f.close() except Exception,e: logging.info('{0} file not exits,create stat file!'.format(statfile)) # 若是是第一次使用,文件读取状态不存在,这重置读取标志为空 offset = [] alter = [] with open(statfile, 'w+') as offwr: with open(logfile, 'r') as f: # 若是读取状态文件,为空,则重置为从头读取 if len(offset) == 0: f.seek(0, 2) elif len(offset) == 2: # 判断文件是否为新文件 # 文件没有改变,则从上次读取的位置继续读取 if int(offset[1]) == int(os.stat(logfile)[1]): logging.info("start_offset: {0}".format(offset[0].strip())) f.seek(int(offset[0].strip())) else: # 若是文件改变了,则从头开始去读 logging.info("start_offset: 0") f.seek(0) for i in f.readlines(): # 将查询结果用0和1存入list中 if re.search(str(keyword), i.strip()): logging.error("Find {0} the key!!".format(keyword)) alter.append(0) else: alter.append(1) # 将文件读取位置和inode值写入状态文件 offwr.write(str(f.tell())) offwr.write("\n") offwr.write(str(os.stat(logfile)[1])) f.close() offwr.close() logging.info("======================================================End======================================================") # set是去重,若是list中包含1和2,则长度为2,应当报警 if len(set(alter)) == 1: print 100 else: print 200