How to Automatically Send an Email Alert When a Specific User Logs into Ubuntu via SSH

Monitoring who logs into your Linux server is a critical part of system security. While you can always check the authentication logs manually (/var/log/auth.log), it is much more effective to receive a real-time email notification the moment someone accesses the system.

You can configure Ubuntu to automatically trigger an email alert when a specific user (or any user) successfully logs in via SSH. This is achieved by utilizing the global SSH configuration profile.

Prerequisites

Before proceeding, your Ubuntu server must be capable of sending outgoing emails. You must have an MTA (Mail Transfer Agent) installed and configured, such as postfix, sendmail, or mailutils. Test that your server can send emails before configuring the SSH alert.

How to Configure the Login Alert Script

We will create a simple bash script that triggers upon login and sends the email.

  1. Open your terminal and create a new script file in a secure location: sudo nano /etc/ssh/login-alert.sh
  2. Paste the following code into the script. Be sure to replace [email protected] with your actual email address:
#!/bin/bash
# Get the username of the person logging in
USER=$USER

# Check if the user is the one we want to monitor (e.g., 'root' or 'admin')
if [ "$USER" == "root" ]; then
    # Prepare the email content
    SUBJECT="SSH Login Alert: $USER"
    BODY="User '$USER' has successfully logged into the server via SSH.\n\nDate: $(date)\nIP Address: $SSH_CLIENT"
    
    # Send the email
    echo -e "$BODY" | mail -s "$SUBJECT" [email protected]
fi
  1. Save and exit the file (Press Ctrl+O, Enter, then Ctrl+X).
  2. Make the script executable so the system can run it: sudo chmod +x /etc/ssh/login-alert.sh

How to Trigger the Script on SSH Login

Now that the script is ready, we need to tell the SSH daemon to run it every time a user logs in.

  1. Open the global Bash profile configuration file: sudo nano /etc/profile
  2. Scroll to the very bottom of the file and add the following line: /etc/ssh/login-alert.sh
  3. Save and exit the file.

How It Works

The /etc/profile file is executed every time any user logs into the system via an interactive shell (like SSH). When the user logs in, the profile executes your login-alert.sh script.

The script checks the $USER variable. If it matches “root” (or whichever username you specified in the if statement), it extracts the login timestamp and the source IP address from the $SSH_CLIENT environment variable, formats them into a message, and emails it to you instantly.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.