Trying to run a sudo command from script
ktenney at gmail.com
Sun Jan 3 15:05:44 CET 2010
On Fri, Jan 1, 2010 at 5:08 PM, Diez B. Roggisch <deets at nospam.web.de> wrote:
> Kent Tenney schrieb:
>> 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(),
>> 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
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 "):
if not password:
password = getpass.getpass(prompt)
command = "sudo " + command
child = pexpect.spawn(command)
# is this necessary?
More information about the Python-list