【网站】非法访问攻击防御脚本
之前写过一个DDOS攻击检测和防御脚本,今天稍作改造写了个非法访问检测的防御脚本
1、建立脚本文件/root/scripts/auto_detect_attack_unknown.sh
#!/bin/sh #auto deny attack IP address - unknown url attack #maplnan 2016-9-4 #定义变量 LOG_FILE=/usr/local/nginx/logs/error.log #定义脚本日志文件 SCRIPT_FILE_NAME=`basename $0` SCRIPT_DIR_NAME=`dirname $0` SCRIPT_LOG_FILE=${SCRIPT_DIR_NAME}/log/${SCRIPT_FILE_NAME}.log #IP白名单文件 WHITELIST_FILE=${SCRIPT_DIR_NAME}/ip_whitelist.conf #如下为截取日志文件恶意攻击ip,每秒内访问不存在的网址大于3次就写入防火墙,禁止以后再访问服务器的80端口 IP_ADDR=`grep -v "access forbidden by rule" $LOG_FILE | grep "Primary script unknown" | awk 'gsub(/,/, "", $20) {print $20" "$1" "$2}' | sort |uniq -c |sort -nr |awk ' $1>3 {print $0}'` IPTABLE_CONF=/etc/sysconfig/iptables echo cat <<EOF ++++++++++++++welcome to use auto detect attack IP address++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++------------------------------------++++++++++++++++++ EOF echo RESTART_FLAG=0 for i in `echo $IP_ADDR` do #查看iptables配置文件是否含有提取的IP信息 RULE="-A INPUT -s $i -p TCP --dport 80 -j DROP" RULE_COUNT=`cat $IPTABLE_CONF |grep -e "$RULE" -c` WHITE_IP_COUNT=`cat $WHITELIST_FILE | grep -e "$i" -c` if [ $WHITE_IP_COUNT -ne 0 ];then echo "$i exists in white list." elif [ $RULE_COUNT -eq 0 ];then #判断iptables配置文件里面是否存在已拒绝的ip,如何不存在就不再添加相应条目 sed -i "/Add/a $RULE" $IPTABLE_CONF RESTART_FLAG=1 #记录日志 echo `date "+%Y-%m-%d %H:%M:%S"`" 发现非法访问IP ${i},增加iptables规则:${RULE}" >> ${SCRIPT_LOG_FILE} echo `tail -n 99999 $LOG_FILE |grep -v "saveOrderCoordinates"|grep -e "$i" -m 1` >> ${SCRIPT_LOG_FILE} echo `tail -n 99999 $LOG_FILE |grep -v "saveOrderCoordinates"|sort -r|grep -e "$i" -m 1` >> ${SCRIPT_LOG_FILE} echo "" >> ${SCRIPT_LOG_FILE} else #如何存在的话,就打印提示信息即可 echo "$i has existed in iptables." fi done echo #最后重启iptables生效 if [ $RESTART_FLAG -eq 1 ];then /etc/init.d/iptables restart fi
2、增加IP白名单ip_whitelist.conf,文件中每行一个IP
3、增加crontab -e记录,定时执行脚本
*/5 * * * * /root/scripts/auto_detect_attack_unknown.sh
完毕。
标签: 网站
还没有人抢沙发呢~