对于多个服务器上执行命令bash脚本 [英] bash script for executing commands on multiple server
问题描述
我想这将重新启动各自的服务器上定义的服务的脚本。我想通过参数如下的脚本:
例如:
I want a script which will restart the defined services on their respective servers. I want to pass parameter as below to the script: eg:
sh execute.sh
Enter your server and service list: [server1:nginx,mysql],[server2:mysql,apache],[server3:mongodb,apache]
通过此输入脚本应该核实和相应的服务器上启动服务。我能够通过声明变量这样做一台服务器上。
By this input the script should verify and start the services on the respective servers. I am able to do this on a single server by declaring variables.
#!/bin/bash
Instance_Name=server1
Service_Name=(nginx php-fpm mysql)
SSH_USER=admin
SSH_IDENT_FILE=~/credentials/user.pem
len=${#Service_Name[*]}
i=0
while [ $i -lt $len ]; do
service=${Service_Name[$i]}
ssh -i $SSH_IDENT_FILE -o StrictHostKeyChecking=no $SSH_USER@$Instance_Name 'service $service restart'
done
现在我没有一个想法前进。请让我知道,如果我的问题是不清楚。提前致谢。
Now I don't have an idea to move forward. Please let me know if my question is unclear. Thanks in advance.
推荐答案
解析您的输入参数
# create an array of server:services
a=($(echo "$1" | gawk 'BEGIN { FS="[]],[[]" } ; { print $1, $2, $3 }' | tr -d '[]'))
# add a for loop here to iterate values in array with code below
for var in "${a[@]}" ; do
# get server name
server1=$(echo $var | cut -d ':' -f1)
# get your services as space separated
servs1="$(echo $var | cut -d ':' -f2 | tr ',' ' ')"
# loop your services
for s in $servs1; do
ssh $server1 "service $s restart"
done
done
如果你喜欢bash编程或者学习它这是圣经给我
高级Bash脚本编程指南
在深入探索艺术shell脚本的
孟德尔库珀
http://www.tldp.org/LDP/abs/html/
If you like bash programming or have to learn it this is the 'bible' to me Advanced Bash-Scripting Guide An in-depth exploration of the art of shell scripting Mendel Cooper http://www.tldp.org/LDP/abs/html/
这篇关于对于多个服务器上执行命令bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!