I am a beginner to python and I have a log file which I need to take date time. I use regex for taking the 2 conditions but unfortunately my result is not as expected, this is the result I got:
Date Time
20170119 193739188+0900
log file:
20170119 193739188+0900 elim1td001p imapserv 58124 72559 139941478487808 Note;AcctBadPswd(50/6)
I would like to know that how to change the date and time format inside the regex code to have a better result? This is my regex code:
import re
from csv import writer
log_file = '/Users/kiya/Desktop/mysql/ipscan/ip.txt'
output_file = '/Users/kiya/Desktop/mysql/ipscan/output.csv'
name_to_check = 'MBX_AUTHENTICATION_FAILED'
with open(log_file,encoding="utf-8") as infile:
for line in infile:
if name_to_check in line:
username = re.search(r'(?<=userName=\[)(.*)(?=\],)', line)
username = username.group()
date = re.search('(?P<year>\d{4})(?P<month>\d{2})(?P<date>\d{2})', line)
date = date.groups()
time = re.search(r'(\d{9}\+\d{4})', line)
time = time.group()
ip = re.search(
r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',
line)
ip = ip.group()
with open(output_file, 'w') as outfile:
csv_writer = writer(outfile)
csv_writer.writerow(["Username","Date","Time","Ip_address"])
csv_writer.writerow([username,date,time,ip])
I would like the result to be as:
Date: 2017-01-09
Time: 01:15:30 (like)