Can someone please help with regex pattern for below string in Python? I have .log
file and I want to find below line from string I have to get user and ip.
I want regex that can get me one word before from
and one after from
.
Failed password for root from 123.183.209.132 port 39706 ssh2
I want root
and 123.183.209.132
from above string
Failed password for invalid user packer from 13.82.211.217 port 45832 ssh2
I want packer
and 13.82.211.217
from above string
reverse mapping checking getaddrinfo for undefined.datagroup.ua
[93.183.207.5] failed - POSSIBLE BREAK-IN ATTEMPT!
reverse mapping checking getaddrinfo for nsg-static-226.127.71.182.airtel.in [182.71.127.226] failed - POSSIBLE BREAK-IN ATTEMPT!
reverse mapping checking getaddrinfo for 179.185.44.168.static.gvt.net.br [179.185.44.168] failed - POSSIBLE BREAK-IN ATTEMPT!
I want undefined.datagroup.ua
and 93.183.207.5
from(new regex).
My working code.
def parse(filename, date=None):
try:
# string = 'Failed password for ([a-z]*|[a-z]* [a-z]* [a-z]*) from '
string = 'Failed password for ([a-z]*|[a-z]* [a-z]* [a-z]*) from [0-9]+(?:\.[0-9]+){3}'
# string_sub = 'for (?<user>[a-zA-Z\.]+).*?(?<ip>(?:\d{1,3}\.){3}\d{1,3})'
# string_re = re.compile(r"^[^ ]+ - (C[^ ]*) \[([^ ]+)").match
match_list =[]
with open(filename, 'r') as file:
for line in file:
for match in re.finditer(string, line, re.S):
match_text = match.group()
user_ip = re.search(r'Failed password for .*?(\w+) from (\d+(?:\.\d+){3})', match_text)
user = user_ip.groups()[0]
print(user)
except KeyError as e:
msg="key %s is missing" % str(e)
return msg
except Exception as e:
return str(e)
I'm stuck with regex.