Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect script return value

I'm including simple Expect commands within a Bash script (I know I could be just writing a pure Expect script, but I would like to get it to work from within Bash).

The script is below:

#!/bin/bash

OUTPUT=$(expect -c '
spawn ssh [email protected]
expect "password:"
send "dog\r"
')

Upon ssh'ing to the above address, it will return something of the form mihail911's password: on the prompt, so I think my expect line is valid.

When I run this my script does not print anything. It does not even show the password: prompt. In general, even if I manually provide an incorrect password, I will receive a Incorrect password-type response prompt. Why is nothing printing and how can I get my script to execute properly?

I have tried debugging by using the -d flag and it seems to show that at least the first expect prompt is being matched properly.

In addition, what values should I expect in the OUTPUT variable? When I echo this variable, it simply prints the first the first command of the expect portion of the script and then mihail911's password:. Is this what it's supposed to be printing?

like image 635
MEric Avatar asked Aug 29 '26 15:08

MEric


1 Answers

Use:

#!/bin/bash
OUTPUT=$(expect -c '
    # To suppress any other form of output generated by spawned process
    log_user 0
    spawn ssh [email protected]
    # To match some common prompts. Update it as per your needs.
    # To match literal dollar, it is escaped with backslash
    set prompt "#|>|\\$"
    expect {
        eof     {puts "Connection rejected by the host"; exit 0}
        timeout {puts "Unable to access the host"; exit 0;}
        "password:"
    }
    send "root\r"
    expect {
        timeout {puts "Unable to access the host"; exit 0;}
        -re $prompt
    }
    send "date\r"
    # Matching only the date cmd output alone
    expect {
        timeout { puts "Unable to access the host";exit 0}
        -re "\n(\[^\r]*)\r"
    }
    send_user "$expect_out(1,string)\n"
    exit 1
')
echo "Expect's return value: $?"; # Printing value returned from 'Expect'
echo "Expect Output: $OUTPUT"

Output:

dinesh@MyPC:~/stackoverflow$ ./Meric
Expect's return value: 1
Expect Output: Wed Sep  2 09:35:14 IST 2015
dinesh@MyPC:~/stackoverflow$
like image 183
Dinesh Avatar answered Aug 31 '26 06:08

Dinesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!