用python監控您的window服務

2021-09-03 10:08:33 字數 2340 閱讀 9471

最近比較煩,研發給的pc服務版本在虛擬機器上已經開始給客戶使用了,服務老是莫名的死翹翹,客戶不停的**給我,搞的我心情很差,於是在乙個下午,靜下心來,用python寫了個簡單的監控程序的指令碼,當發現程序消失的時候,立即呼叫服務,開啟服務。。。

指令碼的工作原理是這樣的:指令碼讀取配置檔案,讀取預先配置好的呼叫系統服務的路徑和所要監控的服務在程序管理器中的程序名,之所以要用配置檔案,是為了方便給需要的朋友,你只需要修改程序名和系統路徑,源**就不需要修改了。具體的看**中的注釋吧。。。下面的是配置檔案 config.ini

[monitorprogrampath] 

programpath: c:\program files\ssh communications security\ssh secure shell\sshclient.exe 

[monitorprocessname] 

processname: sshclient.exe 

下面來看看**:

#-*- encoding: utf-8 -*-

import logging 

import wmi 

import os 

import time 

from configparser import configparser 

configfile = 'config.ini'

config = configparser() 

config.read(configfile) 

programpath = config.get('monitorprogrampath','programpath') 

processname = config.get('monitorprocessname','processname') 

#讀取配置檔案中的程序名和系統路徑,這2個引數都可以在配置檔案中修改

prolist =  

#定義乙個列表

c = wmi.wmi() 

def main(): 

for process in c.win32_process(): 

#把所有任務管理器中的程序名新增到列表

if processname in prolist: 

#判斷程序名是否在列表中,如果是true,則所監控的服務正在 執行狀態,

#列印服務正常執行

print

''print

"server is running..."

print

''else: 

#如果程序名不在列表中,即監控的服務掛了,則在log檔案下記錄日誌

#日誌檔名是以年月日為檔名

f=open('.\\log\\'+time.strftime("%y%m%d", time.localtime())+'-exception.txt','a') 

print

'server is not running,begining to restart server...'

#列印服務狀態

f.write('\n'+'server is not running,begining to restart server...'+'\n') 

f.write(time.strftime('%y-%m-%d %h:%m:%s --%a--%c', time.localtime()) +'\n')

#寫入時間和服務狀態到日誌檔案中

os.startfile(programpath) 

#呼叫服務重啟

f.write('restart server success...'+'\n') 

f.write(time.strftime('%y-%m-%d %h:%m:%s --%a--%c', time.localtime())) 

f.close() 

#關閉檔案

print

'restart server success...'

print time.strftime('%y-%m-%d %h:%m:%s --%a--%c', time.localtime()) 

del prolist[:] 

#清空列表,否則列表會不停的新增程序名,會占用系統資源

if __name__=="__main__" : 

while

true: 

main() 

time.sleep(10) 

#每隔10秒呼叫指令碼看下服務是否正常,如果不正常則重啟服務,如果正常,則列印服務正常

呵呵,指令碼還是很簡單的,需要的朋友可以拿去玩玩,只要修改配置檔案就可以了,不需要修改源**,就能拿去跑跑,希望對大家的工作和學習有幫助,如果在使用中有問題,可以給我建議。。。

用Python寫個程序監控程式

有個應用程式不是很穩定,又暫時找到具體問題,只知道出現錯誤時日誌檔案會反映出來.該應用定時更新日誌目錄,有兩個日誌檔案 fromclient.log 記錄接收請求,fromserver.log記錄接收服務端返回.出現問題時一般是fromclient.log日誌在更新,但是fromserver.log...

用Python寫個程序監控程式

有個應用程式不是很穩定,又暫時找到具體問題,只知道出現錯誤時日誌檔案會反映出來.該應用定時更新日誌目錄,有兩個日誌檔案 fromclient.log 記錄接收請求,fromserver.log記錄接收服務端返回.出現問題時一般是fromclient.log日誌在更新,但是fromserver.log...

搭建python的web開發環境 windows下

本文以windows xp windows 2003為例,介紹windows環境下python web開發環境的安裝配置 1.安裝apache 2.安裝python 3.安裝mod python mod python 3.3.1.win32 py2.5 apache2.2.exe 安裝過程中安裝程式...