我已经有一个ssh代理设置,我可以在外部服务器上运行命令在Bash脚本做这样的事情:

ssh blah_server "ls; pwd;"

现在,我真正想做的是在外部服务器上运行大量长命令。把所有这些都放在引号之间会很难看,为了避免这种情况,我真的宁愿避免多次ssh。

有没有一种方法可以一次性完成,用括号括起来?我想要的是:

ssh blah_server (
   ls some_folder;
   ./someaction.sh;
   pwd;
)

基本上,我对任何解决方案都很满意只要它是干净的。

Edit

为了澄清,我说的是这是一个更大的bash脚本的一部分。其他人可能需要处理脚本,所以我希望它保持干净。我不想有一个bash脚本与一行看起来像:

ssh blah_server "ls some_folder; ./someaction.sh 'some params'; pwd; ./some_other_action 'other params';"

因为它极其丑陋,难以阅读。


当前回答

这对于创建脚本很有效,因为你不需要包含其他文件:

#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
    # here you just type all your commmands, as you can see, i.e.
    touch /tmp/test1;
    touch /tmp/test2;
    touch /tmp/test3;
EOF

# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..

其他回答

为了匹配示例代码,可以将命令包装在单引号或双引号中。例如

ssh blah_server "
  ls
  pwd
"

这对于创建脚本很有效,因为你不需要包含其他文件:

#!/bin/bash
ssh <my_user>@<my_host> "bash -s" << EOF
    # here you just type all your commmands, as you can see, i.e.
    touch /tmp/test1;
    touch /tmp/test2;
    touch /tmp/test3;
EOF

# you can use '$(which bash) -s' instead of my "bash -s" as well
# but bash is usually being found in a standard location
# so for easier memorizing it i leave that out
# since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..

对于任何像我一样在这里出错的人,我成功地逃脱了分号和换行符:

第一步:分号。这样,我们就不会破坏ssh命令:

ssh <host> echo test\;ls
                    ^ backslash!

列出了远程主机/home目录(以根用户登录),而

ssh <host> echo test;ls
                    ^ NO backslash

列出当前工作目录。

下一步:拆分行:

                      v another backslash!
ssh <host> echo test\;\
ls

这再次列出了远程工作目录-改进的格式:

ssh <host>\
  echo test\;\
  ls

如果真的比这里的文档或虚线周围的引号更好-好吧,不是我说了算…

(使用bash, Ubuntu 14.04 LTS)

我认为有两种方法:

首先,像这样创建一个控制套接字:

 ssh -oControlMaster=yes -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip>

运行你的命令

 ssh -oControlMaster=no -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip> -t <yourcommand>

通过这种方式,您可以编写ssh命令,而不必实际重新连接到服务器。

第二种方法是动态生成脚本,扫描脚本并运行。

这也可以按照以下方法完成。 将命令放到脚本中,我们将其命名为commands-inc.sh

#!/bin/bash
ls some_folder
./someaction.sh
pwd

保存文件

现在在远程服务器上运行它。

ssh user@remote 'bash -s' < /path/to/commands-inc.sh

我从来没有失败过。