【问题标题】:Multiple ssh in a Single command单个命令中的多个 ssh
【发布时间】:2018-01-16 15:23:26
【问题描述】:

我需要通过管道传输多个 ssh 命令才能在远程机器上运行命令。 这些命令在单个 ssh 上运行良好,但在管道 ssh 之后却不行。 例如

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

回你好 但是

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.

注意:从我的机器到 remotemachine1.com 和从 remotemachine1.com 到 remotemachine2.com 建立无密码 ssh

【问题讨论】:

    标签: linux ssh centos redhat cut


    【解决方案1】:

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

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

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

    【讨论】:

    • 没有帮助,因为仍然没有产生任何输出。此外,从我的机器到 remotemachine1.com 和从 remotemachine1.com 到 remotemachine2.com 建立无密码 ssh
    • 当您坚持将参数提供给 ssh 二进制文件时,您需要使用正确的引用。这意味着第二个 ssh 命令需要用引号括起来,而第二台机器的命令需要用转义引号括起来。
    • 尝试了所有可能的引号组合.. " inside ' , ' inside ' , \" inside " .. 他们都没有工作......
    【解决方案2】:
    ssh abc@remotemachine1.com ssh abc@remotemachine2.com"a=hello ; echo \$a"
    

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

    【讨论】:

    • 我没有尝试连接到多台机器。我正在尝试在仅从 remotemachine1.com 启用 ssh 的 remotemachine2.com 上执行命令。
    • 所以你想从 machine1 跳到 machine2?然后使用 ProxyJump。在.ssh/config/etc/ssh/ssh_config 文件中将ProxyJump remotemachine1 添加到remotemachine2 的主机部分。
    • 我实际上不想编辑 ssh 配置文件,所以代理跳转是不可能的..
    • 在 ssh 程序的命令行中提供它也不是一个选项?
    【解决方案3】:

    在我添加多个转义字符后它终于起作用了

    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'  \" "
    

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 2016-06-11
      • 1970-01-01
      相关资源
      最近更新 更多