1. Requires root user execution
2. The Hosts.deny file will be generated in the directory where the script resides, and the data is stored
Script to Serve "I rookie, do not spray ah":
#!/usr/bin/python# _*_coding:utf-8 _*_import timeimport reimport sysimport Osfrom datetime import datelogfile = r '/var/log/secure ' current_path = Sys.path[0]denyfile = r '/' +current_path+ '/hosts.deny ' months_31 = [' Jan ', ' Mar ', ' may ', ' Jul ', ']months_30 = [', ' Oct ', ' Dec ', ' APR ', ' June ', ' Sep ', ']month_28or29 = ', ' Feb ' months = { ' Jan ': 1, ' Feb ': 2, ' Mar ': 3, ' APR ': 4, ' May ': 5, ' June ':6, ' Jul ': 7, ': 8, ' SEP ': 9, ' Oct ': +, ' Nov ': 11, ' Dec ': 12 }month_days = {}for mon in &NBSP;MONTHS_31:&NBSP;&NBSP;&NBSP;&NBSP;MONTH_DAYS[MON]&NBSP;=&NBSP;31FOR&NBSP;MON&NBSP;IN&NBSP;MONTHS_30: month_days[mon] = 30if date.isocalendar (Date.today ()) [0] % 4 == 0: month_days[month_28or29] = 29else: month_days[month_28or29] = 28def copyfiles (Sourcefile, targetfile): open (targetFile, "WB"). Write (Open (sourcefile, "RB"). Read ()) Def search_source (): t = Date.today () month = t.strftime ('%b ') day = T.strftime ('%d ') pat = re.compile (' .+sshd.+failed password.+ (\d{ 1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) .+ ') lines = [] F = open (logfile, ' R ') for line in f: if line.split () [0] == month and (int (day) - int ( Line.split () [1]) < 7 and (int (day) - int (Line.split () [1]) >= 0 : &NBSP;&NBSP;&NBSP;&NBSP;&NBSp; if re.search (Pat,line): lines.append (line) elif (Months[month] - months[line.split () [0]]) == 1 or (Months[month] - months[line.split () [0]]) == -11: if (int (day) + month_days[line.split () [0]] - int (Line.split () [1]) < 7 and re.search (pat,line): lines.append (line) Return linesdef count_ips (lines): count = {} if len (lines) == 0: print ' no One use ssh and failed. ' raise SystemExit pat = Re.compile (' (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) ') for line in lines: ip = re.findall (Pat,line) [0] if ip in count: count[ip] += 1 else: count[ip] = 1 return countdef deny_ips (count): f = open (Denyfile, ' W ') valve = 50 for ip in count: if count[ip] >= valve: word = ' all: %s #failed %d times in a Week.\n ' % (Ip,count[ip]) F.write (Word) f.close () Def main (): current_path=sys.path[0] if os.path.isfile (current_path+ "/hosts.deny"): copyfiles (current_path+ "/hosts.deny", current_path+ "/hosts.deny." +STR (int (time.time ()))) lines = search_source () count = count_ips (lines) deny_ips (count) if __name__ == ' __main__ ': main ()
Python stats by brute force attempts to log on to the local IP and number of times