yun 发表于 2017-1-27 17:51:28

shell(python)防ftp暴力破解代码分享

  朋友的服务器搭建了ftp,这几天一直在被暴力破解,找到我要我帮忙解决这个问题,登录到他服务器上一看,是用的Pure-ftp搭建的ftp服务器,它日志文件跟系统日志文件绑定在一起:/var/log/messages,知道了这些后,专门从网上找了个脚本给他,让脚本去帮他挡攻击.
脚本内容:#!/usr/bin/python
#This script can deny anythings to all of ports
import os,re

#Find time today
tm=os.popen('date').read()

#Basic steup
deny_port= '21'
log_path = '/var/log/messages'
ip_count= '30'
aut_message = tm+ '.*pure-ftpd.*failed.*'
list_path='/shell/ip_list.txt'

#The program run to decide
16
class port:

    def re_ip(self):
        r_file=open(log_path,'r').read()
        s_rule=re.compile(aut_message,re.I)
        n_rule=s_rule.findall(r_file)
        self.f_ip =re.findall('\d+\.\d+\.\d+\.\d+',''.join(n_rule))

    def loop_list(self):
        for ip in set(self.f_ip):
            if not os.path.isfile(list_path):
                os.mknod(list_path)
            self.ip_list=open(list_path,'rw+')
            if re.search(ip,self.ip_list.read()) is None:
                if self.f_ip.count(ip) >= int(ip_count):
                    self.ip_list.write(ip+'\n')
                self.ip_list.seek(0)
            else:
                self.ip_list.seek(0)

    def iptables(self):
        for ip in self.ip_list.readlines():
            iptables_list=os.popen('iptables --list --numeric').read()
            if re.search(ip.strip('\n'),iptables_list) is None:
                if re.search('RH-Firewall-1-INPUT',iptables_list,re.I) is None:
                    os.system("iptables -I INPUT 2 -m state --state NEW -s %s -m tcp -p tcp --dport %s -j DROP"%(ip.strip('\n'),deny_port))
                else:
                    os.system("iptables -I RH-Firewall-1-INPUT 2 -m state --state NEW -s %s -m tcp -p tcp --dport %s -j DROP"%(ip.strip('\n'),deny_port))

D=port()
D.re_ip()
D.loop_list()
D.iptables()
脚本实现的原理是:
通过程序读取->带登录信息验证的日志文件->调用iptables直接进行封杀

把脚本丢到系统的计划任务里实现自动抵御:
chmod +x /root/soft_shell/deny_port.py
vi /etc/crontab
*/3 * * * * root /root/soft_shell/deny_port.py
好了,做完这些重启下系统的crond服务,等脚本自己去封杀ip.
页: [1]
查看完整版本: shell(python)防ftp暴力破解代码分享