一个对付ssh密码扫描的脚本
1分钟同一个IP超过10次尝试密码出错,IPTABLES封24小时.
练练手的,应该有更强大的工具的.
[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/env python
import time,syslog,os,sys,re
import bsddb
pid=os.fork()
if pid>0:
sys.exit(0)
elif pid<0:
print "fork error"
sys.exit(-1)
os.setsid()
os.chdir("/tmp")
os.close(0)
os.close(1)
os.close(2)
os.umask(0)
def iptables_fresh():
ddb=bsddb.hashopen("/var/log/sshdetect.db")
nowt=time.time()
for ip in ddb.keys():
disable_time=float(ddb[ip])
if disable_time<nowt-86400:
syslog.syslog("unblock ip address %s" % ip)
iptables_delete(ip)
ddb.close()
def iptables_delete(ip):
ddb=bsddb.hashopen("/var/log/sshdetect.db")
cmd="iptables -D INPUT -s %s -p tcp ! --syn -j DROP" % ip
os.system(cmd)
os.system("service iptables save")
del(ddb[ip])
ddb.close()
def iptables_disable(ip):
ddb=bsddb.hashopen("/var/log/sshdetect.db")
nowt=time.time()
cmd="iptables -I INPUT -s %s -p tcp ! --syn -j DROP" % ip
os.system(cmd)
os.system("service iptables save")
ddb[ip]=str(nowt)
ddb.close()
cmd="tail -F /var/log/messages"
f=os.popen(cmd)
failips={}
while 1:
iptables_fresh()
try:
line=f.readline()
except:
f.close()
f=os.popen(cmd)
continue
rs=re.search("authentication failure.*rhost=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})",line)
nowt=time.time()
if rs:
ip=rs.group(1)
if failips.has_key(ip):
failips[ip].append(nowt)
while failips[ip][0]<nowt-60:
failips[ip].pop(0)
if len(failips[ip])>10:
iptables_disable(ip)
del(failips[ip])
syslog.syslog("block ip address %s" % ip)
else:
failips[ip]=[nowt]