[root@master01 scripts]# mkdir log
[root@master01 scripts]# cat config.txt
192.168.206.5 |nginx tomcat
192.168.206.6 |minio
#/bin/bash
## 验证用户密码
IP=192.168.206.6
while true
do
read -p "请输入用户:" user
echo -n "请输入密码:"
read -s passwd
echo $''
read -p "请输入端口号:" port
sshpass -p $passwd ssh -p $port $user@$IP "hostname" >/dev/null 2>&1
if [ $? -eq 0 ];then
break;
else
echo "登录失败,重新输入"
fi
done
time=$(date +"%Y-%m-%d-%H:%M:%S")
isContinue='y'
# 检查服务
check(){
sshpass -p $passwd ssh -p $port $user@$a "$d" > ./log/temp.log 2>&1
cat ./log/temp.log >>./log/$time.log 2>&1
if [ ! -z "`cat ./log/temp.log|grep -i running`" ];then
echo "有服务未能停止,具体如下,请手动停止,具体详情在./log/$time.log"
run=`cat ./log/temp.log|grep -i -n "running" |awk -F ':' '{print $1}'`
for e in $run;do sed -n "`echo $(($e-2))`p" ./log/temp.log ;done
echo "手动停止后,按y继续,按ctrl+c或者n退出"
else
echo "停止$a服务器完毕,日志记录在./log/$time.log, 可以进行查看,无问题按y,有问题按ctrl+c或者n"
fi
}
# 停止服务
len=`cat ./config.txt|wc -l`
for ((i=1; i<=$len; i ++))
do
echo $i
a=`cat ./config.txt|awk -F '|' '{print $1}'|sed -n "$i"p`
b=`cat config.txt|awk -F '|' '{print $2}'|sed -n "$i"p`
c="for i in $b ;do systemctl stop \$i --no-pager && sleep 2s;done"
d="for i in $b ;do systemctl status \$i --no-pager ;echo $'';done"
echo "停止$a服务器$b业务,请查看./log/$time.log"
echo " 停止$a服务器$b业务 " >> ./log/$time.log
sshpass -p $passwd ssh -p $port $user@$a "$c" >> ./log/$time.log 2>&1
if [ $? -eq 0 ];then
sleep 15s;
check $a $b $d;
while true
do
read -p 'continue?[y/n]' isContinue
if [ $isContinue == 'y' ];then
echo $i
break;
elif [ $isContinue == 'n' ];then
exit;
else
echo "输入错误请重新输入"
fi
done
else
echo "停止$a服务器异常,请查看./log/$time.log和检查ssh是否可连接"
exit;
fi
done
echo "所有服务停止完毕 "
问题解决
len=${#list_name[*]} # 数组的长度
name=${list_name[@]} # 列出所有的数组
for 循环
for ((i=0; i<=len; i ++)) do order=${list_order[i]} eval $order='"for i in $name ;do systemctl stop \$i --no-pager && sleep 5s;done"' done
i ++ : i=$(($i+1))
如下这样,双引号中的$name 还是会获取变量name的数值,而其他的都是常量,不会进行bash
a="for i in $name ;do systemctl stop \$i --no-pager && sleep 5s;done"
a=b $a=123 因为shell 不能二次进行解析,使用eval
字符串转数组
list_name=`cat service.txt` list_name=(${list_name//,/})