Last active
August 16, 2018 00:57
-
-
Save mplinuxgeek/fc2c6984025523db1a1be0dc26e21d5e to your computer and use it in GitHub Desktop.
Bash script to check for failed ssh logins and email a report.
This file contains hidden or 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
#!/bin/bash | |
# Script requirements lastb, diff, touch, whois, mail. | |
# To succesfully send an email it will require a working mail configuration | |
# Tested on Ubuntu 16.04 | |
recipient="[email protected]" | |
if [ ! -f /root/failed ]; then | |
touch /root/failed | |
fi | |
lastb > /root/failed.new | |
DIFF=$(diff --changed-group-format="%>" --unchanged-group-format="" /root/failed /root/failed.new) | |
if [ ! -z "${DIFF}" ]; then | |
message+="$(date '+%x %T') Found failed login attempt(s)\n" | |
echo -ne "${message}" | |
while read -r line; do | |
if [ ! -z "${line}" ]; then | |
lastb=($(echo "${line}")) | |
echo " Looking up ${lastb[2]}..." | |
whois=$(whois "${lastb[2]}") | |
message+="Failed login from ${lastb[0]}@${lastb[2]}\n\n" | |
message+="lastb entries:\n${line}\n\n" | |
message+="whois entry:\n${whois}\n" | |
message+="---------------------------------------------------------------------------------------------------------------------------------\n\n" | |
fi | |
done <<< "$DIFF" | |
cp -f /root/failed.new /root/failed | |
fi | |
if [ ! -z "${message}" ]; then | |
echo " Sending email to ${recipient}..." | |
echo -e "${message}" | mail -s "Failed login attempt $(date '+%x %T')" "${recipient}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment