1. 程式人生 > >python寫的日誌監控程式,關鍵字統計,日誌大小監控,關鍵字出現報警並擷取日誌

python寫的日誌監控程式,關鍵字統計,日誌大小監控,關鍵字出現報警並擷取日誌

#!/bin/python
#coding:UTF-8
'''
    @author:   verlink
    @desc:     log monitor 
    @date:     2015-6-16
'''
import sys
import re
import time
import os
import random
import datetime
import pycurl
import StringIO
import urllib
import ConfigParser

class logMonitor():

    def __init__(self):

        self.conf = ConfigParser.ConfigParser()
        self.conf.read("./log_monitor.ini")
	self.email_list = []
	self.log_name = ''


    def task_portal(self):
        
        section_list = self.conf.sections()
	monitor_list = []
	email_list = []
        result = 0

        for item in section_list:
	    if item == 'basic':
		    if self.conf.get(item,'enable') == 'false':
			    return
		    else:
		            self.log_name = self.conf.get(item,'log_name')
			    self.log_name_everyday()
			    print self.log_name
		            self.email_list = self.conf.get(item,'emails').split(';')
	    else:
		    if self.conf.get(item,'enable') != 'false':
			    monitor_list.append(item)
        for monitor_item in monitor_list:
                self.worker(monitor_item)

    def worker(self,monitor_item):
        
        if monitor_item == 'error_words_monitor':
	    print 'error_words_monitor start'
            if self.conf.get(monitor_item,'monitor_words') == '':
                return
            monitor_words_list = self.conf.get(monitor_item,'monitor_words').split(';')
	    threshold = self.conf.get(monitor_item,'threshold')
	    self.error_words_monitor(monitor_words_list,threshold)
	elif monitor_item == 'log_file_monitor':
	    print 'log_file_monitor start'
	    file_max_threshold = self.conf.get(monitor_item,'file_max_threshold')
	    self.log_file_monitor(file_max_threshold)
	elif monitor_item == 'target_words_monitor':
	    print 'target_words_monitor start'
	    monitor_words_list = self.conf.get(monitor_item,'target_words').split(';')
	    self.target_words_monitor(monitor_words_list)

        else:
            return 

    def log_name_everyday(self):

    	today = datetime.datetime.today()
	try:
		log_prefix = self.log_name.split('-')[0]
		date = today.strftime("%Y-%m-%d")
		self.log_name = log_prefix + '-' + date
	except Exception,e:
		print str(e)
		return

    def target_words_monitor(self,monitor_words_list):

	file_list = self.get_file_list()
	for file_name in file_list:
		f = open(file_name,'r')
		file_content = f.read()
		for word in monitor_words_list:
			if file_content.find(word) != -1:
				print 'find it!'
				log_content = file_content[file_content.find(word):file_content.find(word) + 1000]
				email_subject = self.conf.get('target_words_monitor','email_subject')
				email_content = self.conf.get('target_words_monitor','email_content') + '         ' +log_content
				print email_content
				self.alert_emails(email_subject,email_content)

    def get_file_list(self):

    	cmd = 'ls ' + self.log_name + '*'
	file_str = os.popen(cmd).read()
	file_list = file_str.split('\n')
	return file_list[0:len(file_list) - 1]

    def error_words_monitor(self, monitor_words_list, threshold):

    	email_subject = self.conf.get('error_words_monitor','email_subject')
	email_content = self.conf.get('error_words_monitor','email_content')
	file_list = self.get_file_list()
    	for word in monitor_words_list:
		pattern = re.compile(word)
		for file_name in file_list:
			f = open(file_name,'r')
			file_content = f.read()
			result_list = pattern.findall(file_content)
			if len(result_list) >= int(threshold):
				self.alert_emails(email_subject,email_content);

    def log_file_monitor(self,file_max_threshold):

    	email_subject = self.conf.get('log_file_monitor','email_subject')
	email_content = self.conf.get('log_file_monitor','email_content')
    	file_list = self.get_file_list()
	for file_name in file_list:
		cmd = "ls -l " + file_name + " | awk '{print $5}'"
		file_size = os.popen(cmd).read()
		if int(file_size.strip()) >= int(file_max_threshold):
			self.alert_emails(email_subject,email_content)

    def send_curl_command(self,url):

        c = pycurl.Curl()
        c.setopt(c.URL, url)
        b = StringIO.StringIO()
        c.setopt(pycurl.WRITEFUNCTION,b.write)
        c.perform()
        c.close

    def alert_emails(self,email_subject,email_content):

        monitor_str = ''
    	for monitor in self.email_list:
		monitor_str = monitor_str + ',' + monitor
	monitor_str = monitor_str[1:]
	email_content = urllib.quote(email_content)
	email_subject = urllib.quote(email_subject)
    	cmd_email = 'http://sdf1.letv.cn/ews/mailer/send/?receivers='+monitor_str+'&subject='+email_subject+'&content=' + email_content 
	self.send_curl_command(cmd_email)
	 

