Automate SSH Login Notification via Email

You can enhance your system’s security by setting up an automated email notification whenever someone logs in via SSH. This can help you stay informed about unauthorized access to your system. Below is a guide on how to implement this feature.

Note: This guide assumes you have administrative access to your system and are familiar with basic Linux commands.

1. Edit /etc/profile

First, open the /etc/profile file in a text editor as the root user:

1
sudo nano /etc/profile

2. Add the Following Script

Copy and paste the following script to the end of the /etc/profile file. This script retrieves the IP address, hostname, and timestamp of the login session and sends an email notification using mailx.

1
2
3
4
5
6
7
8
# Send email when someone logs in via SSH
if [ -n "$SSH_CONNECTION" ]; then
    IP="$(echo $SSH_CONNECTION | cut -d " " -f 1)"
    HOSTNAME=$(hostname)
    NOW=$(date +"%e %b %Y, %a %r")

    echo 'Someone from '$IP' logged into '$HOSTNAME' on '$NOW'.' | mailx -s 'SSH Login Notification' -r '[email protected]' '[email protected]'
fi

Make sure to replace '[email protected]' with your actual sender email address and '[email protected]' with the email address where you want to receive notifications.

3. Save and Exit

Save the changes and exit the text editor.

  • In Nano, press Ctrl + O to save the file, then Enter, and finally Ctrl + X to exit.

4. Test SSH Login

Now, you can test the SSH login notification by connecting to your server via SSH. After successfully logging in, you should receive an email notification at the specified email address.

Note: Ensure that your system is properly configured to send emails. You may need to install and configure a mail server or use a third-party SMTP server for this to work.

By following these steps, you will receive automated email notifications whenever someone logs in via SSH, helping you monitor your system’s security more effectively.

0%