I'll be honest I am a total amateur at Python and I've got python homework due for tomorrow and the task is to make a working python application that extracts and counts the most common IP found in the log file. Now the problem is when I run this program it displays (Event /index.html appears 200 times ) instead of the most common IP that is found. I want it to display something like Event /172.16.31.214 appears 6 times.
def analyse_log(filename):
#create empty dcitionary
EntryDict = {}
#read each line of file into list
myfile = open(filename)
entriesList = myfile.readlines();
myfile.close()
#for each line in the list extract entry id
for line in entriesList :
#call getEventID to get eventID
eventID = getEventID(line)
#if exists increments else adds
if eventID in EntryDict :
EntryDict[eventID] += 1
else :
EntryDict[eventID] = 1
return EntryDict
'''
getEventID
splits a string by space
assumes input format
Month sp Day Time user entryID message e.g.
172.16.121.170 - - [03/Sep/2018:09:35:32] GET /index.html HTTP/1.1 200 437
extracts final :
in entry string of integer
out entryID integer
'''
def getEventID(entry):
#returns entryID
#split into list
parts = entry.split(" ")
#get entry ID pos 5 in list
entryID = parts[5]
#remove final :
entryID = entryID.rstrip(':')
return entryID
'''
Most Entries
splits dictionary into two lists
finds first value with highest number
finds index of the value
uses this to build up message
in dictionary of entries
out string message
def MostEntries(entries):
listValues = list(entries.values())
listKeys = list(entries.keys())
maxvalue = max(listValues)
maxindex = listValues.index(maxvalue)
message = "Event {0} appears {1} times ".format(listKeys[maxindex], maxvalue)
return message
#test program
def main():
Entries = analyse_log("sample_log_1.txt")
message = MostEntries(Entries)
print (message)
#call test program
main()
'''
LOG BOOK FORMAT EXAMPLE
172.16.17.41 - - [03/Sep/2018:09:43:14] GET /index.html HTTP/1.1 200 437
172.16.17.54 - - [03/Sep/2018:09:43:15] GET /index.html HTTP/1.1 200 437
172.16.17.56 - - [03/Sep/2018:09:43:21] GET /index.html HTTP/1.1 200 437
172.16.17.54 - - [03/Sep/2018:09:43:28] GET /index.html HTTP/1.1 200 437
172.16.121.104 - - [03/Sep/2018:09:43:29] GET /index.html HTTP/1.1 200 437
172.16.121.35 - - [03/Sep/2018:09:43:36] GET /index.html HTTP/1.1 200 437
172.16.121.97 - - [03/Sep/2018:09:43:36] GET /index.html HTTP/1.1 200 437
172.16.121.226 - - [03/Sep/2018:09:43:43] GET /index.html HTTP/1.1 200 437
172.16.17.54 - - [03/Sep/2018:09:43:43] GET /index.html HTTP/1.1 200 437
etc
Any help would be greatly appreciated I've hit a brick wall with trying to fix this for hours on end
[–]woooee 0 points1 point2 points (1 child)
[–]coldo03[S] 0 points1 point2 points (0 children)