現在主機大多都用 Debian / Ubuntu Linux, 可能實驗性的東西裝太多, 常常不小心就玩掛了而沒注意到.
所以用 Python 寫隻 Script 來 檢查 / 判斷 Apache2 是否活著, 死掉的話, 要自動重新啟動.
Check and Restart Apache2 script
- 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)
- chmod +x /usr/bin/monitor_apache2.py
- 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')