使用expect脚本发送命令的输出并存储在文件中

时间:2016-02-06 06:06:21

标签: buffer expect out spawn

您好我正在尝试将通过spawn ssh远程窗口运行的命令的输出存储到我的本地主机中,我是新来的,我无法弄清楚我错在哪里。 我的代码:

#!/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

我收到错误

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

任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

你有一个shell heredoc你期望的程序。 shell将在启动expect之前扩展heredoc 中的变量。你必须从shell中保护expect的变量。

一种方法是使用'引用'heredoc,并传递shell变量以期望通过环境:

#!/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

在heredoc终止符周围加上单引号意味着整个heredoc就像一个单引号字符串,并且期望的变量留给期望处理。

您还可以调查期望log_file命令:您可以随意启用和禁用日志记录,就像您在此处手动执行一样。