单个命令中的多个 ssh

Multiple ssh in a Single command

我需要通过管道传输多个 ssh 命令,以便 运行 在远程机器上执行命令。 这些命令在单个 ssh 上工作正常,但在管道 ssh 之后就不行了。 例如

ssh abc@remotemachine1.com "a=hello ; echo $a"

return你好 但是

ssh abc@remotemachine1.com ssh abc@remotemachine2.com"a=hello ; echo $a"

没有输出。

同理:

ssh abc@remotemachine1.com "mountedDir=$(df \tmp | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w $mountedDir"

工作正常,产生以下输出:

/dev/sda2 on / type xfs (rw,relatime,attr2,inode64,noquota)

但是

ssh abc@remotemachine1.com ssh abc@remotemachine2.com "mountedDir=$(df \tmp | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w $mountedDir"

抛出以下错误:

Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.

注意:无密码 ssh 是从我的机器到 remotemachine1.com 以及从 remotemachine1.com 到 remotemachine2.com

ssh abc@remotemachine1.com ssh abc@remotemachine2.com"a=hello ; echo $a"

看起来不对。如果您想从 remotemachine1 跳转到 remotemachine2,请查看 ssh 配置中的 ProxyJump 选项。您可以使用 ssh 二进制文件的 -o 选项在命令行上提供它。

如果出于某种原因你不想修改你的 ssh_config 文件,你需要使用 ssh -t 这将导致在机器 2 上分配一个真正的 TTY,如下所示:

ssh -t abc@remotemachine1.com ssh abc@remotemachine2.com"a=hello ; echo $a"

请注意,使用此方法意味着所有 SSH 登录身份验证过程都将在 remotemachine1.com 发生,因此如果您有安全问题,最好使用 @allo 的回答。

添加了多个转义字符后终于成功了

ssh abc@remotemachine1.com " ssh abc@remotemachine2.com \" a=hello ;echo \$a \" "

ssh abc@remotemachine1.com " ssh abc@remotemachine2.com \" mountedDir=\$(df /var | grep -vi filesystem | rev | cut -d ' ' -f 1); mount | grep -w \$mountedDir | grep -vi 'noexec'  \" "