python实现简易内存监控
程序员文章站
2022-05-17 21:26:18
本例主要功能:每隔3秒获取系统内存,当内存超过设定的警报值时,获取所有进程占用内存并发出警报声。内存值和所有进程占用内存记入log,log文件按天命名。
1 获取cpu、...
本例主要功能:每隔3秒获取系统内存,当内存超过设定的警报值时,获取所有进程占用内存并发出警报声。内存值和所有进程占用内存记入log,log文件按天命名。
1 获取cpu、内存、进程信息
利用wmi
简单说明下,wmi的全称是windows management instrumentation,即windows管理规范。它是windows操作系统上管理数据和操作的基础设施。我们可以使用wmi脚本或者应用自动化管理任务等。
安装模块
wmi下载地址
win32com下载地址:
学会使用wmi
不错的
获取cpu、内存、磁盘
def getsysinfo(wmiservice = none): result = {} if wmiservice == none: wmiservice = wmi.wmi() # cpu for cpu in wmiservice.win32_processor(): timestamp = time.strftime('%a, %d %b %y %h:%m:%s', time.localtime()) result['cpupercent'] = cpu.loadpercentage # memory cs = wmiservice.win32_computersystem() os = wmiservice.win32_operatingsystem() result['memtotal'] = int(int(cs[0].totalphysicalmemory)/1024/1024) result['memfree'] = int(int(os[0].freephysicalmemory)/1024) result['mempercent']=result['memfree'] * 100 /result['memtotal'] #disk result['disktotal'] = 0 result['diskfree'] = 0 for disk in wmiservice.win32_logicaldisk(drivetype=3): result['disktotal'] += int(disk.size) result['diskfree'] += int(disk.freespace) result['disktotal'] = int(result['disktotal']/1024/1024) result['diskfree'] = int(result['diskfree']/1024/1024) return result
获取所有进程占用内存
def getallprocessinfo(mywmi = none): """取出全部进程的进程名,进程id,进程实际内存, 虚拟内存,cpu使用率 """ allprocesslist = [] allprocess = mywmi.execquery("select * from win32_perfformatteddata_perfproc_process") #print (allprocess.count) for j in allprocess: #print j.properties_("percentprivilegedtime").__int__() ##print j.properties_("name").__str__()+" "+j.properties_("idprocess").__str__()+" "+j.properties_("percentprivilegedtime").__str__() #for pro in j.properties_: # print (pro.name) #break name = j.properties_("name").__str__() if name != "_total" and name !="idle": pid = j.properties_("idprocess").__str__() percentprivilegedtime = j.properties_("percentprivilegedtime").__int__() workingsetprivate = j.properties_("workingsetprivate").__int__()/1024 workingset = j.properties_("workingset").__int__()/1024 allprocesslist.append([name, pid, workingsetprivate, workingset, percentprivilegedtime]) return allprocesslist
也可以用psutil
import psutil,time from operator import itemgetter, attrgetter def getprocessinfo(p): """取出指定进程占用的进程名,进程id,进程实际内存, 虚拟内存,cpu使用率 """ try: cpu = int(p.cpu_percent(interval=0)) memory = p.memory_info() rss = memory.rss/1024 vms = memory.vms/1024 name = p.name() pid = p.pid except psutil.error: name = "closed_process" pid = 0 rss = 0 vms = 0 cpu = 0 #return [name.upper(), pid, rss, vms] return [name, pid, vms, rss, cpu] def getallprocessinfo(): """取出全部进程的进程名,进程id,进程实际内存, 虚拟内存,cpu使用率 """ instances = [] all_processes = list(psutil.process_iter()) for proc in all_processes: proc.cpu_percent(interval=0) #此处sleep1秒是取正确取出cpu使用率的重点 time.sleep(1) for proc in all_processes: instances.append(getprocessinfo(proc)) return instances if __name__ == '__main__': processinfolist = getallprocessinfo() processinfolist.sort(key=itemgetter(2), reverse=true) for p in processinfolist: print(p)
2. 保存log
配置config文件
[loggers] keys=example01 [logger_example01] handlers=hand04 [handlers] keys=hand04 [handler_hand04] class=handlers.timedrotatingfilehandler level=debug formatter=form01 args=('./logs/monitor.log', 'd', 1, 7) [formatters] keys=form01,form02 [formatter_form01] format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s datefmt=%y-%m-%d %h:%m:%s
记录log
import logging import logging.config logger.info("message") logger.warning("message") logger.error("message")
3. 完整代码
文件夹结构:
maintain
–monitor
—-logs
—-logger.conf
—-monitor.py
–packages
—-init.py
—-processinfo.py
—-sysinfo.py
monitor
import wmi import time import winsound import logging import logging.config from operator import itemgetter, attrgetter from os import path import packages.sysinfo #使用wmi #import packages.processinfo #使用 #def showprocessinfo(): # processinfolist = packages.processinfo.getallprocessinfo() # processinfolist.sort(key=itemgetter(2), reverse=true) # for p in processinfolist: # logger.info(p) def showprocessinfo(wmiservice = none): processinfolist = packages.sysinfo.getallprocessinfo(wmiservice) processinfolist.sort(key=itemgetter(2), reverse=true) for p in processinfolist: logger.info(p) if __name__ == '__main__': memperworningline = 50 mempererrorline = 20 erroralertcount = 10 processinfocount = 10 counterprocessinfo = processinfocount print("memory monitor start!") log_file_path = path.join(path.dirname(path.abspath(__file__)), 'logger.conf') #print(log_file_path) logging.config.fileconfig(log_file_path) logger = logging.getlogger("example01") wmiservice = wmi.wmi() while true: mempercent = int(packages.sysinfo.getsysinfo(wmiservice)['mempercent']) strmempercent = 'freememory: ' + str(mempercent) + '%' if(mempercent < mempererrorline): logger.error(strmempercent) #processinfolist counterprocessinfo+=1 if(counterprocessinfo >= processinfocount): showprocessinfo(wmiservice) counterprocessinfo = 0 #alert counter = 1 while counter <= erroralertcount: winsound.beep(2080, 100) time.sleep(0.1) counter += 1 elif(mempercent < memperworningline): logger.warning(strmempercent) #processinfolist counterprocessinfo+=1 if(counterprocessinfo >= processinfocount): showprocessinfo(wmiservice) counterprocessinfo = 0 #alert winsound.beep(2015, 2000) else: logger.info(strmempercent) time.sleep(3)
sysinfo
# -*- coding: utf-8 -*- import wmi import os import sys import platform import time import win32api import win32com from win32com.client import getobject from operator import itemgetter, attrgetter def getsysinfo(wmiservice = none): result = {} if wmiservice == none: wmiservice = wmi.wmi() # cpu for cpu in wmiservice.win32_processor(): timestamp = time.strftime('%a, %d %b %y %h:%m:%s', time.localtime()) result['cpupercent'] = cpu.loadpercentage # memory cs = wmiservice.win32_computersystem() os = wmiservice.win32_operatingsystem() result['memtotal'] = int(int(cs[0].totalphysicalmemory)/1024/1024) result['memfree'] = int(int(os[0].freephysicalmemory)/1024) result['mempercent']=result['memfree'] * 100 /result['memtotal'] #disk result['disktotal'] = 0 result['diskfree'] = 0 for disk in wmiservice.win32_logicaldisk(drivetype=3): result['disktotal'] += int(disk.size) result['diskfree'] += int(disk.freespace) result['disktotal'] = int(result['disktotal']/1024/1024) result['diskfree'] = int(result['diskfree']/1024/1024) return result def sys_version(): c = wmi.wmi () #获取操作系统版本 for sys in c.win32_operatingsystem(): print ("version:%s" % sys.caption.encode("utf8"),"vernum:%s" % sys.buildnumber) print (sys.osarchitecture.encode("utf8"))#系统是32位还是64位的 print (sys.numberofprocesses) #当前系统运行的进程总数 def cpu_mem(): c = wmi.wmi () #cpu类型和内存 for processor in c.win32_processor(): #print "processor id: %s" % processor.deviceid print ("process name: %s" % processor.name.strip() ) for memory in c.win32_physicalmemory(): print ("memory capacity: %.fmb" %(int(memory.capacity)/1048576)) def cpu_use(): #5s取一次cpu的使用率 c = wmi.wmi() while true: for cpu in c.win32_processor(): timestamp = time.strftime('%a, %d %b %y %h:%m:%s', time.localtime()) print ('%s | utilization: %s: %d %%' % (timestamp, cpu.deviceid, cpu.loadpercentage)) time.sleep(5) def disk(): c = wmi.wmi () #获取硬盘分区 for physical_disk in c.win32_diskdrive (): for partition in physical_disk.associators ("win32_diskdrivetodiskpartition"): for logical_disk in partition.associators ("win32_logicaldisktopartition"): print (physical_disk.caption.encode("utf8"), partition.caption.encode("utf8"), logical_disk.caption) #获取硬盘使用百分情况 for disk in c.win32_logicaldisk (drivetype=3): print (disk.caption, "%0.2f%% free" % (100.0 * long (disk.freespace) / long (disk.size))) def network(): c = wmi.wmi () #获取mac和ip地址 for interface in c.win32_networkadapterconfiguration (ipenabled=1): print ("mac: %s" % interface.macaddress ) for ip_address in interface.ipaddress: print ("ip_add: %s" % ip_address ) print #获取自启动程序的位置 for s in c.win32_startupcommand (): print ("[%s] %s <%s>" % (s.location.encode("utf8"), s.caption.encode("utf8"), s.command.encode("utf8"))) #获取当前运行的进程 for process in c.win32_process (): print (process.processid, process.name) def getallprocessinfo(mywmi = none): """取出全部进程的进程名,进程id,内存(专有工作集), 工作集 """ allprocesslist = [] allprocess = mywmi.execquery("select * from win32_perfformatteddata_perfproc_process") #print (allprocess.count) for j in allprocess: #print j.properties_("percentprivilegedtime").__int__() ##print j.properties_("name").__str__()+" "+j.properties_("idprocess").__str__()+" "+j.properties_("percentprivilegedtime").__str__() #for pro in j.properties_: # print (pro.name) #break name = j.properties_("name").__str__() if name != "_total" and name !="idle": pid = j.properties_("idprocess").__str__() percentprivilegedtime = j.properties_("percentprivilegedtime").__int__() workingsetprivate = j.properties_("workingsetprivate").__int__()/1024 workingset = j.properties_("workingset").__int__()/1024 allprocesslist.append([name, pid, workingsetprivate, workingset, percentprivilegedtime]) # allprocess = mywmi.execquery("select * from win32_process") # for i in allprocess: # name = str(i.properties_("name")) # processid = int(i.properties_("processid")) # workingsetsize = int(i.properties_("workingsetsize"))/1024 # #virtualsize = int(i.properties_("virtualsize"))/1024 # peakworkingsetsize = int(i.properties_("peakworkingsetsize"))/1024 # creationdate = str(i.properties_("creationdate")) # allprocesslist.append([name, processid, workingsetsize, peakworkingsetsize, creationdate]) return allprocesslist #def main(): #sys_version() #cpu_mem() #disk() #network() #cpu_use() if __name__ == '__main__': #mywmi = getobject("winmgmts:") mywmi = wmi.wmi() processinfolist = getallprocessinfo(mywmi) processinfolist.sort(key=itemgetter(2), reverse=true) for processinfo in processinfolist: print(processinfo)
processinfo
import psutil,time from operator import itemgetter, attrgetter def getprocessinfo(p): """取出指定进程占用的进程名,进程id,进程实际内存, 虚拟内存,cpu使用率 """ try: cpu = int(p.cpu_percent(interval=0)) memory = p.memory_info() rss = memory.rss/1024 vms = memory.vms/1024 name = p.name() pid = p.pid except psutil.error: name = "closed_process" pid = 0 rss = 0 vms = 0 cpu = 0 #return [name.upper(), pid, rss, vms] return [name, pid, vms, rss, cpu] def getallprocessinfo(): """取出全部进程的进程名,进程id,进程实际内存, 虚拟内存,cpu使用率 """ instances = [] all_processes = list(psutil.process_iter()) for proc in all_processes: proc.cpu_percent(interval=0) #此处sleep1秒是取正确取出cpu使用率的重点 time.sleep(1) for proc in all_processes: instances.append(getprocessinfo(proc)) return instances if __name__ == '__main__': processinfolist = getallprocessinfo() processinfolist.sort(key=itemgetter(2), reverse=true) for p in processinfolist: print(p)
logger
#logger.conf ############################################### [loggers] keys=root,example01,example02 [logger_root] level=debug handlers=hand01,hand02 [logger_example01] handlers=hand01,hand04 qualname=example01 propagate=0 [logger_example02] handlers=hand01,hand03 qualname=example02 propagate=0 ############################################### [handlers] keys=hand01,hand02,hand03,hand04 [handler_hand01] class=streamhandler level=info formatter=form02 args=(sys.stderr,) [handler_hand02] class=filehandler level=debug formatter=form01 args=('myapp.log', 'a') [handler_hand03] class=handlers.rotatingfilehandler level=info formatter=form02 args=('myapp.log', 'a', 10*1024*1024, 5) [handler_hand04] class=handlers.timedrotatingfilehandler level=debug formatter=form01 args=('./logs/monitor.log', 'd', 1, 7) ############################################### [formatters] keys=form01,form02 [formatter_form01] format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s datefmt=%y-%m-%d %h:%m:%s [formatter_form02] format=%(asctime)-12s: %(levelname)-8s %(message)s datefmt=%y-%m-%d %h:%m:%s
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Oculus创始人:苹果Mac性能差 所以暂不支持VR
下一篇: List Leaves