2

我想要一个脚本,它将在各自的服务器上重新启动定义的服务。我想将如下参数传递给脚本:例如:

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

现在我没有前进的想法。如果我的问题不清楚,请告诉我。提前致谢。

4

2 回答 2

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 脚本指南 深入探索 shell 脚本艺术 Mendel Cooper http://www.tldp.org/LDP/abs/ html/

于 2013-10-15T13:39:10.057 回答
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
于 2013-10-15T17:17:21.017 回答