Python - splitting a list then loop through to find an ip address -
i'm required analyse system log. i've been told should split list , iterate through find ip address. small part of log. there duplicate entries therefore must take notice of lines contain words "failed password root".
jan 10 09:32:07 j4-be03 sshd[3876]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:09 j4-be03 sshd[3876]: failed password root 218.241.173.35 port 47084 ssh2 jan 10 09:32:17 j4-be03 sshd[3879]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:19 j4-be03 sshd[3879]: failed password root 218.241.173.35 port 47901 ssh2 jan 10 09:32:26 j4-be03 sshd[3881]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:29 j4-be03 sshd[3881]: failed password root 218.241.173.35 port 48652 ssh2
here code far, bit of psuedo code aswell.
f=open('auth','r') count=0 line in f: if "failed password root from" in line: count +=1 if count>=13: take ip address, remove duplicates , print address
if there 13 or more attempts 1 ip address address must added file. understand how write new file, if possible small example handy. familiar .append
probably easier use re
:
re_ips = r'failed password (?:root|invalid user\s?.*) ((?:\d{1,3}\.){3}\d{1,3}) '
this ip addresses relevant lines. here's example of how use regex print ips recur 13 or more times file bad_ips.log
:
from collections import defaultdict import re ip_freq = defaultdict(int) open("auth", "r") fh: match in re.finditer(r'failed password (?:root|invalid user\s?.*) ((?:\d{1,3}\.){3}\d{1,3}) ', fh.read()): ip_freq[match.group(1)] += 1 open("bad_ips.log", "w") fh: ip, n in ip_freq.iteritems(): if n>=13: print >>fh, ip
edit: updated regex per new request.
edit2: updated regex again match correctly invalid user xxxx
in log file.
edit3: tidied example
Comments
Post a Comment