方法一:

vi block.sh

#! /bin/bash
cat /var/log/secure | awk '/Failed/{print $(NF-3)}'| sort | uniq -c|awk '{print $2"="$1;}' > /root/black.txt
DEFINE="5"
for i in `cat /root/black.txt`
do
        IP=`echo $i | awk -F= '{print $1}'`
        NUM=`echo $i | awk -F= '{print $2}'`
        if [ $NUM -gt $DEFINE ];
        then
                grep $IP /etc/hosts.deny > /dev/null
                if [ $? -gt 0 ];
                then
                        echo "sshd:$IP" >> /etc/hosts.deny
                fi
        fi
done


vi /etc/crontab

*/10 * * * * root /bin/sh /root/block.sh >/dev/null 2>&1


vi /etc/hosts.allow 加入白名单,防止无法登录


方法二:

tar zxf DenyHosts-2.6.tar.gz
cd DenyHosts-2.6
python setup.py install
cd /usr/share/denyhosts/
cp denyhosts.cfg-dist denyhosts.cfg
vi denyhosts.cfg
PURGE_DENY = 5m
DENY_THRESHOLD_INVALID = 1
DENY_THRESHOLD_VALID = 3
DENY_THRESHOLD_ROOT = 1
HOSTNAME_LOOKUP=NO
#ADMIN_EMAIL =
#SMTP_HOST = localhost
#SMTP_PORT = 25
#SMTP_FROM = DenyHosts <nobody@localhost>
#SMTP_SUBJECT = DenyHosts Report
AGE_RESET_VALID=5m
#AGE_RESET_ROOT=25d
#AGE_RESET_RESTRICTED=25d
#AGE_RESET_INVALID=10d
DAEMON_PURGE = 5m

vi  /etc/logrotate.d/denyhosts
# how many historical logs do you wish to keep
rotate 5

# don't rotate empty logs
notifempty

missingok

# uncomment this if you want the file created with
# rw permissions for the root user and root group
#create 0600 root root

# uncomment this if you want to compress the rotated files
#compress

# uncomment this out if you want to rotate it each day
#daily

# uncomment this out if you want to rotate it each month
#monthly

# uncomment this if you want the logs to be capped at a
# certain size and then specify the size.
#size=64k

# this should match the DAEMON_LOG configuration setting of DenyHosts
/var/log/denyhosts {
        prerotate
                service denyhosts stop
        endscript
        postrotate
                service denyhosts start
        endscript
}

cp daemon-control-dist daemon-control
ln -s /usr/share/denyhosts/daemon-control /etc/init.d/denyhosts
chkconfig --add denyhosts
service denyhosts start
service rsyslog restart


vi /etc/hosts.allow 加入白名单,防止无法登录