Personal tools
You are here: Home Downloads logger.py
Document Actions

logger.py

by dredd last modified 2005-10-12 03:01 AM

A Python based tool which converts a log file to html and sends you an email if that log has changed.

Click here to get the file

Size 6.3 kB - File type text/x-python

File contents

#! /usr/bin/python
##### Logger.py
# Copyright (c) 2005, George Bobeck
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, 
# are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this 
#    list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice, this
#    list of conditions and the following disclaimer in the documentation and/or other
#    materials provided with the distribution.
#
#  * Neither the name of the LOYOLA UNIVERSITY CHICAGO nor the names of its contributors 
#    may be used to endorse or promote products derived from this software without  
#    specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#####
#
# To use: python logger.py <file to be processed>
#
# OR chmod 0700 faker.py so that you can ./faker.py <port>
#
# You will need to read over this entire file and make modifications before you can use this file.
#
#####

import copy
import os
import sys
import shutil
import smtplib
from time import gmtime, strftime
from types import *
from email.MIMEText import MIMEText

test = 1
arguments = sys.argv[1:]
todo = arguments[0]
input = open(todo , 'r')
todo_list= input.readlines()
logsub = todo
l = logsub.split('/')
l = l[len(l)-1]
l=l.replace('.','-')
todo_data = '%s.data'%(l)

# Edit these variables to suit your needs
# EMAIL VARIABLES
server = 'localhost'		# your mail server here
source = 'root@localhost'	# an originating email, should be valid
destination= 'user@server.TLD'  # your email address here.

# HTML VARIABLES
# Example /var/log/auth.log would become auth-log.html
# This file will be placed in /usr/local/apache2/htdocs , but you can change that.
# If you don't want this feature, keep on going.  The proper places to comment out 
# have been signified below.

# Change this to where you want the .html file to be created.
# If you don't want to use html output, leave it as is OR change to /dev/null
page = '/usr/local/apache2/htdocs/'

#leave this alone.
page = page + '%s.html'%(l)

# takes a list and strips out elements which start with '#'
def comment_strip(input_list): 
	input_list2 = []
	lp = 0
	while lp < len(input_list):
		st = input_list[lp]
		if st[0] is not '#':
			input_list2.append(str)
		lp = lp + 1
	return input_list2

# takes a list of strings and adds a '\n' character to the end of each string.
def spacer(lst):
	lst2 = []
	lp = 0
	while lp < len(lst):
		s = lst[lp] + '\n'
		lst2.append(s)
		lp = lp+1
	return lst2

# takes a list of strings and returns one large string	    
def stringer(lst): 
	st = ''
	lp = 0
	while lp < len(lst):
		st = st + lst[lp]
		lp = lp + 1
	
	return st

# converts the list (text) into a html file.  
# Filename is the output, sub is used for the title and header of the page.
def webize(filename , text, sub):
        f = open(filename , 'w')
        time = strftime("%a, %d %b %Y %H:%M")
        if type(text) is StringType:
                a = text.split('\n')
                lt = []
                b = ''
                lp = 0
                while lp < len(a):
                        b = '\t' + a[lp] + '<br> \n'
			
                        if (b == '\t<br> \n'):
				# if the line is 'blank', nuke it.
				b = ''
			if ('[**]' in b):
				# if the line is the beginning of an alert, add a  blank line
				b = '<br>' + b	
			lt.append(b)
                        lp = lp + 1
        htmlhead = '<html> \n   <head> \n\t<meta name="GENERATOR" content="Some script written by George Bobeck"> \n\t<META http-equiv="Pragma" content="no-cache"> \n\t<META NAME="ROBOTS" content="NOINDEX,FOLLOW"> \n\t<TITLE>%s</TITLE> \n   </head>\n' % sub
        htmlbody1 = '   <body> \n\t<H1> %s as of %s </H1><br> \n\t \n' % (sub, time)
        htmlbody2 = stringer(lt) + '    \n   </body> \n</html>'
        f.writelines(htmlhead)
        f.writelines(htmlbody1)
        f.writelines(htmlbody2)
        f.close()

# mail function... simple but effective.  should be self explanitory.
def mail(server, source, destination, message): 
	msg = MIMEText(message)
	# me == the sender's email address
	# you == the recipient's email address
	me = source
	you = destination
	msg['Subject'] = "Current %s Log Events"%(logsub)
	msg['From'] = me
	msg['To'] = you
	# Send the message via a SMTP server, but don't include the
	# envelope header.
	s = smtplib.SMTP(server)
	s.sendmail(me, [you], msg.as_string())
	s.quit()

todo_list = spacer(todo_list)
try:
	# Get data file.
        input = open(todo_data , 'r')
        backup_list = input.readlines()
	backup_list = spacer(backup_list)
except:
	# The data file doesn't exist, create it.
        shutil.copyfile(todo , todo_data)
        input = open(todo_data , 'r')
        backup_list= input.readlines()
	backup_list = spacer(backup_list)
        test = 0

# if file hasn't changed, print 'no change' and update webpage.
if (todo_list == backup_list) and test:
        shutil.copyfile(todo , todo_data)
	TODO = stringer(todo_list)
	# COMMENT OUT THE NEXT LINE IF YOU DON'T WANT TO HAVE HTML OUTPUT.
	webize(page, TODO, logsub)
	# COMMENT OUT THE NEXT LINE IF YOU HATE VERBOSE OUTPUT
        print 'no change'

# if file changed, pring 'change', email it and update webpage.
else:
        TODO = stringer(todo_list)
	# COMMENT OUT THE NEXT LINE IF YOU DON'T WANT TO HAVE EMAILED OUTPUT.
        mail(server, source, destination, TODO)
        shutil.copyfile(todo , todo_data)
	# COMMENT OUT THE NEXT LINE IF YOU DON'T WANT TO HAVE HTML OUTPUT.
	webize(page, TODO, logsub)
	# COMMENT OUT THE NEXT LINE IF YOU HATE VERBOSE OUTPUT
        print 'change'
        
#<eof>
« November 2009 »
Su Mo Tu We Th Fr Sa
1234567
891011121314
15161718192021
22232425262728
2930
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: