Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading