Sitemap

Our best price of the year.

Get 20% off new memberships for a limited time.now.
Press enter or click to view image in full size

Stop Intruders in Their Tracks: Get an Email Every Time Someone Logs In via SSH

2 min readOct 9, 2025

--

Ever wondered who’s logging into your Linux box? Whether it’s a critical production server or a personal VPS, it’s smart to get notified the moment someone connects over SSH. Here’s how to make your system send you an automatic email alert whenever a login occurs — no heavy monitoring tools needed.

Create the Notification Script

We’ll use a short Bash script that gathers the username, IP, hostname, and login time, then sends it via email.

#!/bin/bash
# /usr/local/bin/notify_login.sh

user="$PAM_USER"
host="$(hostname)"
ip="$PAM_RHOST"
time="$(date '+%Y-%m-%d %H:%M:%S')"

echo "SSH login on $host by $user from $ip at $time" | \
mail -s "SSH login alert: $user@$host" admin@example.com

Make it executable:

chmod +x /usr/local/bin/notify_login.sh

Hook It Into SSH

Add a PAM execution rule so the script runs automatically when a user logs in. Edit /etc/pam.d/sshd and add this at the end

session optional pam_exec.so /usr/local/bin/notify_login.sh

This tells PAM (Pluggable Authentication Module) to execute your script on every SSH session start.

--

--

Konstantinos Patronas

Written by Konstantinos Patronas

DevOps engineer, loves Linux, Python, cats and Rock music

No responses yet