【问题标题】:Using an expect Script to send the output of a command and store in a file使用期望脚本发送命令的输出并存储在文件中
【发布时间】:2016-02-06 06:06:20
【问题描述】:

您好,我正在尝试将通过 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

我收到了错误

期望:生成 id exp6 未打开 在执行时 “期望”mininet@mininet-vm:*“”

请任何人帮助我处理此代码。

【问题讨论】:

  • 你拼错了“assword:”吗?或者这是正确的?
  • 嗨 e0k 没关系,这是正确的。

标签: buffer expect out spawn


【解决方案1】:

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

一种方法是使用 'quoted' 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就像一个单引号字符串,而expect的变量留给expect处理。

您还可以研究 expect log_file 命令:您可以随意启用和禁用日志记录,就像您在此处手动执行的操作一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2019-11-17
    • 2016-09-06
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多