Skip to content

Instantly share code, notes, and snippets.

@mplinuxgeek
Last active February 28, 2023 08:26
Show Gist options
  • Save mplinuxgeek/f08b91d2236b742f19c63579cd727167 to your computer and use it in GitHub Desktop.
Save mplinuxgeek/f08b91d2236b742f19c63579cd727167 to your computer and use it in GitHub Desktop.
Script to check the IP address of the SSH session, if it doesn't match the local subnet an email is sent with details of the session and some details of the IP from whois
#!/bin/bash
# Paste this script into /etc/ssh/sshrc
# This runs everytime an ssh session is initiated.
# The script checkes the remote IP address against the local
# subnet, if the subnet is not in the IP address then an
# email is sent containing details about the session and
# some details from whois about the IP address.
#
# Changes: Initial version, tested on CentOS 7
#
# Todo: Add subnet detection
recipient="[email protected]"
subnet="192.168.1."
# The variable SSH_CONNECTION contains the IP of the remote device
# Extract the IP address of the string using bash parameter expansion
ssh_ip=${SSH_CONNECTION%% *}
red='\033[0;31m'
nc='\033[0m' # No Color
# Check if the SSH sessions IP address is like our subnet, if not send an email with the relevant details
if [[ ! "${ssh_ip}" =~ "${subnet}" ]]; then
# Use the whois tool to get information about the IP address
whois=$(whois ${ssh_ip} | grep -wi 'Name:\|City:\|Country:\|OriginAS:\|NetRange:' | sort -u)
message="User ${USER} logged in from ${ssh_ip} on $(date '+%x %T')\n\nwhois:\n\n${whois}"
#echo -e "${message}" # This is only for diagnostic purposes, if this is uncommented it will print on screen when someone logs in
echo -e "${red}This connection has been logged and the owner of the server notified.${nc}"
echo -e "${message}" | mail -s "External SSH login from ${USER}@${ssh_ip} - $(date '+%x %T')" "${recipient}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment