1. 程式人生 > >shell指令碼實現定時開啟Apache服務

shell指令碼實現定時開啟Apache服務

  1. 寫shell指令碼
#! /bin/bash
case $1  in
        start)
                systemctl start httpd
                if [ $? -eq 0 ]
                then
                        echo "已成功開啟httpd服務"
                else
                        echo "開啟失敗"
                fi
                ;;
        stop)
                systemctl stop httpd
                if [ $? -eq 0 ]
                then
                        echo "已成功關閉httpd服務"
                else
                        echo "關閉失敗"
                fi
                ;;
        restart)
                systemctl restart httpd
                if [ $? -eq 0 ]
                then
		                echo "已成功重啟httpd服務"
                else
                        echo "重啟失敗"
                fi
                ;;
          *)
                echo "沒有此項功能,敬請期待"
                ;;
esac

  1. 實現定時任務

yum install -y crontabs
systemctl start crond
crontab -e 設定定時任務
46 14 * * * . /root/mariadb.sh stop
crontab -l 檢視已經設定的定時任務
[[email protected] ~]# crontab -l
46 14 * * * . /root/mariadb.sh stop

#! /bin/bash
read -p "請輸入您要管理的服務名稱:" name
echo "1、開啟${name};"
echo "2、重啟${name};"
echo "3、關閉${name};"
echo "4、檢視${name}狀態;"
echo "5、開啟定時服務;"
echo "6、退出"
read -p "請選擇您要進行的操作:" num
case $num in
        1) systemctl start $name
           if [ $? -eq 0 ]
           then
           echo "${name}開啟成功!"
           else
           echo "${name}開啟失敗!"
           fi
        ;;
        2) systemctl restart $name
           if [ $? -eq 0 ]
           then
           echo "${name}重啟成功!"
           else
           echo "${name}重啟失敗!"
           fi
        ;;
        3) systemctl stop $name
           if [ $? -eq 0 ]
           then
           echo "${name}關閉成功!"
           else
           echo "${name}關閉失敗!"
           fi
        ;;
        4)
          systemctl status $name
        ;;
        5)
          read -p "請輸入每天自動開啟的時間(24小時制):" h_up
          read -p "請輸入每天自動關閉的時間(24小時制):" h_down
          echo "0 ${h_down} * * * systemctl stop $name" > crontab.cron
          echo "0 ${h_up} * * * systemctl start $name" >> crontab.cron
          crontab crontab.cron
          if [ $? -eq 0 ]
          then
          echo "${name}定時功能開啟成功!"
          echo "您的設定為每天${h_up}點開啟,${h_down}點關閉!"
          else
          echo "${name}定時功能開啟失敗!"
          fi
        ;;
        6)echo "歡迎下次使用,謝謝!"
        ;;
        *) echo "暫無此功能,正在開發中..."
        ;;
esac