Calling Bash Command From Python

Wildman best_lay at yahoo.com
Mon Oct 31 14:20:27 EDT 2016


On Mon, 31 Oct 2016 11:55:26 -0500, Wildman wrote:

> On Mon, 31 Oct 2016 11:05:23 -0400, Random832 wrote:
> 
>> On Mon, Oct 31, 2016, at 10:55, Wildman via Python-list wrote:
>>> I have code using that approach but I am trying to save myself
>>> from having to parse the entire shadow file.  Grep will do it
>>> for me if I can get code right.
>> 
>> Python already has built-in functions to parse the shadow file.
>> 
>> https://docs.python.org/3/library/spwd.html#module-spwd
> 
> I didn't know about that module.  Thanks, this can simplify
> things for me.
> 
>> But you can't use sudo this way if you use that. But why do you want to
>> use sudo from within the python script instead of just running the
>> python script with sudo?
> 
> In view of the module I just learned about, that would be
> a better approach.

I made a ‭discovery that I thought I would share.  When using
sudo to run the script the environment variable $USER will
always return 'root'.  Not what I wanted.  But this will
work:

user = os.environ["SUDO_USER"]
shadow = spwd.getspnam(user)

That will return the actual user name that invoked sudo.

-- 
<Wildman> GNU/Linux user #557453
The cow died so I don't need your bull!



More information about the Python-list mailing list