Email notification whenever an user ssh to your Linux machine

TL;DR - Instructions

  1. Install pam_python module. This can be done in ubuntu by "sudo apt-get install libpam-python".
  2. Download the following script (https://gist.github.com/2380454), to a convenient location. I saved it to /lib/security/pam_notify.py
  3. In the file pam_notify.py, modify the variables FROM_ADDRESS and TO_ADDRESS.
  4. Add the following line to /etc/pam.d/sshd

    session optional pam_python.so /lib/security/pam_notify.py

  5. Done. SSH into your server, and see if you get an email. Check your spam filter, too.

Introduction

For security reasons, you might want to be notified whenever someone logs into your server. I've asked the following question - http://serverfault.com/questions/375558/how-to-email-notify-admin-when-users-log-in-to-the-linux-server, and I was referred to a C PAM module to do the job. I couldn't get the module to work for some reason. I wasn't feeling to happy to debug C code to figure out what's going on under the scene, so I re-wrote it as a python script.

Explanation

We're using the following technologies

  • Pluggable Authentication Module (PAM)
  • pam_python
  • Python
  1. PAM gives you fine-grained control over the authentication system in an *nix environment. For our use, we're adding the logic to send email whenever a ssh session is created.
  2. PAM modules need to be compiled into *.so, native shared library object. Which is annoying for debugging and development, because it means that the PAM modules need to be written in C, and need to be compiled. However, the library pam_python provides a bridge between PAM modules and python scripts, allowing you to write them in Python.
  3. pam_notify.py is our little nifty script to send email notifications.
  4. Finally, the PAM module needs to be configured into the machine. All the PAM configuration files are stored in the directory /etc/pam.d/. The line "session optional pam_python.so /lib/security/pam_notify.py" in /etc/pam.d/sshd configures PAM to call the python script whenever a ssh session is created.
This entry was posted in Uncategorized. Bookmark the permalink.
  • 4430salton

    I am running Centos 6.2 and the libpam-python is not able to install because it is not available, is this only for Ubuntu?

  • Freddy

    Hi, thanks for the script but it is not working for me. I get an error 'ImportError: No module named _socket' whenever I log in. This module is loaded by the module socket. Trying to import syslog or logging results in ImportError: No module found as well. Running the script in the bash works very well and all imports are resolved. What can I do to make the script find the modules? Thanks