Bash for循环在远程服务器上执行命令

时间:2017-02-03 21:38:57

标签: linux bash ssh

所以我有一个n长度的服务器列表。我需要打开一个连接并编辑一个文件并关闭它。

以下是我目前的情况:

#!/bin/bash

server_list=(a b c d)

for i in "${server[@]}"; do ssh "${server[@]}"; cd /etc; cp file file.bak; perl -pi -i 's/find/replace/g' file; exit; done

我唯一的问题是我无法退出ssh连接并转到数组中的下一个连接。我使用-n-t-T选项无济于事。

感谢。

1 个答案:

答案 0 :(得分:1)

您当前的代码不会向ssh会话发送任何命令。使用heredoc将命令传递到ssh

    #!/bin/bash

    server_list=(a b c d)
    for i in "${server_list[@]}"; do
      #
      # As per Charles' suggestion - "bash -s" makes sure the commands
      # would run with Bash rather than the default shell on the remote
      # server.
      #
      # I have left your commands exactly as in your question.
      # They can be written as a single command as per @chepner's recommendation 
      ssh "$i" bash -s << "EOF"
        cd /etc
        cp file file.bak
        perl -pi -i 's/find/replace/g' file
        exit
EOF
    done
相关问题