Trying to run a sudo command from script

Paul Kölle paul at subsignal.org
Sat Jan 2 05:13:51 EST 2010


Am 01.01.2010 23:55, schrieb Kent Tenney:
> Howdy,
Hi Kent,

> A script running as a regular user sometimes wants
> to run sudo commands.
>
> It gets the password with getpass.
> pw = getpass.getpass()
>
> I've fiddled a bunch with stuff like
> proc = subprocess.Popen('sudo touch /etc/foo'.split(), stdin=subprocess.PIPE)
> proc.communicate(input=pw)
If you don't use shell=True you have to provide the full path to 
commands (and split command and parameters as you do). So eather of this 
works for me:
p = Popen('/usr/bin/sudo /usr/bin/touch /tmp/foo.txt'.split(), 
stdin=PIPE, stdout=PIPE)

p = Popen('/usr/bin/sudo /usr/bin/touch /tmp/foo2.txt', stdin=PIPE, 
stdout=PIPE, shell=True)

The bad news is: It this gives me a password promt inside the 
interactive interpreter. Seems you can't catch stdout this way.

hth
  Paul

>
> getting assorted errors with all variations I try.
>
> Googling says use pexpect, but I'd prefer a stdlib solution.
>
> Any help appreciated.
>
> Thanks,
> Kent





More information about the Python-list mailing list