How do I get variables from a Python script that are visible in the sh script?

Question:

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_USERnHost: $PAM_RHOST")" > /dev/null 2>&1
    exit 0
fi
Asked By: Santa Monica

||

Answers:

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 ($)

Answered By: Michael M.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.