nginx 自動封 ip 過高連接

用命令查看web連接過高的IP地址,但是需要人工智能去封,太麻煩了,直接寫個腳本自動解決。web服務器是用nginx,python爲2.6
  首先在nignx的config中建立空文件deny.ip, 然後在nginx.conf 的http標籤中添加“include deny.ip;”。在nginx下sbin的目錄中放入自動腳本。腳本可以查到連接最大的IP,並插入屏蔽列表中,驗證正確性後導入配置。全部完成或者出錯後發送郵件。被封ip再次訪問會報403錯誤,如果不希望報錯可以跳轉到其它頁面。源碼如下:

check_deny_up.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-20
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       [email protected]
### END INIT INFO
importos
fromstring importstrip
fromemail.mime.text importMIMEText
importsmtplib
####
check_comm ="/bin/netstat -antp|grep :80|awk ' ''{print $5}'|awk -F: '{print $1}'|sort -r|uniq -c|sort -n -k1 -r"
max_ip =100
mail_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_list
else:
_mail_content ='Error'
#### send mail
msg =MIMEText(_mail_content)
msg['From'] =mail_user
msg['Subject'] =' force ip.'
msg['To'] =mail_to
try:
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 IP
defforce_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 =1
return_write_status
except:
return_write_status
reboot_nginx_sendmail("Error !")
return_write_status
defmain():
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 value
if(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 file
ifstr(_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()

啓動i腳本
check_deny_up.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#! /bin/bash
#
#
#
### END INIT INFO
# Source function library.
. /etc/profile
cd/Data/apps/nginx/sbin/
# See how we were called.
case"$1"in
start)
/usr/local/bin/pythoncheck_ip_deny.py
;;
*)
echo$"Usage: $0 {start}"
exit1
esac
exit

將啓動腳本放在crontab中運行。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章