首先,不要重新发明轮子。这正是denyhosts
用于:
DenyHosts is a python program that automatically blocks ssh attacks by
adding entries to /etc/hosts.deny. DenyHosts will also inform Linux
administrators about offending hosts, attacked users and suspicious
logins.
据我所知,denyhosts
仅用于ssh
连接,但也
fail2ban
涉及几乎所有内容:
Fail2Ban consists of a client, server and configuration files to limit
brute force authentication attempts.
The server program fail2ban-server is responsible for monitoring log
files and issuing ban/unban commands. It gets configured through a
simple protocol by fail2ban-client, which can also read configuration
files and issue corresponding configuration commands to the server.
两者都在存储库中可用:
sudo apt-get install denyhosts fail2ban
如果愿意,也可以编写脚本。就像是:
#!/usr/bin/env sh
netstat -an |
awk -vmax=100 '/tcp/{split($5,a,":"); if(a[1] > 0 && a[1]!="0.0.0.0"){c[a[1]]++}}
END{for(ip in c){if(c[ip]>max){print ip}}}' |
while read ip; do iptables -I INPUT 1 -s "$ip" -j DROP; done
在awk
将提取的IP地址,并指望他们和只打印那些出现超过max
倍(这里-vmax=100
,相应修改)。然后将IP馈送到运行相关iptables
规则的while循环。
要运行此24/7,我将创建一个cronjob,每分钟左右运行一次以上命令。将此行添加到/etc/crontab
* * * * * root /path/to/script.sh