Advertisement
Guest User

miniban.sh

a guest
Nov 19th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.71 KB | None | 0 0
  1. #!/bin/bash
  2. clear
  3.  
  4. # Filen skal overvåkes
  5. LOGFILE=$1
  6.  
  7. # declare an array
  8. declare -A ips
  9.  
  10. # start reading log
  11. cat ${LOGFILE} | \
  12. while IFS='' read -r line; do
  13.   # read lines and grep the lines with "Failed password" match and IPS only
  14.   IP=$(echo $line | grep -i "Failed password" | awk '{print $11}' | uniq -c | sort -nr |  grep -Eo '[0-9\.]{7,15}')
  15.     if [ ! -z ${IP} ]; then # skipping the lines that has no match
  16.       echo "IP found : ${IP}"
  17.       eval "(( ips[$IP] ++ ))" # adding an element to associative array with ip as key and value as number of attempts found
  18.       if (( ips[$IP] >= 3 )); then # checking array if the IP has more than 3 attempts
  19.         sudo iptables -L | grep ssh | grep -w $IP >>/dev/null 2>&1
  20.         if (( $? == 0 )); then # checking if there is already an ssh login block for this ip.
  21.           echo "IP $IP with ${ips[$IP]} failed attempts is already blocked"
  22.         else
  23.           echo "----------------ALERT---------------------"
  24.           echo "Blocking this IP: " $IP
  25.           echo "This $IP has ${ips[$IP]} failed attempts"
  26.           echo "sudo iptables -I INPUT -s $IP -p tcp --dport ssh -j DROP" # blocks it if there is no iptables rules found
  27.           echo "------------------------------------------"
  28.         fi
  29.       fi
  30.     fi
  31. done
  32.  
  33. # For better understanding of the script line 25 is showing as ouput instead of executing
  34. # This is to avoid accidental block of  known IPs with some failed attemps.
  35. # Remove the echo "" for executing this command
  36. # Iptables must run as sudo. The script can be run as sudo
  37.  
  38. # Instead of iptables we can use the following
  39. # method to block the IPs. It might not work on
  40. # ubuntu 16.10+
  41. #
  42. # sshd: 192.168.0.1 >> /etc/hosts.deny
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement