监控脚本
#!/usr/bin/env python
import psutil, time
from threading import Timer
def getProcessInfo(p):
global mem_percent,Path,Cmd
try:
cpu = int(p.cpu_percent(interval=0.1))
mem_percent = int(p.memory_percent())
# rss,vms,shared,text,lib,data,dirty = p.memory_info()
name = p.name()
pid = p.pid
Path = p.cwd()
Cmd = p.cmdline()
except psutil.NoSuchProcess, e:
name = "Closed_Process"
pid = 0
cpu = 0
return [name, pid, cpu, mem_percent, Path, Cmd]
def getAllProcessInfo():
instances1 = []
instances2 = []
all_processes = list(psutil.process_iter())
for proc in all_processes:
info = getProcessInfo(proc)
if info[3] > 40:
instances1.append(getProcessInfo(proc))
if info[2] > 70:
instances2.append(getProcessInfo(proc))
return instances1,instances2
def main():
obj1,obj2 = getAllProcessInfo()
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), obj1,obj2
if obj1 != []:
f1 = open('/tmp/memory_monitor.log', 'a')
for data1 in obj1:
f1.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + ' ')
f1.write(str(data1) + '\n')
f1.close()
if obj2 != []:
f2 = open('/tmp/cpu_monitor.log', 'a')
for data2 in obj2:
f2.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + ' ')
f2.write(str(data2) + '\n')
f2.close()
t = Timer(14, main)
t.start()
if __name__ == '__main__':
main()