[英]Bash for loop to execute commands on remote servers
So I have a list of servers with n length.所以我有一个长度为 n 的服务器列表。 I need to open a connection and edit a file and close it.我需要打开一个连接并编辑一个文件并关闭它。
Here's what I currently have:这是我目前拥有的:
#!/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
The only issue I have is that I can't exit the ssh connection and move on to the next in the array.我唯一的问题是我无法退出 ssh 连接并移动到数组中的下一个。 I have used the -n
, -t
and -T
options to no avail.我使用了-n
、 -t
和-T
选项无济于事。
Thanks.谢谢。
Your current code isn't sending any commands to the ssh
sessions.您当前的代码未向ssh
会话发送任何命令。 Use a heredoc to pass your commands into 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.