I am currently searching through a log file that contains IP addresses.
Log example:
10.1.177.198 Tue Jun 19 09:25:16 CDT 2018
10.1.160.198 Tue Jun 19 09:25:38 CDT 2018
10.1.177.198 Tue Jun 19 09:25:36 CDT 2018
10.1.160.198 Tue Jun 19 09:25:40 CDT 2018
10.1.177.198 Tue Jun 19 09:26:38 CDT 2018
10.1.177.198 Tue Jun 19 09:27:16 CDT 2018
10.1.177.198 Tue Jun 19 09:28:38 CDT 2018
I can currently grab the IP address from the last line of the log. I can also search for all line numbers that have the same IP address.
If the last IP address in the log is listed 3 or more times in the log, how can I get the line number for the 3rd to last occurrence of that IP address?
For example, I want to get the line number for this line:
10.1.177.198 Tue Jun 19 09:26:38 CDT 2018
Or better yet, just print the entire line.
Here is an example of my code:
import re
def run():
try:
logfile = open('read.log', 'r')
for line in logfile:
x1 = line.split()[0]
for num, line in enumerate(logfile, 0):
if x1 in line:
print("Found " + x1 + " at line:", num)
print ('Last Line: ' + x1)
logfile.close
except OSError as e:
print (e)
run()
I am listing all the line numbers where the specific IP address occurs.
print("Found " + x1 + " at line:", num)
I am wanting to print the line where "num" is the 3rd to last number in the list of line numbers.
My overall goal is to grab the IP address from the last line in the log file. Then check if it has previously been listed more than 3 times. If it has, I want to find the 3rd to last listing of the address and get the line number.(or just print the address and date listed on that line)