Pushbullet is a service that allows you to push notifications to your devices. We will be using it to send us a notification any-time somebody successfully connects to our server with ssh.

The cleanest way to run a script when on ssh logins is through PAM. PAM or "Pluggable Authentication Module" is a library called by all the authentication related functions in Linux that provides a way to hook into the authentication process.

The pam_exec module gives us easy access to this system. It allows us to run scripts to react to events like user logins.

Save this script to /opt/ssh_notify/notify.sh. The script uses the Pushbullet API to send a notification to your phone with the username and IP address for the user that has just signed on.

#!/bin/bash

PB_TOKEN="------REPLACE-ME-----------------"

if [[ "${PAM_TYPE}" == "open_session" ]]; then
    PAYLOAD=$(printf '{
            "title": "New shh connection",
            "body": "User <%s>, from %s successfully connected at %s to %s.",
            "type": "note"
        }' "${PAM_USER}" "${PAM_RHOST}" "$(date +%H:%M)" "$(hostname)" \
    )

    curl --header "Access-Token: ${PB_TOKEN}" \
         --header 'Content-Type: application/json' \
         --data-binary "${PAYLOAD}" \
         --request POST https://api.pushbullet.com/v2/pushes
fi

Before you can start sending notifications you need to retrieve and API access token from the Pushbullet website. Go to your profile and click on CreateAccessToken. Copy the token into the space marked PB_TOKEN in the script.

Now we need to tell pam about our script. Add the following line to the end of /etc/pam.d/sshd:

session optional pam_exec.so /opt/ssh_notify/notify.sh

To test your changes open a new terminal and ssh into your machine. You should receive a notification.

The pam_exec environment exposes several other variables that you can use to build a more descriptive message. You can check out the complete list here.