1

Mini Apache Logfile-Analyzer in Python v 0.1

Geschrieben von: Rocu am 22.11.2009 um 11:28 am

Heute habe ich einen kleinen Apache-Logfile Analyzer in Python geschrieben. Warum? Ich muss manchmal durch unsere Logfiles und nach Auffälligkeiten suchen. Da ich das wiederkehrend mache muss es automatisiert sein.

Da das Ding für den Hausgebrauch ist, kann es auch nur dass was ich direkt wollte und zwar:

  • nach Script Tags in Referer und User-Agent suchen
  • Seiten mit Fehler 500 analysiere
  • Sehen wie häufig eine einzelne IP vorkommt

Wenn ihr mehr wissen wollt, dann schreibt euch einfach eure eigene Analyzer-Klasse mit den Methoden processedParsedLine und printStats und hängt sie in Zeile 73 mit ein analyzers = [HttpStatusCodeAnalyzer(500), ClientIpAnalyzer("64.127.102.82"), SecurityAnalyzer(), meinNeuerAnalyzer()]

Ich warne gleich vor: Ich kenne mich nicht mit Python aus.

#!/usr/bin/python
import sys, re

APACHE_LOG_REGEX = re.compile(r'(\d+\.\d+\.\d+\.\d+) ([^ ]*) ([^ ]*) \[([^\]]*)\] "([^"]*)" (\d+) ([^ ]*) "([^"]*)" "([^"]*)"')

# Counts HTTP-Response Codes
class HttpStatusCodeAnalyzer(object):
	__error_count = 0
	__error_dict = {}

	# Sets the error code for this analyser
	def __init__(self, error_code):
		self.__error_code = error_code

	def processParsedLine(self, parsed_line):
		if(int(parsed_line[5]) == self.__error_code):
			self.__error_count += 1
			if(parsed_line[4] not in self.__error_dict):
				self.__error_dict[parsed_line[4]] = 0
		  	self.__error_dict[parsed_line[4]] += 1

	# Print Error statistics
	def printStats(self):
		print "Statistic for Error ", self.__error_code, " :"
		print self.__error_count, " Total errors"
		error_pages = self.__error_dict.keys().sort()
		for error in error_pages:
			print self.__error_dict[error], "x : ", error

# Get hit-countStatistics for a single ip-adress
class ClientIpAnalyzer(object):
	__ip_count = 0

	def __init__(self, client_ip):
		self.__client_ip = client_ip

	def processParsedLine(self, parsed_line):
		if(parsed_line[0] == self.__client_ip):
			self.__ip_count += 1

	def printStats(self):
		print "Statistic for Client with Ip ", self.__client_ip, " :"
		print self.__ip_count, " Total Hits"

# Looks if a <script>-tag was send in the header-fields
class SecurityAnalyzer(object):
	__javascript = re.compile(r"<script")
	__hacker_dict = {}

	def processParsedLine(self, parsed_line):
		referer_check = self.__javascript.search(parsed_line[7])
		browser_check = self.__javascript.search(parsed_line[8])

		if(referer_check or browser_check):
			if(parsed_line[0] not in self.__hacker_dict):
		  		self.__hacker_dict[parsed_line[0]] = parsed_line

	def printStats(self):
		hacker_ips = self.__hacker_dict.keys()
		print "Hacker Statistics:"
		for ip in hacker_ips:
			print ip, " Log example :", self.__hacker_dict[ip]

# Parses a line of a logfile into a nice structure
def parseLine(line):
	matched_line = APACHE_LOG_REGEX.match(line)
	if(matched_line == None):
		return
	parsed_line = matched_line.groups()
	return parsed_line

input = open(sys.argv[1], "r")
analyzers = [HttpStatusCodeAnalyzer(500), ClientIpAnalyzer("64.127.102.82"), SecurityAnalyzer()]

for line in input:
	parsed_line = parseLine(line)
	if(parsed_line == None):
		continue
	for analyzer in analyzers:
		analyzer.processParsedLine(parsed_line)

input.close()
for analyzer in analyzers:
	analyzer.printStats()
sys.exit(0)</pre>

Die Bedienung ist übrigens (unter *nix) wie folgt:

  • Zuerst ausführbar machen
  • ./parser.py logfile.log
  • Oder auch gerne etwas wie ./parser.py logfile.log > auswertung.txt

    So. Das war mein heutiges 60 Minuten-Programm in Python. Solltet ihr euch mit Python auskennen irgend etwas besonders schlecht finden, dann schreibt es bitte in den Kommentaren. Solltet ihr eine eigene Analyzer-Klasse bauen, dann bitte auch :)

    Ähnliche Artikel:

Eine Antwort auf “Mini Apache Logfile-Analyzer in Python v 0.1”

  1. Japs sagt:

    Hi, ich bin auch gerade dabei, Python zu lernen. Find die Sache ganz gut gelöst, sofern ich das beeurteilen kann. Gerne mehr Python Stuff. Im Gegensatz zu PHP & Co findet sich ja nicht viel deutsches Wissen im Netz, was sehr schade ist da Python eine schöne Sache ist.

Hinterlasse einen Kommentar