Using an expect Script to send the output of a command and store in a file
Asked Answered
L

1

1

Hi I am trying to store the output of a command run through a spawn ssh remote window into my local host, I am new to expect and am not able to figure out where I am wrong. My Code:

#!/bin/bash

while read line
do
        /usr/bin/expect <<EOD
        spawn ssh mininet@$line
        expect "assword:"
        send -- "mininet\r"
        set output [open "outputfile.txt" "a+"]
        expect  "mininet@mininet-vm:*"
        send -- "ls\r"
        set outcome $expect_out(buffer)
        send "\r"
        puts $output "$outcome"
        close $output
        expect  "mininet@mininet-vm:*"
        send -- "exit\r"
        interact
        expect eof
EOD
done <read_ip.txt

I am getting the error

expect: spawn id exp6 not open
    while executing
"expect  "mininet@mininet-vm:*""

Please can any body help me on this code.

Lamontlamontagne answered 6/2, 2016 at 6:6 Comment(2)
Did you misspell "assword:"? Or is this correct?Deuno
Hi e0k It doesn't matters, It is correct.Lamontlamontagne
H
2

You have your expect program in a shell heredoc. The shell will expand variables in the heredoc before launching expect. You have to protect expect's variables from the shell.

One way is to use a 'quoted' heredoc, and pass the shell variable to expect through the environment:

#!/bin/bash
export host                            ## an environment variable
while read host
do
    /usr/bin/expect <<'EOD'            ## note the quotes here
        spawn ssh mininet@$env(host)   ## get the value from the environment
        expect "assword:"
        send -- "mininet\r"
        set output [open "outputfile.txt" "a+"]
        expect  "mininet@mininet-vm:*"
        send -- "ls\r"
        set outcome $expect_out(buffer)
        send "\r"
        puts $output "$outcome"
        close $output
        expect  "mininet@mininet-vm:*"
        send -- "exit\r"
        expect eof                 ## don't want both "interact" and "expect eof"
EOD
done <read_ip.txt

Putting single quotes around the heredoc terminator means the whole heredoc acts like a single quoted string, and expect's variables are left for expect to handle.

You might also investigate the expect log_file command: you can enable and disable logging at will, much as you are doing manually here.

Heron answered 7/2, 2016 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.