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

筅森魡賤 提交于 2019-12-11 11:14:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35237960/using-an-expect-script-to-send-the-output-of-a-command-and-store-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!