我必须使用Expect和ssh在远程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)
表达式将在我的本地计算机而不是远程计算机上求值。我尝试了不同级别的反斜杠转义,单引号和双引号,
<<- DONE
和<< DONE
,然后将$(hostname)
移至其自己的期望变量(即set someCommand "\\$hostname"
,然后引用$someCommand
)。但是没有任何帮助。如何让远程Shell评估SSH Expect脚本中的Shell表达式?
最佳答案
你快到了。
#!/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)}
关于bash - 让远程Shell评估期望ssh脚本中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776060/