for循环中的远程服务器阵列args

时间:2019-01-09 14:52:13

标签: bash

我需要将值从数组传递到远程主机上的脚本。

远程脚本在每个数组值上本地创建文件。

是的,我可以通过:

for i in ${LIST[@]}
do ssh root@${servers} bash "/home/test.sh" "$i"
done

但是此操作相当缓慢,并且会在每个数组值上进行ssh会话

ssh root@${servers} bash "/home/test.sh" "${LIST[@]}"

通过此代码,我得到一个错误:

bash:第1338行:找不到命令

我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用ssh的连接共享功能,以便循环中每个ssh进程仅使用一个预先经过身份验证的连接。

# This is the socket all of the following ssh processes will use
# to establish a connection to the remote host.
socket=~/.ssh/ssh_mux

# This starts a background process that does nothing except keep the
# authenticated connection open on the specified socket file.
ssh -N -M -o ControlPath="$socket" root@${servers} &

# Each ssh process should start much more quickly, as it doesn't have to
# go through the authentication protocol each time.
for i in "${LIST[@]}"; do
  # This uses the existing connection to avoid having to authenticate again
  ssh -o ControlPath="$socket" root@${servers} "bash /home/test.sh '$i'"

  # The above command is still a little fragile, as it assumes that $i
  # doesn't have a single quote in its name.
done

# This closes the connection master
ssh -o ControlPath="$socket" -O exit root@{servers}

另一种方法是尝试将循环移到远程命令中,但这很脆弱,因为未在远程主机上定义数组,并且没有很好的方法来保护每个元素的方式转移每个元素。如果您不担心分词,可以使用

ssh root@${servers} "for i in ${LIST[*]}; do bash /home/test.sh \$i; done"

但是那样的话,您可能一开始就不会使用数组。