I wanted to send an email email to myself whenever a user logs into my raspberry via SSH. These instructions will work for ubuntu as well.

Send an email notification when a user logs into your raspberry pi via SSH

Zahir Jacobs
Nov 6 · 2 min read
Photo by Sai Kiran Anagani on Unsplash

First thing I had to do was set up my raspi to send email via gmail

Install ssmtp and and mailutils

# sudo apt install sstp mailutils

Configure your gmail account details

I’m using the nanotext editor.

# sudo nano /etc/ssmtp/ssmtp.conf

Update the ssmtp.conf like so:

root=postmaster
mailhub=smtp.gmail.com:587
hostname=raspberrypi
AuthUser=<your gmail email address>
AuthPass=<your password here>
UseSTARTTLS=YES

Enable Less Secure App access to your gmail account.

Log into your gmail account and go to

https://myaccount.google.com/lesssecureapps?utm_source=google-account&utm_medium=web

Make sure to enable Less secure app access.

Let’s test sending an email from the command line

echo "This is a test body" | mail -s "test subject" test@test.com

If all went well you should receive a test email at the destination address. You may have to wait a few minutes for Less secure app access to be enabled.

Once you get the email you can execute the send email command in the background by appending the & symbol after the command forcing execution to the background. Like so

echo "This is a test body" | mail -s "test subject" test@test.com &

Forcing it to the background will eliminate a noticeable delay when you do this at the login prompt.

Next I configured the sshrc file to execute some code when the user logs in

Note this file is like abashrc file which is executed when the user logs into a shell.

# sudo nano /etc/ssh/sshrc

Edit the file like so

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
logger -t ssh-wrapper $USER login from $ip
echo "$USER - $ip" | mail -s "SECURITY ALERT: $USER has logged in from $ip" <your email here> &

Here the environment variable $SSH_CONNECTION contains information about the IP address of the logged in user. We use the cut command to print selected parts of this string and load it into the variable ip

We then create a system log entry, and finally we send the email. Note the & character at the end of the command.

Zahir Jacobs

Written by

Fmr Quality Controller now living in South Africa. I like piña coladas, running in the rain and stacking the odds in my favour.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade