We noticed a large number of failed login attempts on a few Linux servers that we had SSH open to the outside. So to prevent such attacks I modified a script to be run by cron at a interval time to detect failed logins and after a certain number of attempts add them to hosts.deny.

Hope this helps someone.

#This script will monitor for failed login attempts and after a specified number of times add the ip to a deny list
# read logfile and look for invalid login attemps
grep sshd $LOGFILE |grep "Invalid user"| awk '{print $NF}'|sort|uniq -c|sort -n|sed "s/[[:space:]]*//" | while read i
        # read number of failed attempts
        count=`echo $i | cut -d" " -f1`
        # read ip address from failed attempt
        ip=`echo $i | cut -d" " -f2`
        #check hostdeny file to see if IP already exist
        already=`grep $ip $HOSTSDENY | grep sshd`
        #if IP does not exist add it to hostdeny file
        if [ -z "$already"  ]
                if [ "$count" -ge "$BADCOUNT" ]
                        echo "sshd: "$ip >> $HOSTSDENY
(Visited 1 times, 1 visits today)

Category: Free Tools, Technical Solutions
This entry was posted Wednesday, 10 October, 2007 at 1:56 pm
You can follow any responses to this entry via RSS.


  • GoldTek says:

    You’ll need to watchout for this grep statement :

    already=`grep $ip $HOSTSDENY | grep sshd`

    IP addresses have (.) periods in them which is a wildcard for regular expressions.

    If for example the IP address was being checked by the above grep command, it would also report a match if there was 211.101 in the file already and the script would never add to the Hosts deny file.

  • Leave a Reply

    Your email address will not be published. Required fields are marked *