2

I've tried using some bash commands in an expect script before spawning anything, and this doesn't seem to work:

#!/usr/bin/expect

sudo ifdown usb0
sudo ifup usb0

expect "[sudo] password for stud:"
send "FirstPassword\r"

spawn ssh root@10.9.8.2
expect "root@10.9.8.2's password:"
send "SecondPassword\r"

expect eof

I've tried running this with the first part of the script commented out (because it's not neccesary to do this check 100% of the time, just better), but in that case I enter the device, and literally can't do anything there. I'd like to ifdown ifup, enter pass, ssh, enter pass, and scope to that shell.

2 Answers 2

3

Nope. you can't expect to run bash commands in an expect interpreter, just like you can't run perl commands in a python interpreter -- they're different languages. If you want to run some bash commands that require user interaction (sudo), then you have to spawn bash

set prompt {\$ $}    ; # this is a regular expression that should match the
                       # *end* of you bash prompt. Alter it as required.
spawn bash
expect -re $prompt

send "sudo ifdown usb0\r"
expect {
    "[sudo] password for stud:" {
        send "FirstPassword\r"
        exp_continue
    }
    -re $prompt
}
send "sudo ifup usb0\r"
expect -re $prompt

send "ssh root@10.9.8.2\r"
expect "root@10.9.8.2's password:"
send "SecondPassword\r"
expect eof
0

If the command you want to run inside an expect script is supposed to generate some output that you want to consume inside the script then consider running your command outside the script and then passing whatever value you need as a parameter.

An example for openvpn that requires an OTP token as a parameter:

autovpn.exp

#!/usr/bin/expect -f

set OTP_CODE [lindex $argv 0]

set timeout -1

spawn sudo openvpn --config my_vpn_profile.ovpn

expect "Enter Auth Username:"
send -- "myuser\r"

expect "Enter Auth Password:"
send -- "mysecret\r"

expect "CHALLENGE: Enter Authenticator Code"
send -- "$OTP_CODE\r"
expect_background

Now you can run the expect script passing the opt code as first argument:

./autovpn.exp $(oathtool -b --totp 'my_otp_seed_ABCDEFGH')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.