我正在尝试一个shell脚本,它需要等待该服务停止,如果停止的脚本继续执行,否则该脚本将挂起退出。有人可以帮我这个忙。我正在尝试的PFB脚本
for i in 13.127.xxx.xxx xx.xxx.xxx.xx
do
echo '############# Stopping the '$i' Apache service ################'
ssh $i echo 'ansible' | sudo -S /etc/init.d/apache2 stop || { echo 'my command failed' ; exit 1 ; }
wait
echo 'service has been stopped'
echo '############# Status of the '$i' Apache service ################'
abc=0
abc=`ps -ef | grep "apache" | grep -v "grep" | wc -l`
if [ $abc -eq 0 ]
then
echo "Boomi process on $i is stopped, proceeding further!!!"
else
echo "Exiting the script as Script could not stop the Boomi process, Please check the issue " ; exit 1;
fi
sleep 10
ssh $i echo 'ansible' | sudo -S /etc/init.d/apache2 status
done
答案 0 :(得分:0)
对我来说,脚本应如下所示:
#!/bin/bash
for i in 13.127.xxx.xxx xx.xxx.xxx.xx
do
echo '############# Stopping the '$i' Apache service ################'
ssh $i echo "ansible | sudo -S /etc/init.d/apache2 stop" || { echo 'my command failed' ; exit 1 ; }
wait
echo 'service has been stopped'
echo '############# Status of the '$i' Apache service ################'
abc=0
abc=$(ssh $i echo "ansible | sudo -S pgrep apache | wc -l")
if [ "$abc" -eq 0 ]
then
echo "Boomi process on $i is stopped, proceeding further!!!"
else
echo "Exiting the script as Script could not stop the Boomi process, Please check the issue " ; exit 1;
fi
sleep 10
ssh $i echo "ansible | sudo -S /etc/init.d/apache2 status"
done
sshing您的主机时检查引号和abc var
答案 1 :(得分:0)
一个人应该警告,通过简单的ssh bash命令使用管道重定向传递未加密的密码既不安全,也很糟糕。可以检查脚本的脚本将立即获得对节点的root访问权限。正确的方法是添加一个行sudoers文件,以作为普通,无特权的用户执行指定的命令(/etc/init.d/apache和pgrep)。
for i in 13.127.xxx.xxx xx.xxx.xxx.xx; do
echo '############# Stopping the '"$i"' Apache service ################'
if ! ssh "$i" 'echo ansible | sudo -S /etc/init.d/apache2 stop'; then
echo "ERROR: stopping apache2 on $i failed!" >&2
exit 1
fi
echo 'service has been stopped'
echo '############# Status of the '"$i"' Apache service ################'
ssh "$i" 'echo ansible | sudo -S pgrep apache' && ret=$? || ret=$?
if [ "$ret" -eq 0 ]; then
echo "apache process is not stopped"
elif [ "$ret" -eq 1 ]; then
echo "apache process was successfully stopped"
else
echo "error in executing ssh + pgrep"
exit 1
fi
sleep 10
ssh "$i" 'echo ansible | sudo -S /etc/init.d/apache2 status'
done
您忘记了引号。如果您运行ssh $i echo ansible | ....
,则...
中的零件将在本地而不是在远程计算机上执行。 |
字符分隔命令,就像;
或&&
或||
或&
一样。除了分隔命令外,它还将第一个命令stdout与其他stdin连接起来。
要在其他主机上运行所有内容,需要将其作为参数传递给ssh ssh $i "echo ansible | ...."
。整个命令传递给ssh,然后远程shell将命令再次拆分为令牌,并将echo ansible
和...
部分作为两个用|
分隔的命令来执行。