Using pexpect with 'sudo'

dwelch91 at dwelch91 at
Tue Oct 17 21:32:24 CEST 2006

I'm having a problem using pexpect with 'sudo' on Ubuntu 6.06 (Dapper).
Here's the program:

#!/usr/bin/env python
import pexpect
import sys

child = pexpect.spawn("sudo apt-get update")
child.logfile = sys.stdout

    i = child.expect(["Password:", pexpect.EOF, pexpect.TIMEOUT])

    if i == 0:
        print "****************************** sending password"
        child.sendline("XXX") # Not my real sudo password
    elif i == 1:
        print "EOF"

    elif i == 2:
        print "TIMEOUT"

except Exception:
    print "Exception"

The strange thing is that this script runs with no problems (downloads
the repository updates), even though it should fail. It never prints
the "****************************** sending password" line, and even if
it did write the password to the process, it isn't the correct
password. I've done this after a 'sudo -k' to clear the sudo password,
and if I run 'sudo apt-get update' from the command line manually, it
asks for the password every time.

I I change the spawn to:

child = pexpect.spawn("sudo -u <my user name here> apt-get update")

it fails with:

E: Could not open lock file /var/lib/apt/lists/lock - open (13
Permission denied)
E: Unable to lock the list directory

which is expected.

If I'm not going crazy, this seems like a security hole that allows a
user to run any system command without a superuser password.

Any ideas?



More information about the Python-list mailing list