Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine what user and group a Python script is running as?

I have a CGI script that is getting an "IOError: [Errno 13] Permission denied" error in the stack trace in the web server's error log.

As part of debugging this problem, I'd like to add a little bit of code to the script to print the user and (especially) group that the script is running as, into the error log (presumably STDERR).

I know I can just print the values to sys.stderr, but how do I figure out what user and group the script is running as?

(I'm particularly interested in the group, so the $USER environment variable won't help; the CGI script has the setgid bit set so it should be running as group "list" instead of the web server's "www-data" - but I need code to see if that's actually happening.)

like image 506
Chirael Avatar asked Jun 15 '10 03:06

Chirael


People also ask

How do you check which specific processes Python scripts are running?

I usually use ps -fA | grep python to see what processes are running. The CMD will show you what python scripts you have running, although it won't give you the directory of the script.

How do I run a Python script as a different user?

Use the command sudo . In order to run a program as a user, the system must "authenticate" that user. Obviously, root can run any program as any user, and any user can su to another user with a password. The program sudo can be configured to allow a group of users to sudo a particular command as a particular user.


2 Answers

import os, getpass print getpass.getuser() 

Consider the following script.

---- foo.py ----  import os, getpass print "Env thinks the user is [%s]" % (os.getlogin()); print "Effective user is [%s]" % (getpass.getuser()); 

Consider running the script.

$ python ./foo.py 

results in

Env thinks the user is [jds] Effective user is [jds] 

now run

$ sudo -u apache python ./foo.py 

results in

Env thinks the user is [jds] Effective user is [apache] 

As you can see, you these 2 calls os.getlogin() and getpass.getuser() are not the same thing. The underlying principle is how linux/and other unix's manages the running user.

Consider

$ id -u 

1000

vs the effective id of the running process.

$ sudo -u apache id -u 

33

Note: this is exactly what web servers are doing when they start up. They are creating a sandbox (by forking/divorcing the psudo terminal etc), and running as another user. For an in-depth account of what is going on here: see the chapter on 'daemon processes' in the Advanced Programming in the UNIX environment book.

Another good thread on the subject.

like image 119
Jeff Sheffield Avatar answered Sep 29 '22 09:09

Jeff Sheffield


You can use the following piece of code:

import os print(os.getegid()) 
like image 43
Peter Lyons Avatar answered Sep 29 '22 10:09

Peter Lyons