【问题标题】:Have remote shell evaluate expressions inside expect ssh script让远程 shell 评估期望 ssh 脚本中的表达式
【发布时间】:2016-06-17 00:11:54
【问题描述】:

我必须使用 expectssh 在远程 shell 上实现自动化(在我的特定情况下,bash shell 在本地和远程)。也就是说,我需要将ssh someuser@example.com "echo This is \$(hostname)" 包装在expect 脚本中。

运行上面的“手动”脚本,我得到了预期的输出:This is example.com,所以$(hostname) 表达式(命令替换)在远程机器上得到评估。

现在我将 ssh-remote-shell 命令包装在 expect 这里文档中:

#/bin/bash

expect <<- DONE
  spawn ssh someuser@example.com "echo This is \\$(hostname)"
DONE

包装后的脚本返回[...] This is localhost。所以$(hostname) 表达式在我的本地机器上被评估,而不是在远程机器上。

我尝试了不同级别的反斜杠转义、单引号和双引号、&lt;&lt;- DONE&lt;&lt; DONE,并将$(hostname) 移动到它自己的expect 变量(即set someCommand "\\$hostname" ,然后引用$someCommand)。但没有任何帮助。

如何让远程 shell 评估 SSH expect 脚本中的 shell 表达式?

【问题讨论】:

  • 这“只是”一个引用问题。使用不插入文档的heredoc形式:expect &lt;&lt;- 'DONE'(引用终止词),其余保持不变。
  • @glennjackman,在我的情况下使用expect &lt;&lt;- 'DONE' 会导致can't read "(hostname)": no such variable while executing "spawn ssh someuser@example.com "echo This is \\$(hostname)""

标签: bash shell ssh expect


【解决方案1】:

你快到了。

#!/bin/bash
expect <<- DONE
 set timeout 120
 spawn ssh dinesh@remote-lab "echo This is \\\$(hostname)"
 expect {
         "password: $" {send "welcome\r";exp_continue}
         eof
 }
DONE

输出:

dinesh@myPC:~/stackoverflow$ ./abdull
spawn ssh dinesh@remote-lab echo This is $(hostname)
dinesh@remote-lab's password: 
This is remote-lab

注意:spawn语句也可以写成

 spawn ssh dinesh@remote-lab {echo This is \$(hostname)}

【讨论】:

  • 您不需要在大括号中转义美元,但您可能希望在 echo 的参数中使用双引号:spawn ssh who@where {echo "this is $(hostname)"}
  • @Dinesh,非常感谢。您的解决方案使我走上了正确的道路。我错过了expect { ... } 部分。
猜你喜欢
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2017-03-26
  • 1970-01-01
相关资源
最近更新 更多