Linux shell script Analysis Nginx log anti-small DDoS attack

Source: Internet
Author: User
Tags iptables


Site was DDoS attack, so wrote a foot to resist, to achieve the way:

1. Attack characteristics, different IP constantly post Web page, resulting in excessive resource consumption
2. Analyze Nginx Access log, Judge post feature to obtain Client access IP
3. Attack IP block with a connection number greater than 50
4. Record attack IP to document
5. Comparison of each acquired attack IP and an existing attack IP

View Source code:

#!/bin/bash

Websites= (
example.com
)

minute_now= ' Date +%m '
Max_connections=50
Banips= "/wwwdata/jobs/banips.txt"

For site in ${websites[*]}
Todo
Access_log_file= "/wwwdata/logs/${site}.access.log"
If [-F "${access_log_file}"]
Then
Cat ${access_log_file} | grep POST | awk ' {print $} ' | Sort |uniq-c| Sort-nr >/wwwdata/jobs/ip_records.txt

lines= ' Wc-l/wwwdata/jobs/ip_records.txt | awk ' {print '} '
echo "Lines: $lines"

I=1
While [${i}-le ${lines}]
Todo
Ip_record= ' head-${i}/wwwdata/jobs/ip_records.txt | Tail-1 | Sed ' s/^[\t]*//g '

Ip_count= ' echo ${ip_record} | awk ' {print '} '
Ip_address= ' echo ${ip_record} | awk ' {print $} '

echo "${ip_count} ${ip_address}"

If [${ip_count}-gt ${max_connections}]
Then
Banned= ' Cat ${banips} | grep ${ip_address} | Wc-l '
If [${banned}-LT 1]
Then
Iptables-a input-s x.x.x.x-p tcp-m State--state new-m TCP--dport 80-j DROP
Echo ${ip_address} >> ${banips}
Fi
Fi

i= ' expr ${i} + 1 '
Done

Service Iptables Save
Service Iptables Restart

If [${minute_now}-eq 30]
Then
Cat ${access_log_file} >>/wwwdata/logs/olds/${site}.access.log
Cat/dev/null > ${access_log_file}
Fi
Fi
Done

If [${minute_now}-eq 30]
Then
Service Nginx Restart
Fi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.