用于 ssh 和运行命令的 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38239910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:51:47  来源:igfitidea点击:

bash script to ssh and run commands

bashssh

提问by mahmood

I want to ssh to a node and run a command there and then exit. This is repeated for all nods. The script is fairly simple

我想通过 ssh 连接到一个节点并在那里运行一个命令然后退出。对所有点头重复此操作。脚本相当简单

#!/bin/bash
NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
for i in $NODES
do
   ssh $i
   ls -l /share/apps 
   rpm -ivh /share/apps/file.rpm
   exit
done

But the problem is that, after the ssh, the ls -lcommand is missed. Therefore, the command prompt waits for an input!

但问题是,在 ssh 之后,ls -l命令丢失了。因此,命令提示符等待输入!

Any way to fix that?

有什么办法可以解决吗?

UPDATE:

更新:

I modified the loop body as

我将循环体修改为

ssh $i <<END
 ls -l /share/apps
 exit
END

But I get

但我得到

./lst.sh: line 9: warning: here-document at line 5 delimited by end-of-file (wanted `END')
./lst.sh: line 10: syntax error: unexpected end of file

采纳答案by Avihoo Mamka

Try this

尝试这个

    #!/bin/bash
    NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
    for i in $NODES
    do
       ssh $i "ls -l /share/apps;rpm -ivh /share/apps/file.rpm;exit;"
    done

回答by Avihoo Mamka

I'd change the script and would run the sshcommand with the the command to execute.

我会更改脚本并使用要执行的ssh命令运行命令。

For example:

例如:

#!/bin/bash
NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
for i in $NODES
do
   ssh $i "ls -l /share/apps && rpm -ivh /share/apps/file.rpm && exit"
done

The &&operator means that each command will be executed only if the previous command succeeded.

&&操作装置,如果前面的命令成功的每个命令将只执行。

If you want to run the command independently, you can change the &&operator to ;instead.

如果你想独立运行命令,你可以将&&操作符;改为。