Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a root command with Pexpect?

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: ')
child.sendline('mypassword')

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

UPDATE:

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.sendline('mypass')
child.expect_exact('Do you want to continue? [Y/n] ')
child.sendline('Y')

SOLVED:

I needed to add this line at the end.

child.expect(pexpect.EOF, timeout=None)
like image 973
user2631279 Avatar asked Dec 25 '22 00:12

user2631279


1 Answers

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.

like image 78
Joseph LeClerc Avatar answered Dec 26 '22 12:12

Joseph LeClerc