我想要一个脚本,它将在各自的服务器上重新启动已定义的服务。我想将参数如下传递给脚本: 例如:
sh execute.sh
Enter your server and service list: [server1:nginx,mysql],[server2:mysql,apache],[server3:mongodb,apache]
通过此输入,脚本应验证并启动相应服务器上的服务。我可以通过声明变量在单个服务器上执行此操作。
#!/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
现在我没有想法继续前进。如果我的问题不清楚,请告诉我。提前致谢。
答案 0 :(得分:1)
解析输入参数
# 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-Scripting Guide 深入探索shell脚本的艺术 孟德尔库珀 http://www.tldp.org/LDP/abs/html/
答案 1 :(得分:0)
试试这个?
#!/bin/bash
SSH_IDENT_FILE=~/credentials/user.pem
SSH_USER=admin
# tells 'for' to read "per line"
IFS='
'
for line in $(
# read input from 1st command-line arg (not stdin)
echo "$1"|\
# remove all services except (nginx php-fpm mysql)
sed 's/\([:,]\)\(\(nginx\|php-fpm\|mysql\)\|[^]:,[]\+\)/\1\3/g'|\
# make it multi-line:
# server1 svc1 svc2
# server2 svc1
sed 's/\[[^]:]*:,*\]//g;s/\],*$//;s/\],*/\n/g;s/[:,]\+/ /g;s/\[//g'|\
# make it single-param:
# server1 svc1
# server1 svc2
# server2 svc1
awk '{for(i=2;i<=NF;i++)print $1" "$i}'
);do
IFS=' ' read Instance_Name service <<< $line
echo ssh -i $SSH_IDENT_FILE -o StrictHostKeyChecking=no $SSH_USER@$Instance_Name "service $service restart"
done