Nginx automatically blocks excessive ip connections

Source: Internet
Author: User

You can use commands to view IP addresses that are too high for web connections, but you need to use AI to seal them. This is too troublesome. You can directly write a script to automatically resolve this issue. The web server uses nginx and python is 2.6
First, create an empty file deny. ip in the config file of nginx, and add "include deny. ip;" to the http tag of nginx. conf ;". Add an automatic script to the sbin directory of nginx. The script can find the largest connected IP address and insert it into the shield list. After verifying the correctness, import the configuration. Send an email after all or an error occurs. If you do not want to report an error, the system reports a 403 error when the ip address is accessed again. If you do not want to report an error, you can jump to another page. The source code is as follows:

Check_deny_up.py START I script

#!/bin/python#-*- coding:utf-8 -*-# Filename:    main.py# Revision:    1.0# Date:        2012-06-20# Author:      simonzhang# web:         www.simonzhang.net# Email:       simon-zzm@163.com### END INIT INFOimportosfromstring importstripfromemail.mime.text importMIMETextimportsmtplib####check_comm ="/bin/netstat -antp|grep :80|awk ' ''{print $5}'|awk -F: '{print $1}'|sort -r|uniq -c|sort -n -k1 -r"max_ip =100mail_host =‘’;mail_user =‘’;mail_pwd =‘’;mail_to =‘’;mail_cc =‘’;defreboot_nginx_sendmail(ip_list):#### reboot nginx_get_check_confile =os.popen('./nginx -t').readlines()ifstr(_get_check_confile.find('ok')) !='-1':os.system('./nginx -s reload')_mail_content =ip_listelse:_mail_content ='Error'#### send mailmsg =MIMEText(_mail_content)msg['From'] =mail_usermsg['Subject'] =' force ip.'msg['To'] =mail_totry:s =smtplib.SMTP()s.connect(mail_host)s.login(mail_user, mail_pwd)s.sendmail(mail_user, [mail_to, mail_cc], msg.as_string())s.close()exceptException, e:printe#### force out IPdefforce_out(_deny_ip):_write_status =0_read_force_file =open('../conf/deny.ip', 'rb').read()ifstr(_read_force_file.find(_deny_ip)) =='-1':try:_get_force_file =open('../conf/deny.ip', 'ab')_get_force_file.write('deny %s ;\n'%_deny_ip)_get_force_file.close()_write_status =1return_write_statusexcept:return_write_statusreboot_nginx_sendmail("Error !")return_write_statusdefmain():get_high_ip =os.popen('%s'%check_comm).readlines()_count_force_ip =0_force_ip_list =''fori inxrange(3):try:_get_count =strip(get_high_ip[i]).split(' ')[0]_get_ip =strip(strip(get_high_ip[i]).split(' ')[1])except:_get_count =0_get_ip =''# Maximum connection IP is Beyond the limit valueif(int(_get_count) > max_ip) and(len(_get_ip) > 0):force_ip =_get_ip_get_status =force_out(force_ip)# check maximum is added in the deny.ip fileifstr(_get_status) =='1':_count_force_ip +=1_force_ip_list +=' %s '%force_ip#    if _count_force_ip > 0:#        reboot_nginx_sendmail(_force_ip_list)if__name__ =='__main__':main()

Check_deny_up.sh

#! /bin/bash## make simon-zzm@163.com##### END INIT INFO# Source function library.. /etc/profilecd/Data/apps/nginx/sbin/# See how we were called.case"$1"instart)/usr/local/bin/pythoncheck_ip_deny.py;;*)echo$"Usage: $0 {start}"exit1esacexit

Run the startup script in crontab.


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.