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.

e0k
  • 6,961
  • 2
  • 23
  • 30

1 Answers1

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352