Email notification for SSH logins

On servers I maintain I usually have a script running that sends an email whenever someone logs in via SSH. It allows me to keep track on whether something fishy is going on in a very easy way.

It’s not bulletproof but at least provides me with a certain level of safety that everything is all right.

The other day I had to reinstall a server after some time and of course I had to – again – search for how to set that email script up.

So here’s the instructions:

Create the executable that will send the email

First we need a script that will send the email. Take this as a template:

Store this file wherever you like, I put it into /etc/pam_scripts/ but it is really irrelevant where it is.

The variables PAM_USER, PAM_RHOST and PAM_TYPE will be replaced by the PAM system. A tad more on that shortly.

Next we need to make this script executable by running something along the line of sudo chmod 755 /etc/pam_scripts/

Execute the script on SSH-Login

To execute this script now on login I added it to the servers PAM-scripts. The Pluggable Authentication Modules allow for each service to have files executed. SO for SSH there usually is a file /etc/pam.d/sshd that contains a log of information.

The for me interesting part is that I can add this at the end:

Save this file and on the next login via SSH on the machine you should receive an email.

That is: When your email system on the machine is set up properly…