bash - 让远程Shell评估期望ssh脚本中的表达式

标签 bash shell ssh expect

我必须使用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/

相关文章:

linux - xargs : "bash -c" does not pass arguments to command 中的 bash 别名

bash - 带 shell 脚本的音乐

c - 将数据发送到等待 ppoll 的另一个进程的 stdin

分离 ssh+tmux session 时,Python 代码崩溃并显示 "cannot connect to X server"

linux - 更新脚本以替换每个主机的编号,然后将新文件传输到服务器组

java - 如何从 bash 脚本指定工作目录

bash - 在 bash 中将文本附加到 stderr 重定向

ruby - 测试 ssh 连接

bash 检查用户挂载是否失败

python - 允许我的 python 脚本的 Makefile?