- import os, gzip, socket, re, shutil, cPickle, operator, GeoIP
- #config stuffs....
- path='/home/pronto/logs/'
- newfile="ssh_fails.dict.p"
- oldfil="ssh_fails.dict.old.p"
- gi = GeoIP.open("/home/pronto/scripts/ssh-fail/GeoLiteCity.dat",GeoIP.GEOIP_STANDARD)
- shutil.copy2('/home/pronto/logs/ssh_fails.dict.p', '/home/pronto/logs/ssh_fails.dict.old.p')
- ignore_ip = ['75.101.142.201', '198.101.145.249', '76.21.11.37']
- def openfile(logfile):
- if 'gz' in logfile:
- celery = gzip.open(logfile, 'r')
- else:
- celery = open(logfile, 'r')
- return celery
- def get_index(seq, attribute, value):
- return next(index for (index, d) in enumerate(seq) if d[attribute] == value)
- def ipcheck(ip,dns):
- dns_ip=socket.gethostbyname_ex(dns)[2]
- if ip not in dns_ip:
- return "IP: "+ dns_ip[0]
- else:
- return "good"
- def port_check(address, port):
- s = socket.socket()
- s.settimeout(1)
- try:
- s.connect((address, port))
- return True
- except:
- return False
- ip_dict = []
- for files in os.listdir('/var/log'):
- if 'auth.log' in files:
- logfile = "/var/log/" + files
- celery = openfile(logfile)
- for line in celery:
- if "Failed" in line:
- if "pronto" not in line:
- ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)
- if ip:
- if ip[0] not in ignore_ip:
- try:
- index = get_index(ip_dict, 'IP', ip[0])
- ip_dict[index]['attempts'] += 1
- ip_dict[index]['geo'] = gi.record_by_addr(ip[0])['country_name']
- except:
- try:
- host = socket.gethostbyaddr(ip[0])[0]
- checker = ipcheck(ip[0], host)
- ip_dict.append({"IP": ip[0], "attempts": 1, "RDNS": host, "IPCHECK": checker})
- except:
- ip_dict.append({"IP": ip[0], "attempts": 1, "RDNS": None, "IPCHECK": None})
- ip_dict.sort(key=operator.itemgetter('attempts'), reverse=True)
- old_list=cPickle.load(open("/home/pronto/logs/ssh_fails.dict.old.p","rb"))
- for a in ip_dict:
- try:
- index_old=get_index(old_list,'IP',a['IP'])
- index_new=get_index(ip_dict,'IP',a['IP'])
- if ip_dict[index_new]['IP'] == old_list[index_old]['IP']:
- diff = ip_dict[index_new]['attempts']-old_list[index_old]['attempts']
- ip_dict[index_new]['new']=diff
- else:
- ip_dict[index_new]['new']=0
- except:
- ip_dict[index_new]['new']=0
- for a in ip_dict:
- if a['attempts'] > 99:
- index=get_index(ip_dict,'IP',a['IP'])
- ip_dict[index]['Port80']=port_check(a['IP'],80)
- ip_dict[index]['Port443']=port_check(a['IP'],443)
- ip_dict[index]['Port22']=port_check(a['IP'],22)
- cPickle.dump(ip_dict,open("/home/pronto/logs/ssh_fails.dict.p", "wb"))
Untitled
Posted by Anonymous on Sat 8th Dec 2012 00:31
raw | new post
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.