destinationFile = "./destination-file.csv"
sourceFile = "./source-file"
criteria = "Invalid user"
matches = []
with open(sourceFile) as src:
import re
for line in src.read().split("\n"):
if not criteria in line: continue
login = re.sub(".*" + criteria + " (\w+).*", r"\1", line)
matches.append(login)
matches = sorted(list(set(matches)))
count = len(matches)
if count == 0:
import sys
print("No lines having '{}' in {}. Abort.".format(criteria, sourceFile))
exit(1)
else:
with open(destinationFile, "w+") as dst:
dst.write("\n".join(matches))
print("{} login(s) written to {}.".format(count, destinationFile))
#M# file open/read/parse/write, regex/regular expression, regex group capture/replacement, list sort, list clean/remove duplicates, print list in file, system error
May 26 07:29:20 instance-1 sshd[20327]: Disconnected from 61.147.247.146 port 45177 [preauth]
May 26 07:32:22 instance-1 sshd[20351]: Invalid user nagios from 159.65.144.233 port 49715
May 26 07:32:22 instance-1 sshd[20351]: input_userauth_request: invalid user nagios [preauth]
May 26 07:32:23 instance-1 sshd[20351]: Received disconnect from 159.65.144.233 port 49715:11: Normal
May 26 07:32:22 instance-1 sshd[20351]: Invalid user admin from 159.65.144.233 port 49715
May 26 07:32:22 instance-1 sshd[20351]: Invalid user nagios from 159.65.144.233 port 49715
May 26 07:32:22 instance-1 sshd[20351]: Invalid user nagios from 159.65.144.233 port 49715
May 26 07:32:22 instance-1 sshd[20351]: Invalid user admin from 159.65.144.233 port 49715
May 26 07:32:22 instance-1 sshd[20351]: Invalid user ellen from 159.65.144.233 port 49715
admin
ellen
nagios