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

标签 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 选项无济于事。

谢谢。

最佳答案

您当前的代码未向 ssh session 发送任何命令。使用 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

关于linux - Bash for循环在远程服务器上执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033414/

相关文章:

正则表达式 - 拆分字符串

regex - 查找文本文件中至少有两个相同单词的所有行 (Bash)

c++ - 搜索模式名称的共享库

c - setgid() 失败 - 不允许操作

linux - 如何在 shell 脚本中使用 curl?

linux - Shebang 导致脚本失败

ssh - 使用ssh命令将目录上传到远程服务器的本地文件路径?

linux - linux下解析文件

linux - 如何在运行但分离的屏幕上显示 "peek"?

linux - 从 SOAPUI 访问服务器 (PUTTY) 上的日志