r15
r15

Reputation: 496

am I required to use spawn when using expect?

I am creating a simple automated script. here is the code

#!/bin/sh    
echo "testing expect"    
/usr/bin/expect <<delim  
    expect "password for teamer:"
    send "itsme\r"      
    expect eof
delim    
sudo apt-get update

I refer to various documents and blogs they are using spawn. So I have question: is it necessary to use spawn every time? I am executing the update on my local machine.

Not using spawn I get this error:

send: spawn id exp0 not open while executing

or am I missing something?

Upvotes: 3

Views: 4562

Answers (1)

glenn jackman
glenn jackman

Reputation: 247022

expect's expect command is watching the IO channels of the spawned process waiting for the pattern to specify. If you don't give it something to watch, it will just sit there until it times out and then send the password to nothing.

This is what you need to do:

#!/bin/sh    
echo "testing expect"    
/usr/bin/expect <<delim  
    exp_internal 1            ;# remove this when your satisfied it's working
    spawn sudo apt-get update
    expect "password for teamer:"
    send "itsme\r"      
    expect eof
delim

Be careful that you do not have any leading or trailing whitespace on the line with the heredoc delimiter.

If you don't care that your password is in plain text (you should), you don't need to use expect:

#!/bin/sh    
echo "itsme" | sudo -S apt-get update

What you ought to do is to edit the sudoers file to allow yourself to sudo apt-get without having to supply your password, then:

#!/bin/sh    
sudo apt-get update

Read the sudoers man page on your system.

Upvotes: 2

Related Questions