SSH login Log parsing script (Python)

Source: Internet
Author: User
Tags openlog

Haven't updated the blog for a long time, wrote an early script to save the file, a script for analyzing user login log/etc/auth.log, can analyze

The number of successes, failures, and user names from the IP address and login failures can be used to monitor for brute force attacks and can be used to collect dictionaries to avoid the problem of too simple passwords


#/usr/bin/env python3.4#anyalize the/etc/auth.log files to get# 1) What many failed login trials# 2) How many Succeede D Login trials# 3) How many IP's where the login trials comes from and what they are# 4) How many invalid usernames ar E tested and what they are## usage:# anyalyze <filename># Note:-to standard input streamimport Sysimpor    T re# # of Trialsdebug_flag = 0info_flag = 0def Debug (msg): If Debug_flag:print ("[Debug]", MSG) def info (msg):    If Info_flag:print ("[INFO]", msg) def openlog (source): if (Source = = "-"): Return Sys.stdin; Else:debug ("Opening file:" + source) F = open (source, ' R ') return F # failed loginptnfailed = Re.compi Le (R ' Failed password for (? p<user>\w+) from (? p<ip>\d+\.\d+\.\d+\.\d+) ' # Invalid user Trailptninvalid = Re.compile (R ' Failed password for invalid user (? p<user>\w+) from (? p<ip>\d+\.\d+\.\d+\.\d+) ' # Login succeededptnsuccess = re.compile (R ' AcceptEd Password for (? p<user>\w+) from (? p<ip>\d+\.\d+\.\d+\.\d+) ' # Sudoptnsudo = Re.compile (R ' session opened for user (? p<user>\w+) by (? p<ip>\w+) ' # >0:valid user & Incorreck password# <0:invalid usernfailed = {}nsuccess = {}nSuccess_record    s = {}ipfailed={}ipsuccess={}if (len (SYS.ARGV) < 2): Print ("Usage:") print ("\ t" +sys.argv[0]+ "<filename>")    Print ("Note: <filename> can be-for standard input stream") exit (0) log = Openlog (sys.argv[1]) for line in log:        m = Ptnfailed.search (line) debug (m) if not m:m = Ptninvalid.search (line) debug (m) if M: user = M.group (ptninvalid.groupindex[' user ']) if user not in Nfailed:info ("[FAILED] Found a new user &            lt; "+ user +" > ");  Nfailed[user] = 0 Nfailed[user] = nfailed[user]+1 IP = m.group (ptninvalid.groupindex[' IP ')) if IP not In Ipfailed:ipfailed[ip] = 0 info ("[FAILED] Found a new IP < "+ IP +" > "); IPFAILED[IP] = Ipfailed[ip] + 1 else:m = Ptnsuccess.search (line) if not m:m = Ptnsudo.search            (line) debug (M) if M:print (line) user = M.group (ptnsuccess.groupindex[' user ') If user not in Nsuccess:nsuccess[user] = 0 info ("[SUCCESS] Found a new user <" + u            Ser + ">");                Nsuccess[user] = nsuccess[user]+1 IP = m.group (ptnsuccess.groupindex[' IP ')) if IP not in ipsuccess:            IPSUCCESS[IP] = 0 info ("[SUCCESS] Found a new IP <" + IP + ">"); IPSUCCESS[IP] = Ipsuccess[ip] + 1 else:debug ("* * * Unknown:" + line) # todo:close (log) print ("nfailed  : ") print (nfailed) print (" nsuccess: ") print (nsuccess) # Key-value list# It assure that the order was the same to the coming Orderclass keyvalue:def __init__ (self, Key, value): Self.key = key Self.value =Value def __repr__ (self): return repr ((Self.key, Self.value)) # Return a KeyValue list because of the order of th  e keys in a dictionary# was unexpected, not same to the order as they be put indef sortdict (adict): result=[] keys =    Sorted (Adict.keys (), key=adict.__getitem__, reverse = True) for k in Keys:result.append (KeyValue (k,adict[k)))    Return result# convert a KeyValue list to HTML table# @return a HTML stringdef keyvaluelist2html (kvlist, Headermap):        html = "<table>\n" hkey = ' key ' Hvalue = ' Value ' If Headermap:hkey = headermap[' key '];        Hvalue = headermap[' value '];  Debug (hkey) Debug (hvalue) html+= "<th>" + "<td>" +hkey+ ' </td> ' + ' <td> ' +hvalue+ ' </td> ' + ' </th>\n ' for kv in kvlist:html + = "<tr>" + "<td>" +kv.key+ ' </td> ' + ' <td> ' +str (Kv.va Lue) + ' </td> ' + ' </tr>\n ' html + = "</table>\n" Return Htmlprint ("------------tested userList *failed*-------------", Sortdict (nfailed)) print ("------------Source IP *failed*------------------", Sortdict ( ipfailed) Print ("------------Login Success-------------", Sortdict (nsuccess)) print ("------------Source IP *success *-----------------", sortdict (ipsuccess)) # Writing result to a HTML reportprint (" wring result to result.html ... ") reportf Ilename = ' auth.log-analysis.html ' report = open (Reportfilename, ' W ') if Report:title = ' auth log analysis ' REPORT.WR                 Ite (' 

SSH login Log parsing script (Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.