challenging problem for changing to a dedicated non-privileged user within a script.

paul paul at
Thu Jul 23 15:32:10 CEST 2009

Krishnakant schrieb:
> On Thu, 2009-07-23 at 13:50 +0200, paul wrote:
>> If the user running python program is allowed to call setuid() then yes.
> NO, i don't think i can do that.  I am getting opperation not permitted.
> Any ways I think probably subprocess will have to sort it out.
>> Did you try running "sudo -u postgres blabla" with subprocess?
> Yes, but still not got the intended result which is now obvious.
Why is that obvious? Works for me:

---- ---------

from subprocess import Popen, PIPE

cmd = Popen('sudo -u vboxadd /home/pkoelle/Documents/', 
shell=True, stdout=PIPE, stderr=PIPE)
print "OUT: "
print "ERR: "

---- -----
echo $UID
logger "whoami script called for $UID"

Of course, you need to adapt path and user values to your situation. The 
user you use in your 'sudo -u <user>...' call needs execute permissions 
for The relevant entry in /etc/sudoers:

pkoelle ALL=NOPASSWD: /home/pkoelle/Documents/


PS: This has absolutely nothing to do with "connecting to postgresql". A 
"postgres user" is not a "system user" (Piet already asked the right 
questions here ;)

>>> 2. now execute the python code for connecting to the postgresql
>>> database.
>>> In the second point I actually want to execute python code not shell
>>> level command so will the sudo -u in the subprocess.Popen change the
>>> user in the script?
>> No, as the name "subprocess" suggests you are spawning a new process 
>> which gets another uid through sudo. This does not affect the parent 
>> process.
> Ok then here is the work-around which I am thinking to try, Plese tell
> me if it is correct.
> I will let that subprocess start python inthe background and execute the
> connecting code to postgresql including importing the pygresql library.
> Then I will create the connection and cursor objcts in that subprocess.
> But my concern is, will the connection object in the child process
> (subprocess) be available to the parrent process?
> happy hacking.
> Krishnakant.

More information about the Python-list mailing list