#!/usr/bin/env python
# -*- coding: cp936 -*-
'''
Created on 2011-12-6
@author: caojj
'''
import time
import socket
import subprocess
class WatchProtect(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.watchList=[]
self.errorInfo = None
def run(self):
if len(self.watchList)<= 0:
print 'no match string '
return
procWatch = self.matchText()
procWatch.next()
while True:
time.sleep(15)
print ' watching was working ......'
self.errorInfo = None
strResult = self.checkServer()
procWatch.send(strResult)
return
def checkServer(self):
self.errorInfo = None
result= ''
for text in self.watchList:
strcommand= 'ps -ef|grep ' + text
output=subprocess.Popen(strcommand,shell = True,stdout = subprocess.PIPE)
result = result + output.communicate()[0]
return result
def getCurrentDateTime(self):
strCurrentDate = time.strftime(u"%Y-%m-%d %X",time.localtime())
return strCurrentDate
def sendWarning(self,ip ,text):
#print ' find error,send message to manager'
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp.connect((ip,2425))
strError = self.getCurrentDateTime()
if text == 'DeviceServer':
strError += u'''
老宋,设备服务挂了,请通过VNC登陆到测试服务器诊断一下,这是个服务器自动消息,请勿回复。
服务器地址: 192.168.0.245 ; vnc-> 192.168.0.245:1 password: 123456
提示:在服务启动之前,该消息会不停出现,你忽略即可。给你的工作带来不便,深表歉意
'''
if text == 'mediaServer':
strError += u'''
阿军,流媒体服务挂了,请通过VNC登陆到测试服务器诊断一下,这是个服务器自动消息,请勿回复。
服务器地址: 192.168.0.245 ; vnc-> 192.168.0.245:1 password: 123456
提示:在服务启动之前,该消息会不停出现,你忽略即可。给你的工作带来不便,深表歉意
'''
text = u'1:100:server:server:32: ' + strError
#text.encode
udp.send(text.encode('gbk'))
def matchText(self):
#print ' begin match'
while(True):
line= (yield)
for text in self.watchList:
time.sleep(1)
lineN = line.replace('grep '+ text,'None')
lineN = lineN.replace('gdb '+ text,'None')
print ' check :',text , ' is alive ? '
if not(text in lineN):
print ' Failed,sendmessage to administrator'
self.errorInfo = 'Server=',text ,' Failed \n'
if text.find('DeviceServer') >= 0:
self.sendWarning('192.168.0.178',text )
elif text.find('mediaServer') >= 0:
self.sendWarning( '192.168.0.178',text )
#self.sendWarning('192.168.0.178', text )
print ' Yes,pass'
return
def main():
print 'Start watching server alive'
watch = WatchProtect()
# watch.sendWarning('192.168.0.178', 'DeviceServer')
# return
watch.watchList.append('DeviceServer')
watch.watchList.append('mediaServer')
watch.run()
#db.readconfig()
return
if __name__ == '__main__':
main()