First, Shell code
#!/bin/bash
#Author: Zhangge
#Desc: Auto Deny black_ip Script.
#Date: 2014-11-05
#取得参数 is a concurrent threshold, and if left blank, the default allows single IP maximum 50 concurrency (the actual test found that 2M bandwidth, 10 or more concurrent servers have been unable to access!) )
if [[Z $]];then
Num=50
Else
Num=$1
Fi
#巧妙的进入到脚本工作目录
CD $ (CD $ (dirname $BASH _source) && pwd)
#请求检查, judgment and pulling black main function function
function Check () {
Iplist= ' Netstat-an |grep ^tcp.*:80|egrep-v ' listen|127.0.0.1 ' |awk-f ' []+| [:] ' {print $} ' |sort|uniq-c|sort-rn|awk-v str= $num ' {if ($1>STR) {print $}} '
if [[!-Z $iplist]];
Then
>./black_ip.txt
For BLACK_IP in $iplist
Todo
#白名单过滤中已取消IP段的判断功能, you can modify the following code as needed (refer to the script written the day before yesterday)
#exclude_ip = ' echo $black _ip | Awk-f "." ' {print $. ' $ "." $} '
#grep-Q $exclude _ip/white_ip.txt
Grep-q $black _ip./white_ip.txt
if [[$?-eq 0]];then
echo "$black _ip (white_ip)" >>./black_ip.txt
Else
echo $black _ip >>./black_ip.txt
IPTABLES-NL | grep $black _ip | | (iptables-i input-s $black _ip-j DROP & echo "$black _ip ' date +%y-%m-%h:%m:%s '" >>./deny.log & Echo 1 > ./sendmail)
Fi
Done
#存在并发超过阈值的单IP就发送邮件
if [[' Cat./sendmail ' = 1]];then sendmsg;fi
Fi
}
#发邮件函数
function sendmsg () {
NETSTAT-NUTLP | grep "SendMail" >/dev/null 2>&1 | | /etc/init.d/sendmail Start >/dev/null 2>&1
Echo-e "From: Email address @qq.com\nto: Email address @qq.com\nsubject:someone attacking your system!! \nits Ip is ">./message
Cat./black_ip.txt >>./message
/usr/sbin/sendmail-f Email address @qq.com-t email address @qq.com-i <./message
>./sendmail
}
#间隔10s无限循环检查函数
While True
Todo
Check
#每隔10s检查一次, time can be customized according to need
Sleep 10
Done
Ii. Executing scripts
After you save the above code as DENY_BLACKIP.SH, use the following command to run the script backstage (the following 50 indicates the number of concurrent, adjustable):
Nohup/deny_blackip.sh &
After execution, the following message appears:
[Root@mars_server iptables]# nohup./deny_blackip.sh &
[1] 23630
[Root@mars_server iptables]# nohup:ignoring input and appending output to ' nohup.out '
Indicates that if the script produces output information, it will be written to the Nohup.out file, and you can see that the current directory has generated an empty nohup.out:
[Root@mars_server iptables]# ll Nohup.out
-RW-------1 Root 0 Nov 5 21:15 nohup.out
All right, now you perform the implementation PS aux should be able to find the following process:
Root 23630 0.0 0.2 5060 1224 pts/0 S 21:15 0:00/bin/bash./deny_blackip.sh
Root 23964 0.0 0.0 4064 508 pts/0 S 21:19 0:00 sleep 10
Everything is going well! Every 10s will check the server request, if an IP more than 50 concurrent, immediately pull black, and an email to you!