Notify When SSH connection success

Submitted by editor on Fri, 12/16/2016 - 13:45
Question

How to notify by email, url, SMS ... When SSH connection success ?

Method 1. Call Url

You can use this method to call a Custom php script, Custom module, Databaselog .... for example.

1. Create a script (here, notify_login_url.sh)

#Example 1.
#!/bin/sh
# Configure your Url:
URL="http://www.yoursite.com/yourscript.php?var=1";
wget $URL > /dev/null 2>&1

#Or Example 2.
#!/bin/sh
# Configure your Url:
HOST="`hostname`";
NOW=$(date +"%Y-%m-%d:%H:%M:%S");
URL="http://domain.net/mail/notify.php?c=notifyme&t=Connection/Dis++On:+VPS++$PAM_USER++$PAM_RHOST+on+$HOST++$NOW";
curl $URL &>/dev/null;

 

2. Make the script executable
chmod +x notify_login_url.sh

3. Add the script to /etc/pam.d/sshd
session optional pam_exec.so seteuid /path/to/notify_login_url.sh

NOTE 1 : This will also call on disconnection

NOTE 2 :
Set "optional" If you want to still log in if the execution fails.
CAUTION : Set "required" Only After you made sure that it works and if your are sure about what you are doing . login won't be possible unless the execution of your hook script is successful.

Method 2. Send e-Mail using mailx

1. Create a script (here, notify_login_mailx.sh) and make it make it executable (chmod +x notify_login_mailx.sh).

#!/bin/sh
# Configure your email address:
sender="sender-address@example.com"
recepient="notify-address@example.com"

if [ "$PAM_TYPE" != "close_session" ]; then
    host="`hostname`"
    subject="SSH Login: $PAM_USER from $PAM_RHOST on $host"
    # Message to send, e.g. the current environment variables.
    message="`env`"
    echo "$message" | mailx -s "$subject" "$recepient"
    #OR#echo "$message" | mailx -r "$sender" -s "$subject" "$recepient"
fi

2. Add the script to /etc/pam.d/sshd
session optional pam_exec.so seteuid /path/to/notify_login_mailx.sh

 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.