Trying to run a sudo command from script

Steve Holden steve at
Sat Jan 2 14:08:12 CET 2010

Paul Kölle wrote:
> 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.
[please put your answers *after* the questions!]

I don't think it so much that you can't catch stdout. Rather, sudo
ensures it is talking to the user by explicitly reading the password
from /dev/tty. Consequently there is no way to send the password value
over the process's stdin, hence the need to use pexpect.

Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010
Holden Web LLC       

More information about the Python-list mailing list