[英]bash run multiple commands on remote hosts via ssh
I am trying to connect to multiple hosts in a loop and run few commands/scripts via ssh, and store results in local var.我试图在一个循环中连接到多个主机并通过 ssh 运行几个命令/脚本,并将结果存储在本地变量中。 I am using a here doc but I am a bit confused on whether it should be quoted or not, as I am using a mix of local vars and remotely declared vars.
我正在使用此处的文档,但我对是否应该引用它感到有些困惑,因为我使用的是本地变量和远程声明变量的混合。 What would be the proper syntax for this ?
什么是正确的语法? What do I need to escape?
我需要逃避什么?
for host in $HOSTS; do
RESULT+=$(ssh -T $host <<EOF
H=`dirname $HOME`
M=`mount | grep $H | grep nfs`
[[ "$M" ]] && MYFILE=$WD/file1 || MYFILE=$WD/file2
cd $WD && monit.sh $MYFILE
EOF
)
done
$RESULT and $WD are local vars, while the others are remote. $RESULT 和 $WD 是本地变量,而其他变量是远程变量。 The result with the above is that local vars have the expected values, while all the remotely declared vars are empty ($H , $M , $MYFILE..) If I enclose EOF in single quotes, the result is somehow reversed : $WD is empty, while $H and $M get proper values ($MYFILE also but without the $WD part)
上面的结果是本地变量具有预期值,而所有远程声明的变量都是空的 ($H , $M , $MYFILE ..) 如果我将 EOF 用单引号括起来,结果会以某种方式颠倒:为空,而 $H 和 $M 获得正确的值($MYFILE 也有,但没有 $WD 部分)
Many thanks非常感谢
Short answer: escape (with a backslash) every $
and backtick that you want interpreted on the remote computer.简短回答:转义(使用反斜杠)每一个你想在远程计算机上解释的
$
和反引号。 Actually, I'd recommend replacing the backticks with $( )
(and then escaping the $
).实际上,我建议用
$( )
替换反引号(然后转义$
)。 I haven't tested, but this should do it:我还没有测试过,但这应该可以:
for host in $HOSTS; do
RESULT+=$(ssh -T $host <<EOF
H=\$(dirname \$HOME)
M=\$(mount | grep \$H | grep nfs)
[[ "\$M" ]] && MYFILE=$WD/file1 || MYFILE=$WD/file2
cd $WD && monit.sh \$MYFILE
EOF
)
done
Without the escapes, everything was getting interpreted by the local shell before it was sent to the remote system.如果没有转义,所有内容都会在发送到远程系统之前由本地 shell 解释。 When you quoted
EOF
, that told the local shell not to do any interpretation at all, so the local variable ( $WD
) didn't get substituted.当您引用
EOF
,这告诉本地外壳根本不要做任何解释,因此本地变量( $WD
)没有被替换。
You can use below bash script:您可以使用以下 bash 脚本:
for s in $(cat host.txt); do
ssh root@${s} 'bash -s' < /tmp/commands.sh
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.