Created
September 17, 2023 14:19
-
-
Save bryaneaton/6bc6e62f1fe01478cb13df9c8587c29d to your computer and use it in GitHub Desktop.
Grep TarSSH log for ips and add to fail2ban list
This file contains hidden or 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
#!/bin/bash | |
set -euo pipefail | |
if [ "$EUID" -ne 0 ] | |
then echo "Please run as root" | |
exit | |
fi | |
log_file="/tmp/tarssh.log" | |
# Use grep with regular expression to extract IP addresses | |
ip_addresses=$(grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" "$log_file") | |
# Use sort and uniq to get unique IP addresses | |
unique_ip_addresses=$(echo "$ip_addresses" | sort | uniq) | |
# Print the unique IP addresses | |
echo "$unique_ip_addresses" | |
# Loop through each unique IP address | |
for ip_address in $unique_ip_addresses; do | |
# Check if the IP address is already in the fail2ban ban list | |
status=$(fail2ban-client status sshd | grep -c $ip_address) | |
# If IP address is not in the ban list, add it to fail2ban | |
if [[ $status -eq 0 ]]; then | |
echo "Adding $ip_address to fail2ban" | |
fail2ban-client set sshd banip $ip_address | |
else | |
echo "$ip_address is already banned in fail2ban" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment