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