python 一个简单防攻击脚本
2015-04-29 16:01
429 查看
学习python中,写了一个简单预防攻击脚本,感觉不好,mark下待留以后改进。
#!/bin/env python #-*- coding:utf-8 -*- import sqlite3 import commands import time import logging log_file='/var/log/ddoskill.log' logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s',datefmt='%a,%d %b %Y %H:%M:%S',filename=log_file,filemode='a') exclude_list = ['192.168.1.56','192.168.1.200','192.168.1.100','192.168.1.300','127.0.0.1'] cx = sqlite3.connect('/tmp/ddoskill.db') #查看系统防火墙是否开启 (status_4,output_4) = commands.getstatusoutput("service iptables status") if status_4 != 0: logging.error("iptables is closed!") exit(100) #取出数据库中已有IP存入ip列表中 ip_list = [] out_list = cx.execute("select ip from ddos").fetchall() i = 0 while i < len(out_list): ip_list.append(str(out_list[i][0])) i+=1 #将连接数过大且不存在于数据库中的IP禁掉 command_1="netstat -n|awk '/^tcp/{print $5}'|cut -d: -f1|sort|uniq -c" output_1 = commands.getoutput(command_1) length = len(output_1.split('\n')) x = 0 while x < length: num = output_1.split('\n')[x].split()[0] IP = str(output_1.split('\n')[x].split()[1]) if int(num) >= 100 and IP not in ip_list and IP not in exclude_list: logging.warning("将 %s 写进数据库,并在iptable禁止访问!" % IP) command_3 = "iptables -I INPUT -s "+IP+" -j DROP" output_3 = commands.getoutput(command_3) cx.execute("insert into ddos(ip) values(?)",(IP,)) x+=1 #删除列表中5小时之前的数据,并同时删除iptable相应条目 for ip in ip_list: select_com ="select time from ddos where ip='%s'" % ip otime = str(cx.execute(select_com).fetchone()[0]) intv = time.time() - time.mktime(time.strptime(otime,'%Y-%m-%d %H:%M:%S')) if intv/60/60 > 5: logging.warning("从iptables和数据库中删除:%s" % ip) command_2 = "iptables -D INPUT -s "+ip+" -j DROP" output_2 = commands.getoutput(command_2) delete_com = "delete from ddos where ip='%s'" % ip cx.execute(delete_com) cx.commit() cx.close()
相关文章推荐
- 一个简单的python读写文件脚本
- 一个简单的判断远端服务器端口是否通的Python脚本
- 一个简单比较oracle两个用户下表数据差异的python脚本
- 一个简单的将yuv图片转化为jpeg格式图片的Python脚本程序
- python学习之路-第六天-一个简单的脚本
- 一个简单的监控redis性能的python脚本
- 关于一个简单的python上传到linux服务器再经过shell脚本ftp传输的问题
- Windows 下针对python脚本做一个简单的进程保护
- python构建一个简单的备份脚本
- 一个简单的使用代理访问百度页面内容的python脚本
- [python脚本]一个简单的web爬虫(1)
- 写一个简单的python脚本来返回ip地址的掩码,子网个数等
- [python脚本]一个简单的web爬虫(1)
- 写了一个简单的防止IP攻击的脚本 [转]
- 使用一个简单的python脚本将一个本地文件以码流的形式,通过UDP协议发送到对端:
- 分享一个简单的python读写文件脚本
- 写python脚本进行abaqus建模,抄某指导书中的一个简单的悬臂梁代码
- 一个简单的 python 实现 图片同步脚本 ,对于有图片群集的项目有参考价值
- 写一个python脚本,实现简单的http服务器功能:
- python写一个最简单的可执行脚本