1. 程式人生 > >shell作業之http互動指令碼

shell作業之http互動指令碼

作業

問:編寫httpd監控指令碼,要求可以輸入start|stop|restart|status

答:指令碼如下

#!/bin/bash
#Date:2018-12-28
#Author:nelws-lcz
#Connect:[email protected]
#Desc:This script is for http
#Version:1.0
while true
do
    echo -e "
    \033[31m A 開啟httpd,    \033[0m
    \033[32m B 停止httpd      \033[0m
    \033[33m C 重啟httpd,    \033[0m
    \033[34m D 檢視httpd狀態  \033[0m
    \033[35m Q 退出此程式     \033[0m

"
read -p "請輸入你的選擇:" char

state=`systemctl status httpd | grep "Active" | awk '{print $2}'`
state1=`systemctl status httpd | grep "Loaded" | awk '{print $2}'`

case $char in

a|A)
    if [ $state == "inactive" ];then
        if [ $state1 == "not-found" ];then
       		 yum install httpd -y >/dev/null
       		 firewall-cmd --add-service=http >/dev/null
        	 firewall-cmd --reload >/dev/null
       	 	 systemctl start httpd
		 echo "httpd service is installed and running"
	else
       		 systemctl start httpd
                 firewall-cmd --add-service=http >/dev/null
                 firewall-cmd --reload >/dev/null
       		 echo "httpd service is running"
	fi
    else
	echo "httpd service is already running"	
    fi	
    ;;

b|B)
    if [ $state == "inactive" ];then
	echo "httpd service is already stopped"
    else
	systemctl stop httpd
    echo "httpd service has stopped"
    fi
    ;;

c|C)
    if [ $state == "inactive" ];then
	echo "httpd service is not running,what you can do is use command A to start it!"
    else
	systemctl restart httpd
	echo "httpd service has been restarted"
    fi
    ;;

d|D)
    if [ $state == "inactive" ];then
	echo "httpd service is not running"
    else
	echo "httpd service is running"
    fi
    ;;
q|Q)
    exit 0
    ;;
*)
    echo "sorry,you command is not exist,please check!"
esac
done

測試結果

1.http開啟選項(a選項)

1)當http已經開啟的時候

2)當http沒有開啟的時候

3)當http沒有開啟也沒有安裝的時候

2.http停止選項

1)http已經開啟的時候

2)http已經關閉的時候

3.http重啟選項

1)http已經開啟的時候

2)http已經關閉的時候

4.http狀態選項

1)http已經開啟的時候

2)http已經關閉的時候

5.離開選項

6.輸入無效命令的時候

bingo~