Monitoring SSH connections to a Linux Server

If you have an internet-facing server, and that despite applying all the patches, securing everything, you want to keep an eye on your server activity and you want to be notified when someone is logging-in with SSH, here is a small and efficient trick !

The idea is to call a script every time an SSH session is opened. Within your script, you can decide what kind of notification you want: mail, telegram, push notification ( is a good option) …

Step 1 – edit /etc/pam.d/sshd

At the end of the PAM configuration file, add the following line:

# Notify at connection
session optional /data/admin/scripts/

At every SSH connection, PAM will call your script, and pass some environment variables. be sure that your script can be called by the user running SSH. According to the documentation, PAM_EXEC will “Per default will execute the external command with the real user ID of the
calling process. Specifying this option means the command is run with the effective
user ID.”

Step 2 – create your notification script

As per the documentation, the script will be called for all events: successful and non-successful ! If you want to filter on success events only, use the environment variable PAM_TYPE.

I do personally use simple mail notifications for this purpose:


if [ "${PAM_TYPE}" != "open_session" ]; then


CONTENT="A User has logged in.\n\nUser: ${PAM_USER}\nOrigin: ${PAM_RHOST}"

echo -e "To: ${TO}\nFrom: ${FROM}\nSubject: ${SUBJECT}\n${CONTENT}" | ssmtp ${TO}