Monitoring SSH logins is a simple yet powerful way to stay informed about access to your Linux server. Whether you’re managing production infrastructure or personal devices, receiving real-time email alerts for SSH logins can help you detect unauthorised access and maintain better operational visibility. In this guide, we’ll walk through configuring your server to automatically send email notifications whenever a user logs in via SSH, using native tools like Postfix and PAM.
For configuring Postfix to use Gmail as an SMTP relay, you may refer to the following blog. In this article, we’ll focus solely on setting up the script to monitor and send email alerts for SSH logins.
Configuring Postfix notification using Gmail SMTP server.
Let’s create a Bash script that automatically sends an email notification whenever a user accesses the server via SSH.
vi /usr/local/bin/ssh-login-alert.sh
#now add the following content to the file:
~~~
#!/bin/bash
HOSTNAME=$(hostname)
IP=${PAM_RHOST:-$(who | awk '/pts/{print $5}' | tr -d '()' | head -n1)}
USER=${PAM_USER:-$(whoami)}
TIME=$(date '+%Y-%m-%d %H:%M:%S')
echo -e "SSH Login Alert:\nUser: $USER\nIP: $IP\nTime: $TIME\nHost: $HOSTNAME" | mail -s "WARNING: SSH Login on $HOSTNAME from $IP" test@gmail.com
~~~
Ensure that you’ve correctly specified the email subject line and recipient address in the designated sections of the script before deploying it. Also, we need to provide executable permissions for the script:
chmod +x /usr/local/bin/ssh-login-alert.sh
Once the script is prepared and tested, the next step is to integrate it into the PAM configuration to trigger on SSH logins.
vim /etc/pam.d/sshd
#now add the following content on the top of sshd configuration inside pam.d
~~~
session optional pam_exec.so /usr/local/bin/ssh-login-alert.sh
~~~
With the script in place, simply log out and log back in via SSH to verify that the email notification is triggered as expected.