-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_analyzer.py
More file actions
58 lines (45 loc) · 2.17 KB
/
Copy pathlog_analyzer.py
File metadata and controls
58 lines (45 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import time
import os
from datetime import datetime
# The log file we are analyzing
TARGET_LOG = "process_security.log"
# The "threat" keywords we are surveilling for
THREAT_KEYWORDS = ["FORBIDDEN", "SECURITY ALERT", "ERROR", "CRITICAL"]
def log_threat_found(keyword, full_line):
"""Logs when a threat is detected in another log file."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("threat_alerts.log", "a") as f:
f.write(f"[{timestamp}] THREAT DETECTED: Found '{keyword}' -> {full_line.strip()}\n")
def analyze_logs():
print(f"--- Log Analysis Surveillance Started ---")
print(f"--- Scanning '{TARGET_LOG}' for: {', '.join(THREAT_KEYWORDS)} ---")
# Check if the target log even exists yet
if not os.path.exists(TARGET_LOG):
# Create it if it doesn't exist so we don't crash
with open(TARGET_LOG, "w") as f:
f.write("Log File Initialized\n")
# Start at the end of the file (so we only see NEW logs)
file_size = os.path.getsize(TARGET_LOG)
try:
while True:
# Re-check the file size to see if it grew
current_size = os.path.getsize(TARGET_LOG)
if current_size > file_size:
# Open the file and jump to where we left off
with open(TARGET_LOG, "r") as f:
f.seek(file_size)
new_lines = f.readlines()
for line in new_lines:
# Check each new line for our keywords
for keyword in THREAT_KEYWORDS:
if keyword.upper() in line.upper():
print(f"\n[!!!] THREAT ALERT: Found '{keyword}' in log!")
print(f" Line: {line.strip()}")
log_threat_found(keyword, line)
# Update our position in the file
file_size = current_size
time.sleep(1) # Scan every second
except KeyboardInterrupt:
print("\nLog analysis stopped.")
if __name__ == "__main__":
analyze_logs()