Trying to run a sudo command from script

K

Kent Tenney

Howdy,

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)

getting assorted errors with all variations I try.

Googling says use pexpect, but I'd prefer a stdlib solution.

Any help appreciated.

Thanks,
Kent
 
D

Diez B. Roggisch

Kent said:
Howdy,

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)

getting assorted errors with all variations I try.

Googling says use pexpect, but I'd prefer a stdlib solution.

pexpect is pure python, and it's needed. There is no easy way around the
issue, so if you insist on not using pexpect, you re-invent the wheel
and write the exact same code - just more error-prone, because of
wheel-reinvention....

Diez
 
K

Kent Tenney

pexpect is pure python, and it's needed. There is no easy way around the
issue, so if you insist on not using pexpect, you re-invent the wheel and
write the exact same code - just more error-prone, because of
wheel-reinvention....

Indeed, the requirements of this are way more complex than I guessed.
The following seems to work well, took some fiddling with EOF.

def sudo(command, password=None, prompt="Enter password "):

import pexpect

if not password:
import getpass
password = getpass.getpass(prompt)

command = "sudo " + command
child = pexpect.spawn(command)
child.expect(['ssword', pexpect.EOF])
child.sendline(password)
child.expect(pexpect.EOF)
# is this necessary?
child.close()

Thanks,
Kent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top