代碼講解Python對(duì)Windows服務(wù)進(jìn)行監(jiān)控
我們首先來(lái)看下python的全部代碼,大家可以直接復(fù)制后測(cè)試:
#-*- encoding: utf-8 -*-
import logging
import wmi
import os
import time
from ConfigParser import ConfigParser
import smtplib
from email.mime.text import MIMEText
import socket
from datetime import datetime
import re
import sys
import time
import string
import psutil
import threading
from threading import Timer
import logging
# 創(chuàng)建一個(gè)logger
logger = logging.getLogger('Monitor')
logger.setLevel(logging.DEBUG)
# 創(chuàng)建一個(gè)handler,用于寫入日志文件
fh = logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
reload(sys) # Python2.5 初始化后會(huì)刪除 sys.setdefaultencoding 這個(gè)方法,我們需要重新載入
sys.setdefaultencoding('utf-8')
def send_mail(to_list,sub,content):
CONFIGFILE = 'config.ini'
config = ConfigParser()
config.read(CONFIGFILE)
mail_host=config.get('Mail','mail_host') #使用的郵箱的smtp服務(wù)器地址,這里是163的smtp地址
mail_user=config.get('Mail','mail_user') #用戶名
mail_pass=config.get('Mail','mail_pass') #密碼
mail_postfix=config.get('Mail','mail_postfix') #郵箱的后綴,網(wǎng)易就是163.com
me=sub+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list) #將收件人列表以‘;'分隔
try:
server = smtplib.SMTP()
server.connect(mail_host) #連接服務(wù)器
server.login(mail_user,mail_pass) #登錄操作
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
logger.info(str(e))
return False
#讀取配置文件中的進(jìn)程名和系統(tǒng)路徑,這2個(gè)參數(shù)都可以在配置文件中修改
ProList = []
#定義一個(gè)列表
c = wmi.WMI()
#獲取進(jìn)程所用內(nèi)存
def countProcessMemoey(processName):
try:
CONFIGFILE = 'config.ini'
config = ConfigParser()
config.read(CONFIGFILE)
pattern = re.compile(r'([^\s]+)\s+(\d+)\s.*\s([^\s]+\sK)')
cmd = 'tasklist /fi "imagename eq ' + processName + '"' + ' | findstr.exe ' + processName
result = os.popen(cmd).read()
resultList = result.split("\n")
totalMem = 0.0
totalCpu = 0.0
print "*" * 80
for srcLine in resultList:
srcLine = "".join(srcLine.split('\n'))
if len(srcLine) == 0:
break
m = pattern.search(srcLine)
if m == None:
continue
#由于是查看python進(jìn)程所占內(nèi)存,因此通過(guò)pid將本程序過(guò)濾掉
if str(os.getpid()) == m.group(2):
continue
p = psutil.Process(int(m.group(2)))
cpu = p.cpu_percent(interval=1)
ori_mem = m.group(3).replace(',','')
ori_mem = ori_mem.replace(' K','')
ori_mem = ori_mem.replace(r'\sK','')
memEach = string.atoi(ori_mem)
totalMem += (memEach * 1.0 /1024)
totalCpu += cpu
print 'ProcessName:'+ m.group(1) + '\tPID:' + m.group(2) + '\tmemory size:%.2f'% (memEach * 1.0 /1024), 'M' + ' CPU:'+str(cpu)+'%'
print 'ProcessName:'+ m.group(1)+' TotalMemory:'+str(totalMem)+'M'+' totalCPU:'+str(totalCpu)+'%'
logger.info('ProcessName:'+ m.group(1)+' TotalMemory:'+str(totalMem)+'M'+' totalCPU:'+str(totalCpu)+'%')
print "*" * 80
if totalMem> float(config.get('MonitorProcessValue','Memory')):
print 'Memory Exceed!'
IP = socket.gethostbyname(socket.gethostname())
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
subject = IP +' ' + processName + '內(nèi)存使用量過(guò)高!'
content = now + ' ' + IP +' ' + processName + '內(nèi)存使用量過(guò)高,達(dá)到'+str(totalMem) +'M\n請(qǐng)盡快處理!'
logger.info(processName +'內(nèi)存使用量過(guò)高,達(dá)到'+str(totalMem) +'M')
send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content)
if totalCpu > float(config.get('MonitorProcessValue','CPU')):
print 'CPU Exceed!'
IP = socket.gethostbyname(socket.gethostname())
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
subject = IP +' ' + processName + 'CPU使用率過(guò)高!'
content = now + ' ' + IP +' ' + processName + 'CPU使用率過(guò)高,達(dá)到'+str(totalCpu)+'%\n請(qǐng)盡快處理!'
logger.info(processName +'CPU使用率過(guò)高,達(dá)到'+str(totalMem) +'M')
send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content)
except Exception, e:
print str(e)
logger.info(str(e))
#判斷進(jìn)程是否存活
def judgeIfAlive(ProgramPath,ProcessName):
try:
print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
for process in c.Win32_Process():
ProList.append(str(process.Name))
#把所有任務(wù)管理器中的進(jìn)程名添加到列表
if ProcessName in ProList:
countProcessMemoey(ProcessName)
#判斷進(jìn)程名是否在列表中,如果是True,則所監(jiān)控的服務(wù)正在 運(yùn)行狀態(tài),
#打印服務(wù)正常運(yùn)行
print ''
print ProcessName+" Server is running..."
print ''
logger.info(ProcessName+" Server is running...")
else:
#如果進(jìn)程名不在列表中,即監(jiān)控的服務(wù)掛了,則在log文件下記錄日志
#日志文件名是以年月日為文件名
IP = socket.gethostbyname(socket.gethostname())
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
subject = IP +' ' + ProcessName + '已停止運(yùn)行!'
logger.info( ProcessName + '已停止運(yùn)行!')
content = now + ' ' + IP +' ' + ProcessName + '已停止運(yùn)行!' +'\n請(qǐng)盡快處理!'
send_mail(['sunwei_work@163.com','sunweiworkplace@gmail.com'],subject, content)
print ProcessName+' Server is not running...'
#打印服務(wù)狀態(tài)
logger.info('\n'+'Server is not running,Begining to Restart Server...'+'\n'+(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()) +'\n'))
#寫入時(shí)間和服務(wù)狀態(tài)到日志文件中
os.startfile(ProgramPath)
#調(diào)用服務(wù)重啟
logger.info(ProcessName+'Restart Server Success...'+'\n'+time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()))
print ProcessName+'Restart Server Success...'
print time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime())
del ProList[:]
#清空列表,否則列表會(huì)不停的添加進(jìn)程名,會(huì)占用系統(tǒng)資源
except Exception, e:
print str(e)
logger.info(str(e))
def startMonitor(ProgramPathDict,ProcessNameDict) :
for i in range(0,len(ProcessNameDict)):
judgeIfAlive(ProgramPathDict[i],ProcessNameDict[i])
if __name__=="__main__" :
CONFIGFILE = 'config.ini'
config = ConfigParser()
config.read(CONFIGFILE)
ProgramPathDict = config.get('MonitorProgramPath','ProgramPath').split("|")
ProcessNameDict = config.get('MonitorProcessName','ProcessName').split("|")
while True:
startMonitor(ProgramPathDict,ProcessNameDict)
time.sleep(int(config.get('MonitorProcessValue','Time')))
所用配置文件config.ini
[MonitorProgramPath] ProgramPath: C:\Windows\System32\services.exe|C:\Program Files (x86)\Google\Chrome\Application\chrome.exe [MonitorProcessName] ProcessName: services.exe|chrome.exe [MonitorProcessValue] Memory:5000.0 CPU:50.0 Time:60 [Mail] mail_host: smtp.163.com mail_user: mail_pass: mail_postfix: 163.com
以上就是本次小編整理的關(guān)于Python對(duì)Windows服務(wù)進(jìn)行監(jiān)控的全部代碼內(nèi)容,感謝你對(duì)腳本之家的支持。
- python使用Windows的wmic命令監(jiān)控文件運(yùn)行狀況,如有異常發(fā)送郵件報(bào)警
- Python3監(jiān)控windows,linux系統(tǒng)的CPU、硬盤、內(nèi)存使用率和各個(gè)端口的開(kāi)啟情況詳細(xì)代碼實(shí)例
- python3實(shí)現(xiàn)windows下同名進(jìn)程監(jiān)控
- python使用wmi模塊獲取windows下的系統(tǒng)信息 監(jiān)控系統(tǒng)
- Windows環(huán)境中Python應(yīng)用服務(wù)自啟動(dòng)及其監(jiān)控問(wèn)題
相關(guān)文章
python使用if語(yǔ)句實(shí)現(xiàn)一個(gè)猜拳游戲詳解
這篇文章主要介紹了python使用if語(yǔ)句實(shí)現(xiàn)一個(gè)猜拳游戲詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Python使用Phantomjs截屏網(wǎng)頁(yè)的方法
今天小編就為大家分享一篇Python使用Phantomjs截屏網(wǎng)頁(yè)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Python tkinter的grid布局及Text動(dòng)態(tài)顯示方法
今天小編就為大家分享一篇Python tkinter的grid布局及Text動(dòng)態(tài)顯示方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
Python實(shí)現(xiàn)批量讀取word中表格信息的方法
這篇文章主要介紹了Python實(shí)現(xiàn)批量讀取word中表格信息的方法,可實(shí)現(xiàn)針對(duì)word文檔的讀取功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
使用卷積神經(jīng)網(wǎng)絡(luò)(CNN)做人臉識(shí)別的示例代碼
這篇文章主要介紹了使用卷積神經(jīng)網(wǎng)絡(luò)(CNN)做人臉識(shí)別的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
python實(shí)現(xiàn)同時(shí)給多個(gè)變量賦值的方法
這篇文章主要介紹了python實(shí)現(xiàn)同時(shí)給多個(gè)變量賦值的方法,涉及Python中變量賦值的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04

