簡體   English   中英

Bash for 循環在遠程服務器上執行命令

[英]Bash for loop to execute commands on remote servers

所以我有一個長度為 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選項無濟於事。

謝謝。

您當前的代碼未向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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM