user2631279 user2631279 - 1 year ago 146
Linux Question

How do i perform a root command with Pexpect and Python?

I'm working on a python program to assist with the apt-get tool. I want to use pexpect to download the chosen package. I believe I'm getting stuck at the child.expect line. It seems to timeout when it comes to that line.

butt = "vlc"
child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect('[sudo] password for user1: ')

This is the log file.

TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0xb5ec558c>
version: 3.2
command: /usr/bin/sudo
args: ['/usr/bin/sudo', 'apt-get', 'install', 'vlc']
searcher: <pexpect.searcher_re object at 0xb565710c>
buffer (last 100 chars): '[sudo] password for user1: '
before (last 100 chars): '[sudo] password for user1: '
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 27641
child_fd: 4
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: <open file '<stdout>', mode 'w' at 0xb74d8078>
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1


The password gets sent just fine. It also expects the next line as well, but then enters "Y" and does nothing.

child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect_exact('[sudo] password for user1: ')
child.expect_exact('Do you want to continue? [Y/n] ')

Answer Source

Try child.expect_exact().

From the docs:

The expect() method waits for the child application to return a given string. The string you specify is a regular expression, so you can match complicated patterns.

It is good practice to use expect() only when the intent is to match a regular expression.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download