在Bash中ssh和运行多个命令的最干净方法是什么?

编程入门 行业动态 更新时间:2024-10-08 06:17:29
本文介绍了在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和运行多个命令的最干净方法是什么?

本文发布于:2023-10-19 17:38:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508274.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   干净   命令   方法   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!