SSH logon log analysis script (Python)

Source: Internet
Author: User
Tags openlog

SSH logon log analysis script (Python)

I haven't updated my blog for a long time. I wrote a very early script to save it to the next file, and a script used to analyze the user login log/etc/auth. log, which can be analyzed.

The number of successes and failures, as well as the IP address and user name from which the logon fails, can be used to monitor whether there are any brute force attacks. When more attempts are made, they can be used to collect dictionaries to avoid the password being too simple.

 

#/usr/bin/env python3.4#Anyalize the /etc/auth.log files to get#   1) how many failed login trials#   2) how many succeeded login trials#   3) how many IP's where the login trials comes from and what they are#   4) how many invalid usernames are tested and what they are##   usage:#       anyalyze 
 
  #   note: - for standard input streamimport sysimport 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.compile(r'Failed password for (?P
  
   \w+) from (?P
   
    \d+\.\d+\.\d+\.\d+)')# invalid user trailptnInvalid = re.compile(r'Failed password for invalid user (?P
    
     \w+) from (?P
     
      \d+\.\d+\.\d+\.\d+)')# login succeededptnSuccess = re.compile(r'Accepted password for (?P
      
       \w+) from (?P
       
        \d+\.\d+\.\d+\.\d+)')# sudoptnSudo = re.compile(r'session opened for user (?P
        
         \w+) by (?P
         
          \w+)')# >0: valid user & incorreck password# <0: invalid usernFailed = {}nSuccess = {}nSuccess_records = {}ipFailed={}ipSuccess={}if(len(sys.argv) < 2): print("Usage:") print("\t"+sys.argv[0]+" 
          
           ") print("Note: 
           
             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 <" + 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 <" + user + ">"); 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)# a key-value list# it assure that the order is 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 the keys in a dictionary# is unexpected, not same to the order as they are 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 ="\n" hkey = 'Key' hvalue = 'Value' if headerMap: hkey = headerMap['key']; hvalue = headerMap['value']; debug(hkey) debug(hvalue) html+= "'+''+ '\n' for kv in kvlist: html += ""+"'+''+ '\n' html += "
            
 
"+" "+hkey+' '+hvalue+'
"+kv.key+' '+str(kv.value)+'
\n" return htmlprint("------------ Tested user list *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 ...")reportFilename = 'auth.log-analysis.html'report = open(reportFilename, 'w')if report: title = 'Auth Log Analysis' report.write('\n') report.write(''+title+'\n') report.write(' ') report.write("------------ Tested user list *Failed* -------------\n") report.write(KeyValueList2Html(sortDict(nFailed),{'key':'username','value':'# of trial'})) report.write("------------ Source IP *Failed* ------------------") report.write(KeyValueList2Html(sortDict(ipFailed),{'key':'source IP','value':'# of trial'})) report.write("------------ Login Success -------------") report.write(KeyValueList2Html(sortDict(nSuccess),{'key':'username','value':'# of trial'})) report.write("------------ Source IP *Success* -----------------") report.write(KeyValueList2Html(sortDict(ipSuccess),{'key':'source IP','value':'# of login'})) report.write('\n') report.write('\n') report.write('\n')# close(report) print('OK')else: print('Failed to open file:', reportFilename)


 

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.