inux下监控某进程的详细信息并持续写入xml中(python)
时间:2011-03-09 来源:muhuohacker
5、程序默然情况下是5分钟写一次数据,也可以让用户通过第二个参数进行自定义,同时当用户输入-h的时候显示帮助信息。
作者:muhuohacker
# -*- coding:utf-8 -*-
import os,time
import sys
import psutil
import codecs
from xml.dom import *
import xml.dom.minidom as minidom
import xml.etree.ElementTree as ET
class CreateCovXml(): #创建xml的类
def __init__(self,cov_xml_path):
self.__cov_path=cov_xml_path
self.__dom=None
self.__root=None
def _covert_code(self, msg):
return msg
def __create_new_node(self, node_name, node_text = None): #创建节点
if self.__dom == None:
raise Exception,'error'
if None == node_text:
return self.__dom.createElement(self._covert_code(node_name))
else:
newNode = self.__dom.createElement(self._covert_code(node_name))
newText = self.__dom.createTextNode(self._covert_code(node_text))
newNode.appendChild(newText)
return newNode
def begin_cov(self):
try:
impl = minidom.getDOMImplementation()
self.__dom = impl.createDocument(None, u'coverages', None)
self.__root = self.__dom.documentElement
except:
traceback.print_exc()
raise Exception
def add_cov(self, name, pid, rms, vms, cpu, rchar,wchar,read_bytes,write_bytes,pid_tim):
if self.__root == None:
raise Exception
name_node = self.__create_new_node("Name", name)
pid_node = self.__create_new_node("Pid", pid)
rms_line_node = self.__create_new_node("Rms", rms)
vms_line_node = self.__create_new_node("Vms", vms)
cpu_line_node = self.__create_new_node("Cpu", cpu)
cover_line_node = self.__create_new_node("Rchar", rchar)
cover_wchar= self.__create_new_node("Wchar", wchar)
cover_read_bytes = self.__create_new_node("Read_bytes", read_bytes)
cover_write_bytes = self.__create_new_node("Write_bytes", write_bytes)
nopid_time= self.__create_new_node("Time", pid_tim)
new_coverage_node = self.__create_new_node("ProcessInfo")
new_coverage_node.appendChild(name_node)
new_coverage_node.appendChild(pid_node)
new_coverage_node.appendChild(rms_line_node)
new_coverage_node.appendChild(vms_line_node)
new_coverage_node.appendChild(cpu_line_node)
new_coverage_node.appendChild(cover_line_node)
new_coverage_node.appendChild(cover_wchar)
new_coverage_node.appendChild(cover_read_bytes)
new_coverage_node.appendChild(cover_write_bytes)
new_coverage_node.appendChild(nopid_time)
self.__root.appendChild(new_coverage_node)
def end_cov(self):
try:
f = open(self.__cov_path, 'wb')
writer = codecs.lookup('utf-8')[3](f)
self.__dom.writexml(writer, encoding='utf-8')
writer.close()
f.close()
return True
except Exception, err:
traceback.print_exc()
raise Exception
def getProcessInfo(p): #得到进程的 pid rms vms等信息
try:
cpu=int(p.get_cpu_percent(interval=0))
rms, vms = p.get_memory_info()
name = p.name
pid = p.pid
except psutil.error.NoSuchProcess, e:
name ="error not get name"
pid = 0
rms = 0
vms = 0
cpu = 0
return [name.upper(),pid,rms,vms,cpu]
def getProcessIo(pid): #得到进程的io信息
f=open('/proc/%d/io'% pid)
a=[]
lines=f.readlines()
for line in lines:
m=line.rstrip().split(':')
a.append(m[1])
f.close()
return a
def shuchu(input,ti=5*60):
id=[]
for p in psutil.process_iter():
if p.name.upper()==input.upper():
id.append(p.pid)
if os.path.isfile('/tmp/cpu2.xml')==False:
test = CreateCovXml('/tmp/cpu2.xml')
test.begin_cov()
while True:
for p in psutil.process_iter():
if p.name.upper()==input.upper():
id.append(p.pid)
for i in id:
p=psutil.Process(i)
prcIo=getProcessIo(i)
prcInf=getProcessInfo(p)
s=time.strftime('%Y-%m-%d %H-%M-%S',time.localtime(time.time()))
test.add_cov(
name = prcInf[0],
pid = str(prcInf[1]),
rms = str(prcInf[2]),
vms= str(prcInf[3]),
cpu = str(prcInf[4]),
rchar=str(prcIo[0]),
wchar=str(prcIo[1]),
read_bytes=str(prcIo[4]),
write_bytes=str(prcIo[5]),
pid_tim = s
)
time.sleep(ti)
test.end_cov()
#print 'endl'
else:
while True:
for p in psutil.process_iter():
if p.name.upper()==input.upper():
id.append(p.pid)
for i in id:
p=psutil.Process(i)
prcIo=getProcessIo(i)
prcInf=getProcessInfo(p)
addWriteXml(prcInf,prcIo)
time.sleep(ti)
def addWriteXml(prcInf,prcIo): #追加xml数据
xmlHandle=ET.parse('/tmp/cpu2.xml')
root=xmlHandle.getroot()
processInfo=ET.SubElement(root,'ProcessInfo')
nameE=ET.Element('Name')
nameE.text=prcInf[0]
processInfo.append(nameE)
pidE=ET.Element('Pid')
pidE.text=str(prcInf[1])
processInfo.append(pidE)
rmsE=ET.Element('Rms')
rmsE.text=str(prcInf[2])
processInfo.append(rmsE)
vmsE=ET.Element('Vms')
vmsE.text=str(prcInf[3])
processInfo.append(vmsE)
cpuE=ET.Element('Cpu')
cpuE.text=str(prcInf[4])
processInfo.append(cpuE)
rcharE=ET.Element('Rchar')
rcharE.text=str(prcIo[0])
processInfo.append(rcharE)
wcharE=ET.Element('Wchar')
wcharE.text=str(prcIo[1])
processInfo.append(wcharE)
read_bytesE=ET.Element('Read_bytes')
read_bytesE.text=str(prcIo[4])
processInfo.append(read_bytesE)
write_bytesE=ET.Element('Write_bytes')
write_bytesE.text=str(prcIo[5])
processInfo.append(write_bytesE)
pid_tim=ET.Element('Time')
pid_tim.text=time.strftime('%Y-%m-%d %H-%M-%S',time.localtime(time.time()))
processInfo.append(pid_tim)
xmlHandle.write('/tmp/cpu2.xml')
def help_cpu():
print """#########################
-h list help information.
Executive Order python cpu.py name.exe
Executive Order python cpu.py name.exe Time
time default is 300s
#######################################
"""
if __name__=="__main__":
sum=len(sys.argv)
try:
if sum<2:
help_cpu()
elif sum==2:
input=sys.argv[1]
if input=='-h':
help_cpu()
else:
shuchu(input)
elif sum==3:
input=sys.argv[1]
input_Time=int(sys.argv[2])
shuchu(input,input_Time)
except KeyboardInterrupt:
print 'stopped'