if __name__ == '__main__':

    lm = logMonitor()
    lm.task_portal()

配置檔案資訊如下:

[basic]
log_name = wallpaper-2015-6-16.log
emails = [email protected]

enable = true 



[error_words_monitor]

monitor_words = error
threshold= 1
email_subject = 桌布的日誌錯誤詞數量監控
email_content = 桌布的error日誌數量過多,已經超過報警閾值,請登陸伺服器進行處理

enable = false

[target_words_monitor]

target_words = StringToJsonValue 
email_subject = 目標詞監控報警
email_content  = 桌布的fatal日誌出現 部分日誌內容已經擷取,如下所示,請進行處理

enable = true

[log_file_monitor]

file_max_threshold = 10
email_subject = 日誌檔案大小監控
email_content = 桌布的日誌檔案過大,已經超過報警閾值,請進行處理

enable = false

主要用到了python的configparser和urllib等模組,裡面的核心部分主要是實現的細節,比如對與中文的url輸入,等等。

相關推薦

python日誌監控程式關鍵字統計日誌大小監控關鍵字出現報警擷取日誌

#!/bin/python #coding:UTF-8 ''' @author: verlink @desc: log monitor @date: 2015-6-16 ''' import sys import re impo

python實現 輸入一行字元分別統計出其中英文字母空格數字和其他字元的個數

                s=input('input a string:\n')letters=0space=0digit

python實現:輸入一行字元分別統計出其中英文字母空格數字和其他字元的個數

s=input('input a string:\n') letters=0 space=0 digit=0 others=0 for c in s: if c.isalpha():

輸入一行字元分別統計出其中英文字母空格數字和其他字元的個數

#include #include <string.h> using namespace std; int main() { char str[50]; int l=0,b=0,n=0,o=0; //l=letter,b=blank,n=numb

輸入一行字元分別統計出其中英文字母空格數字和其他字元的個數【while迴圈】

/* cj1.c */ #include <stdio.h> main() {int i=0, space=0, num=0, n=0, ch=0;     char s[1000000];     printf("請輸入一串字元 ");     gets(s)

Word圖片大小總是對不齊如何統一圖片的大小位置看一眼就會!

還在為圖片大小位置不統一而發愁嗎,這樣做出來的word文件不美觀圖片看起來也是大小不一很不協調。今天就教大家幾個簡單的處理圖片的辦法,快來學習吧! 修改圖片預設環繞方式 大家在word中插入圖片的時候有沒有遇到這樣的麻煩,插入的圖片無法移動,必須要手動設定一下環繞方式才可以移動圖片,這樣做太費事

python 的一個oracle 服務響應時間的實時監控web 小工具

主要工具: python,flask,SQLLITE (我沒有選擇mysql,sqllite 夠用了,本來就是一個小功能,我喜歡簡單) 主要功能: 監控oracle 10g,11g 資料庫平均響應時間,通過實施採集資料庫rt 並生成趨勢圖,方便客戶通過大屏簡單明瞭,

最近開始努力學python 了一個python小代碼:判斷一個登陸程序如果賬號密碼輸錯3次鎖定賬號無法再登陸

