Let’s look at how to send an email notification when logging into a Linux server remotely via SSH. We’ll use postfix to send email alerts and the Gmail SMTP server as a relay host.
Install the following packages on your Linux host:
- Ubuntu/Debian:
sudo apt-get install postfix mailutils -y
- RHEL/Rocky Linux/CentOS/Oracle Linux:
dnf install postfix mailx
When you install postfix, select Internet site mode and specify the FQDN of your host.
We will use the Gmail SMTP server to send emails. In order to authenticate to SMTP, you need to create an App password under https://myaccount.google.com/ -> Security -> App password -> Select Mail app.
Create a password file:
sudo nano /etc/postfix/sasl_passwd
Add here the Gmail email address and the app password that was generated for you:
[smtp.gmail.com]:587 youruser@gmail.com:mhlmswvnswvnzkya
To make the file accessible only to the root user, change the permissions:
sudo chmod 600 /etc/postfix/sasl_passwd
Compile the contents of the sasl_passwd file:
sudo postmap /etc/postfix/sasl_passwd
Then open the postfix config file:
sudo nano /etc/postfix/main.cf
Change the value of the relayhost parameter:
relayhost = [smtp.gmail.com]:587
Add the following lines:
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
Restart the postfix daemon and add it to startup:
sudo systemctl restart postfix
sudo systemctl enable postfix
Open the /etc/profile file:
sudo nano /etc/profile
Add the following lines:
if [ -n "$SSH_CLIENT" ]; then
TEXT="$(date): ssh login to ${USER}@$(hostname -f)"
TEXT="$TEXT from $(echo $SSH_CLIENT|awk '{print $1}')"
echo $TEXT|mail -s "Alert SSH login" admin_alert@mail.com
fi
Log out and reconnect to the Linux host via SSH. A notification of the remote connection should be sent to the specified email address. It will contain the user name and IP address from which the connection was made.