天天看點

使用python 自動化監控程序

自動化監控程序在項目中是非常重要的,監控指定程式是否運作,如果程式沒有運作,那麼啟動程式,

下面是使用python來實作的一個程序監控腳本,自己搞的過程中遇到的坑,在這裡總結下

下面的我們的python腳本檔案

import commands
import os
import sys
import logging

def monitor_process():
  status,output = commands.getstatusoutput("jps -m  |grep 'com.static.app.Main'|wc -l")
 
  #counts = len(schedule)
  #print(counts)
  print(output)
  if (output == '0'):
    os.system("sh /server/statics/start.sh")
    #subprocess.call("sh /server/statics/start.sh",shell=True)   
 
	
#if __name__ == '__main__':
monitor_process()
           

使用jps -m |grep 'com.static.app.Main'|wc -l   linux指令查詢statics程序數

if判斷等于0時,啟動我的start.sh腳本,start.sh腳本中是啟動服務并配置設定資源的指令,這裡不在闡述

之後需要使用linux的定時啟動指令在定時執行監控的python腳本

linux中執行    contrab -e

*/5 * * * * source /etc/profile && cd /server/statics/ && python /server/statics/defend.py
           

這裡*/5 * * * *  五分鐘啟動一次 defend.py

需要注意的是,有時候代碼沒錯,但是程式不執行,需要注意設定一下環境變量才能生效source /etc/profile