Created
April 17, 2023 14:56
-
-
Save bagaag/228fbd4478d73bceeb8ab4ce38907dad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a quick and dirty script that emails an admin about any new IP addresses found in the auth.log. | |
# It includes the last 10 lines featuring a new IP along with output from ip-api.com. | |
# It saves identified IPs in a text file to prevent repeat reporting. | |
# Set this up to run as a cron job to be notified of any new networks authenticating on your Linux server. | |
import sys | |
import os | |
import subprocess | |
msg_filename = 'monitor_auth.msg' | |
from_email = '[email protected]' | |
to_email = from_email | |
# Create known_ips.txt if needed | |
if not os.path.isfile('known_ips.txt'): | |
subprocess.run("touch known_ips.txt", shell=True) | |
# Collect known IPs | |
known_ips = [] | |
with open('known_ips.txt') as f: | |
lines = f.readlines() | |
for line in lines: | |
ip = line.strip() | |
if not ip in known_ips: | |
known_ips.append(ip) | |
# Process any new IPs | |
result = subprocess.run("grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /var/log/auth.log", shell=True, capture_output=True, text=True) | |
ips = result.stdout.strip().split("\n") | |
msg = '' | |
for ip in ips: | |
if not ip in known_ips: | |
print(ip) | |
result = subprocess.run("grep " + ip + " /var/log/auth.log", shell=True, capture_output=True, text=True) | |
last10 = result.stdout.strip().split("\n")[-10:] | |
result = subprocess.run("curl http://ip-api.com/json/" + ip, shell=True, capture_output=True, text=True) | |
info = result.stdout.strip() | |
msg += '= ' + ip + ' =\n' | |
msg += '\n'.join(last10) + '\n' | |
msg += info + '\n\n' | |
known_ips.append(ip) | |
# Send alert message | |
if msg != '': | |
with open(msg_filename,'w') as f: | |
f.write(msg) | |
subprocess.run('mail -r ' + from_email + ' -s "New IPs Found" ' + to_email + ' < ' + msg_filename, shell=True) | |
os.remove(msg_filename) | |
# Save known IPs | |
with open('known_ips.txt', 'w') as f: | |
for ip in known_ips: | |
f.write(ip + '\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment