所以我有一个长度为 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/