linux - 当期望脚本内容通过管道输入时,"interact"不起作用

标签 linux shell expect

我正在构建一个简单的 ssh 登录包装工具,以帮助自动登录到众多服务器之一。
它首先从用户输入中获取描述,然后提取安全存储在某处的相应(最相关的)服务器 IP 和密码,并使用它创建一段预期脚本。

expect 脚本看起来像这样:

    spawn ssh2 -q -t [email protected]
    expect {
        "assword:" {send "Bob123\r"}
    }
    interact

当我通过管道将其传递给期望时(期望可以从标准输入读取脚本)一切 进展顺利,直到达到“互动”。 Expect 声称它收到 eof 和 立即终止。然后我将其存储到一个文件中,说 tmp.exp 同样的问题 当我执行“expect < tmp.exp”时会发生。但是,当我执行“expect -f tmp.exp”时 一切都好。

我认为原因是“interact”从 fd0 获取输入,该输入被我的程序(或 shell)重定向到管道。 这是否意味着我不能使用交互 像“期望< xx.exp”之类的东西? 有没有办法在“interact”命令之前将 fd0 恢复到真实终端? 我用谷歌搜索了很多,得到的只是“close_on_eof 0”之类的东西。我找不到它的意义,也不知道它是如何工作的。提前致谢!

最佳答案

我只是想出了一个方法来做到这一点。请参阅此示例:

$ cat foo.exp
if {[catch {
    #  Close stdin and reopen it as /dev/tty. Then we are
    #+ connecting to a tty.
    close stdin
    open /dev/tty
} err]} {
    puts stderr $err
    exit 1
}

# Without this, inputed lines will be echo'ed twice.
set stty_init -echo
spawn bash --noprofile --norc

expect -re {bash-[.0-9]+(#|\$) }
interact

exit
$ expect < foo.exp
spawn bash --noprofile --norc
bash-4.2# ptree $$
705   screen -T dtterm -U
  24164 bash
    26826 expect
      26827 bash --noprofile --norc
        26830 ptree 26827
bash-4.2# exit
exit
$

为了使其更智能,我们需要在开始时检查 stdin 是否为 tty。

关于linux - 当期望脚本内容通过管道输入时,"interact"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341388/

相关文章:

linux - SonarQube 返回错误的网关错误

python - 从脚本运行交互式 Python 控制台的键盘快捷键损坏

colors - Expect shell 中的彩色文本

c - sigaddset 有什么用?

linux - 如何在 shell 脚本中保存 "read "错误输出?

bash - 如何使用 shell 命令运行 tmux

linux - "expect"可能只回答一些问题?

php - 安装 PHP 期望扩展时出错

linux - Linux 64 位上的 SQLITE_NOMEM 错误

shell - chmod: ‘og=’ 之后缺少操作数 Gitlab CI/CD executor=shell