我正在尝试一个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
应该警告,通过简单的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。
要在另一台主机上运行所有内容,需要将其作为参数传递给sshssh $i "echo ansible | ...."
。整个命令被传递给ssh,然后远程shell将该命令再次拆分为令牌,并将echo ansible
和...
部分作为用|
分隔的两个命令执行。
对我来说,脚本应该看起来像:
#!/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
检查报价和abc var时,你的主机