sessions.txttrashstring
trashstring
trashstring
10:08:54 AM Login successful from user Sergey Pavlov id_session=2710
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
10:35:33 PM Closing session (user $escalation$, reserved) id_session=2710 reason=1,20
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
trashstring
import re
from datetime import datetime
sessions = {}
with open('sessions.txt', 'r', encoding='utf-8') as f:
log = f.readlines()
for line in log:
if 'Login successful' in line:
chunks = re.search(r'(.+?) Login successful from user (.+?) id_session=(.+?)$', line)
# Возможно придется подкорректировать преобразование времени, если я не угадал с форматом
login_time = datetime.strptime(chunks.group(1), '%I:%M:%S %p')
sessions[chunks.group(3)] = {'login_time': login_time, 'username': chunks.group(2)}
elif 'Closing session' in line:
chunks = re.search(r'(.+?) Closing session.+id_session=(.+?)\sreason=(.+)$', line)
logout_time = datetime.strptime(chunks.group(1), '%I:%M:%S %p')
session_id = chunks.group(2)
if session_id not in sessions:
print('Сессия {} закрыта, нет данных о входе'.format(session_id))
else:
login_time = sessions[session_id]['login_time']
username = sessions[session_id]['username']
session_time = logout_time - login_time
print('Пользователь {} завершил сессию спустя {}, причина: {}'.format(username, session_time, chunks.group(3)))
del sessions[session_id]