標籤:python 防攻擊
學習python中,寫了一個簡單預防攻擊指令碼,感覺不好,mark下待留以後改進。
#!/bin/env python#-*- coding:utf-8 -*-import sqlite3import commandsimport timeimport logginglog_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 = 0while 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 = 0while 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 一個簡單防攻擊指令碼