1

I need to send notifications about new ssh connections.

I was able to implement this through the sh script. But it is difficult to maintain, I would like to use a python script instead.

notify-lo.py

#!/usr/bin/env python3

....
....

I made the script an executable file.

chmod +x notify-lo.py

I added my script call to the pam_exec module calls.

session    optional     pam_exec.so  /usr/local/bin/notify-lo.py

Is it even possible to implement this? Will I be able to have access from my script to variables such as $PAM_TYPE, $PAM_SERVICE, $PAM_RUSER and others?

UPDATE.

An example of what my shell script is doing now (I want to replace it with python).

#!/bin/bash

TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ID="xxxxxxxxxxxxxx"
URL="https://api.telegram.org/bot$TOKEN/sendMessage"

if [ "$PAM_TYPE" != "open_session" ]
then
    exit 0
else
    curl -s -X POST $URL -d chat_id=$ID -d text="$(echo -e "Host: `hostname`\nUser: $PAM_USER\nHost: $PAM_RHOST")" > /dev/null 2>&1
    exit 0
fi
Santa Monica
  • 332
  • 3
  • 11
  • Can you provide an example of a shell script (including the dialect/shell) that implements what you're trying to achieve? Why do you ask if it is "event possible to implement", if you already did it? – Ulrich Eckhardt Dec 03 '22 at 16:25
  • @UlrichEckhardt Updated the question. The script will become more complicated. I need 3 notification steps. Writing to a local database, sending an email, sending a telegram message. – Santa Monica Dec 03 '22 at 16:29

1 Answers1

3

These variables that are available to the shell script are called environment variables and are separate from Python variables. To get environment variables in python, you need to use the os.environ dictionary. You can do it like this:

import os


pam_type = os.environ['PAM_TYPE']
print(pam_type)

pam_service = os.environ['PAM_SERVICE']
print(pam_service)

pam_ruser = os.environ['PAM_RUSER']
print(pam_ruser)

Note that you need to remove the leading dollar sign ($)

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • The [first answer](https://stackoverflow.com/questions/53820496/using-my-own-python-script-to-authenticate-into-my-computer) in this question says that I can't use a python script and a PAM module together. [Here](https://man7.org/linux/man-pages/man8/pam_exec.8.html) we are clearly given to understand that pam_exec is a PAM module. Could you please clarify. – Santa Monica Dec 03 '22 at 16:37
  • @SantaMonica Sorry, but I don't know too much about PAM. Your original question was about accessing variables available to shell scripts in Python. If you're having additional troubles with PAM, then I'd suggest asking another question specifically about that on this site. – Michael M. Dec 03 '22 at 16:42