Skip to main content

Setting Up Email Notifications for Successful SSH Logins

Updated by Tim Rabbetts on
Setting Up Email Alerts for SSH Logins

Setting up email alerts for successful SSH logins can greatly enhance the security monitoring of your server. This guide will help you configure your server to send you an email every time someone logs in via SSH.

Requirements

  • A server with SSH access
  • Root or sudo privileges
  • Mail sending capabilities (e.g., sendmail or postfix)

Steps to Configure Email Alerts

1. Install Sendmail/Postfix

If not already installed, you need a mail server software like 'sendmail' or 'postfix'.

        sudo apt install sendmail
        sudo sendmailconfig  # Follow the prompts
    

2. Configure SSHD

Edit the SSH daemon’s configuration file to execute a command when a user logs in.

        sudo nano /etc/ssh/sshd_config
    

Scroll to the end of the file and add or uncomment the following line:

        ForceCommand /path/to/login-notification.sh
    

3. Create the Notification Script

Create a script that sends an email when someone logs in:

        sudo nano /path/to/login-notification.sh
    
    

Add the following script, replacing 'you@example.com' with your email address:

#!/bin/bash
# Send SSH Login Notification Email
EMAIL="you@example.com"
HOSTNAME=`hostname`
IP=`echo $SSH_CONNECTION | cut -d " " -f 1`
DATE=`date "+%Y-%m-%d %H:%M:%S"`
mail -s "SSH Login: $HOSTNAME" $EMAIL 

Make the script executable:

        sudo chmod +x /path/to/login-notification.sh
    

4. Restart the SSH Service

Finally, restart the SSH service to apply the changes:

        sudo service ssh restart
    

Conclusion

Once these steps are completed, every time a user logs into your server via SSH, you will receive an email notification. This setup can help you monitor access and ensure security compliance on your server.

Add new comment