登陸 readlines 輸入 連續 nbsp 努力 一個 取數據 lis 1 count = 0 2 username = ‘zhangsan‘ 3 userpassword = ‘111111‘ 4 5 f = open(‘lock.txt‘,‘r+‘

python的zabbix短信報警程序收不到短信

短信報警 size mark sha 但是 文件權限 pro strong shadow 問題:用python寫了一個短信的程序,在“報警媒介類型”中也調用了,設置了用戶和動作。在報表--動作日誌中也有記錄。但是就是沒有收到短信,而且短信程序的日誌裏面也沒有。解決辦法:後來

使用python一個監控mysql的腳本在zabbix web上自定義模板

python腳本自定義zabbix監控模##先使用MySQLdb的接口關聯數據庫。[root@cml python]# cat check_Mysql_custom.py #!/usr/local/bin/python '''author = chenmingle''&

為什麽python的多線程不能利用多核CPU但是咱們在代碼的時候多線程的確是在而且還比單線程快。

全局 睡眠 read 處理 sleep roc 需要 寫代碼 強制 python裏的多線程是單cpu意義上的多線程,它和多cpu上的多線程有著本質的區別。單cpu多線程:並發多cpu多線程:並行內部包含並發 首先強調背景: 1、GIL是什麽?GIL的全稱是Gl

給女朋友用Python了一個自動抽獎程序!Python在手獎品我有!

com () 單身 代碼 女孩子 nbsp 不能 是不是 apt 我相信大部分的女孩子都是喜歡買買買的,我還沒有見過不喜歡買東西的女孩子,當然很多東西也是有抽獎這項優惠的,很多小程序都有抽獎這個功能的,好了廢話不多說了,為了給女朋友寫這款抽獎程序,可謂是嘔心瀝血!不過看到她

python簡單的web靜態伺服器對socket的深入理解。

import socket from multiprocessing import Process import time #...使用socket建立簡單的靜態伺服器 def func1(sock): # 子程序實現的功能 read_data = sock.recv(2

一談起外掛都想不到python程式設計今天利用Python一款吃雞輔助!

  那麼我們就用python和R做資料分析來回答以下的靈魂發問? 首先來看下資料:           大吉大利,今晚吃雞~ 今天跟朋友玩了幾把吃雞,經歷了各種死法

擔心酒店資訊洩露我用Python了段加密演算法看你怎麼破

前段時間的酒店資訊洩露事情,鬧的沸沸揚揚!確實我們很多的資料在網路上都是裸奔,在資料庫裡面躺著也都是明文資料,連我自己的寫某某程式都被熱情的粉絲攻破!不如,我們用萬能的Python寫段加密資料傳送玩玩,也許就能避免酒店資料洩漏了! 簡單的場景: Serve

python一個小程式解決買水果的問題?

問題: 商店總共有三種水果,香蕉/蘋果/葡萄,單價分別為3.5/5.0/3.0元/500克。 寫一個小程式實現:          1、輸出一個選單:列印每種水果的價格:          2、尋問客戶欲購買水果?          3、客戶想購買的克數?    

python的簡單的選課系統遇到一堆問題

寫了一個簡單的選課系統的程式碼,問題一堆,遇到pickle反序列化不能完全匯出的問題,大神還煩解答下吧 #!/bin/bash/evn python #* coding:utf-8 * #Autior Dahai import pickle ‘’‘定義三個函式,

Tkinter小專案:用Python一個地址收藏管理工具迅速提高你的工作效率

如何管理雜亂的電腦桌面和一大堆的瀏覽器收藏網址?我用python寫了一個工具,迅速提高工作效率。 工作了一段時間發現,電腦桌面上已經滿屏的常用軟體、常用專案資料夾的快捷方式,一大堆的常用文件,瀏覽器上收藏的工作網址更是有100+,通常想開啟一個文件、網址要尋找半

利用Python一個破解QQ音樂的指令碼海量付費歌曲任意下載!

有些時候我們需要下載一些音樂檔案到本地,比較操蛋是必須要付費,所以寫了一個下載器用!! 在這裡小編多說一句,那些想要入門Python的同學,加群:943752371可以獲取Python入門學習資料哦!   開發工具 Python版本:3.7相關模組:reque