Created
October 9, 2024 20:10
-
-
Save ConnerWill/d1c3dc727c6e1e15be86e1953f422635 to your computer and use it in GitHub Desktop.
Python script to graph the number of failed SSH login attempts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
from collections import defaultdict | |
# Path to the auth.log file | |
LOG_FILE = '/var/log/auth.log' | |
# Function to parse the log file and count failed login attempts per IP address | |
def parse_ssh_failed_attempts_by_ip(log_file): | |
failed_attempts = defaultdict(int) | |
# Regex to match the IP address for failed SSH login attempts | |
pattern = re.compile(r'Failed password for .* from (\d{1,3}(?:\.\d{1,3}){3})') | |
with open(log_file, 'r') as file: | |
for line in file: | |
match = pattern.search(line) | |
if match: | |
# Extract the IP address and increment the counter for that IP | |
ip_address = match.group(1) | |
failed_attempts[ip_address] += 1 | |
return failed_attempts | |
# Function to generate an ASCII bar chart | |
def display_ascii_graph(data): | |
# Get max value for scaling the bars | |
max_attempts = max(data.values(), default=1) | |
print("{:<15} | Failed Attempts".format('IP Address')) | |
print('-' * 50) | |
for ip, count in sorted(data.items(), key=lambda x: x[1], reverse=True): # Sort by count, descending | |
bar = '#' * (count * 50 // max_attempts) # Scale the bar to fit 50 characters | |
print("{:<15} | {} {}".format(ip, bar, count)) | |
if __name__ == "__main__": | |
# Parse the log and get the data by IP address | |
failed_attempts_by_ip = parse_ssh_failed_attempts_by_ip(LOG_FILE) | |
# Display the ASCII graph | |
display_ascii_graph(failed_attempts_by_ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment