Linux 檢查並重新啟動 Apache2

現在主機大多都用 Debian / Ubuntu Linux, 可能實驗性的東西裝太多, 常常不小心就玩掛了而沒注意到.

所以用 Python 寫隻 Script 來 檢查 / 判斷 Apache2 是否活著, 死掉的話, 要自動重新啟動.

Check and Restart Apache2 script

  1. vim /usr/bin/monitor_apache2.py
    #!/usr/bin/python
    from os import system, path
    
    pid_file = '/var/run/apache2.pid'
    cmd = 'sudo /etc/init.d/apache2 restart'
    
    if not path.exists(pid_file):
        system(cmd)
  2. chmod +x /usr/bin/monitor_apache2.py
  3. crontab -e # 下述設定每 10分鐘檢查一次
    */10 * * * * /usr/bin/monitor_apache2.py

感謝 clifflu 指點, 另外寫這隻是用 service 檢查 Apache status 的狀態.

#!/usr/bin/python
import os
status = os.popen('/usr/sbin/service apache2 status').readlines()

# apache2: unrecognized service
# Apache2 is running (pid 24087).
running = False
if status.pop().find('running') > 0:
    running = True

if not running:
    system('sudo /usr/sbin/service apache2 restart')

下面這隻備用, 判斷 Apache2 的 Process 是否存在, 不存在就重新啟動 Apache2.

#!/usr/bin/python
import os
lines = os.popen('ps aux | grep apache | grep -v grep').readlines()

running = False
for len(lines) >= 0:
    running = True

#for line in lines:
#    proc_id = line.split()[1]

if not running:
    system('sudo /etc/init.d/apache2 restart')

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈Linux 檢查並重新啟動 Apache2〉中有 5 則留言

  1. 在 ubuntu 底下,pid file 是從 /etc/apache2/envvars 設定;
    然而其中用到了 $SUFFIX,解析需要載入環境變數,稍微麻煩
    並且也不保證該檔案確實包含 apache2 的 pid

    要避免 hard code pid file 的困擾,可以使用 service 工具
    syntax : service apache2 status

    輸出為 'Apache2 is running (pid 12950).' ,容易以正則表示式取得相關資訊,並且 service 會做相關檢查

    1. 感謝指點, 確實應該判斷行數比較快~
      我用 for-in 主要是要印 pid, 有時候 Apache 卡住砍不掉時, 可以直接用這方法 killall.
      改成您說得方法來寫了, 謝謝~ 😛

Rain 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料