[英]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.