|
| 1 | +import win32evtlog |
| 2 | +import win32evtlogutil |
| 3 | +import win32con |
| 4 | +from datetime import datetime, timedelta |
| 5 | + |
| 6 | +# Definir o nome do log e os identificadores de evento |
| 7 | +log_name = 'Security' |
| 8 | +logon_event_id = 4624 |
| 9 | +logoff_event_id = 4634 |
| 10 | + |
| 11 | +# Abrir o log de eventos |
| 12 | +handle = win32evtlog.OpenEventLog(None, log_name) |
| 13 | + |
| 14 | +# Configurar o arquivo de saída |
| 15 | +with open("eventos_logon_logoff.txt", "w") as file: |
| 16 | + flags = win32evtlog.EVENTLOG_FORWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ |
| 17 | + total_records = win32evtlog.GetNumberOfEventLogRecords(handle) |
| 18 | + events = [] |
| 19 | + logon_times = [] |
| 20 | + logoff_times = [] |
| 21 | + |
| 22 | + while True: |
| 23 | + records = win32evtlog.ReadEventLog(handle, flags, 0) |
| 24 | + if not records: |
| 25 | + break |
| 26 | + for event in records: |
| 27 | + event_time = event.TimeGenerated.Format() |
| 28 | + event_time = datetime.strptime(event_time, '%a %b %d %H:%M:%S %Y') |
| 29 | + if event.EventID == logon_event_id: |
| 30 | + logon_times.append(event_time) |
| 31 | + file.write(f"Logon: {event_time}\n") |
| 32 | + elif event.EventID == logoff_event_id: |
| 33 | + logoff_times.append(event_time) |
| 34 | + file.write(f"Logoff: {event_time}\n") |
| 35 | + |
| 36 | + # Ordenar as listas para garantir que estejam em ordem cronológica |
| 37 | + logon_times.sort() |
| 38 | + logoff_times.sort() |
| 39 | + |
| 40 | + # Calcular o tempo total de sessão |
| 41 | + total_session_time = timedelta() |
| 42 | + for logon_time in logon_times: |
| 43 | + logoff_time = next((l for l in logoff_times if l > logon_time), None) |
| 44 | + if logoff_time: |
| 45 | + session_time = logoff_time - logon_time |
| 46 | + total_session_time += session_time |
| 47 | + file.write(f"Período de sessão: {session_time} (de {logon_time} até {logoff_time})\n") |
| 48 | + |
| 49 | + file.write(f"\nTempo total de sessão: {total_session_time}\n") |
| 50 | + |
| 51 | +win32evtlog.CloseEventLog(handle) |
| 52 | +print("Eventos salvos em 'eventos_logon_logoff.txt'.") |
0 commit comments