在Bash中ssh和运行多个命令的最干净方法是什么? [英] What is the cleanest way to ssh and run multiple commands in Bash?

查看:89
本文介绍了在Bash中ssh和运行多个命令的最干净方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了ssh代理,并且可以使用Bash脚本在外部服务器上运行命令,例如:

I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

ssh blah_server "ls; pwd;"

现在,我真正想做的是在外部服务器上运行许多长命令.将所有这些都用引号引起来是很丑陋的,我真的宁愿避免多次使用ssh来避免这种情况.

Now, what I'd really like to do is run a lot of long commands on an external server. Enclosing all of these in between quotation marks would be quite ugly, and I'd really rather avoid ssh'ing multiple times just to avoid this.

那么,有什么方法可以一次用括号括起来吗?我正在寻找符合以下条件的东西:

So, is there a way I can do this in one go enclosed in parentheses or something? I'm looking for something along the lines of:

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

基本上,只要解决方案满意,我都会对它感到满意.

Basically, I'll be happy with any solution as long as it's clean.

为了澄清,我说的是这是一个更大的bash脚本的一部分.其他人可能需要直接处理脚本,因此我想保持脚本整洁.我不想让bash脚本的一行看起来像这样:

To clarify, I'm talking about this being part of a larger bash script. Other people might need to deal with the script down the line, so I'd like to keep it clean. I don't want to have a bash script with one line that looks like:

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

因为它非常丑陋且难以阅读.

because it is extremely ugly and difficult to read.

推荐答案

关于Bash的操作此处文档:

ssh otherhost << EOF
  ls some_folder; 
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

为避免@Globalz在评论中提到的问题,您可以(根据远程站点的工作情况)将第一行替换为

To avoid the problems mentioned by @Globalz in the comments, you may be able to (depending what you're doing on the remote site) get away with replacing the first line with

ssh otherhost /bin/bash << EOF

请注意,您可以在Here文档中进行变量替换,但是您可能必须处理引用问题.例如,如果引用限制字符串"(即上面的EOF),则不能进行变量替换.但是不引用限制字符串,而是替换变量.例如,如果您在外壳程序脚本中定义了$NAME,则可以

Note that you can do variable substitution in the Here document, but you may have to deal with quoting issues. For instance, if you quote the "limit string" (ie. EOF in the above), then you can't do variable substitutions. But without quoting the limit string, variables are substituted. For example, if you have defined $NAME above in your shell script, you could do

ssh otherhost /bin/bash << EOF
touch "/tmp/${NAME}"
EOF

,它将在目标otherhost上创建一个文件,其名称为您分配给$NAME的名称.关于shell脚本引用的其他规则也适用,但是太复杂了,无法在此处介绍.

and it would create a file on the destination otherhost with the name of whatever you'd assigned to $NAME. Other rules about shell script quoting also apply, but are too complicated to go into here.

这篇关于在Bash中ssh和运行多个命令的最干净方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