2016-03-03 93 views
1

我不得不使用期待SSH自动化的远程外壳(庆典壳本地和远程在我的具体情况)。也就是说,我需要在expect脚本中包装ssh [email protected] "echo This is \$(hostname)"有远程shell计算表达式内预计SSH脚本

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

现在我包内的expect有ssh远程Shell命令在这里记录

#/bin/bash 

expect <<- DONE 
    spawn ssh [email protected] "echo This is \\$(hostname)" 
DONE 

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

我试过不同程度的反斜杠逃逸,单引号和双引号,<<- DONE<< DONE和移动$(hostname)自身的预计变量(即set someCommand "\\$hostname",然后引用$someCommand)。但没有任何帮助。

如何在SSH中使用远程shell评估shell表达式期望脚本?

+0

这 “只是” 一个引用的问题。使用不插入文档的heredoc表单:'expect << - 'DONE''(引用终止词),其余保持不变。 –

+0

@glennjackman,在我的情况下使用'expect << - 'DONE''导致'无法读取“(主机名)”:执行“spawn ssh [email protected]”时没有这样的变量echo这是\\ $ (主机名)“”'' – Abdull

回答

2

你快到了。

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

输出:

[email protected]:~/stackoverflow$ ./abdull 
spawn ssh [email protected] echo This is $(hostname) 
[email protected]'s password: 
This is remote-lab 

注:spawn语句也可以写成

spawn ssh [email protected] {echo This is \$(hostname)} 
+0

您不需要在大括号内转义美元,但是您可能需要使用双引号来表示echo的参数:'spawn ssh who @ where {echo“this is $(hostname)”}' –

+0

@Dinesh,非常感谢。你的解决方案使我走上了正确的道路。我错过了'expect {...}'部分。 – Abdull