#!/usr/bin/evn python # -*- coding:utf-8 -*- #Author = ‘Jun‘ """ 可以同时监控多个进程 """ import sys import re import os import linecache try: import psutil except ImportError as e: print e sys.exit() def process(processname): plist = [] getplist = psutil.process_iter() for pro in getplist: p = str(pro) re1 = re.compile(processname, re.I) if re1.search(p): plist.append(str(p).split(‘pid=‘)[1].split(‘,‘)[0]) return plist def file_size_check(logfile): if os.path.isfile(logfile): if os.path.getsize(logfile) > 2700000: f = open(logfile, ‘w‘) f.write("") f.close() def main(pname, filename, pnumber=1): readline = pnumber * 2 logfile = os.path.dirname(os.path.realpath(__file__)) + os.sep + filename file_size_check(logfile) pidlist = process(pname) chpidlist = [] lines = linecache.getlines(logfile)[-readline:] taillines = [line.strip(‘\n‘) for line in lines] pl = [p for p in pidlist if taillines.count(p) == 2] f = open(logfile, ‘a‘) if len(taillines) < readline: print "check log less than %s line" % readline [f.write(p + ‘\n‘) for p in pidlist] f.close() sys.exit(0) elif len(pl) == pnumber: print "check %s process ok, pidis :" % pname, pidlist [f.write(p + ‘\n‘) for p in pidlist] f.close() sys.exit(0) else: for p in pidlist: if taillines.count(p) != 2: chpidlist.append(p) print "check %s process is change, change pid is :::" % pname, chpidlist [f.write(p + ‘\n‘) for p in pidlist] f.close() sys.exit(1) if __name__ == ‘__main__‘: if len(sys.argv) == 3: proname = sys.argv[1] pnum = int(sys.argv[2]) logf = "check_%s_pid" % proname main(proname, logf, pnum) elif len(sys.argv) == 2: proname = sys.argv[1] logf = "check_%s_pid" % proname main(proname, logf) else: print "Usage:%s processname [processnumber] " % sys.argv[0] sys.exit(2)
本文出自 “拥抱开源” 博客,请务必保留此出处http://junit.blog.51cto.com/9897514/1643598
原文地址:http://junit.blog.51cto.com/9897514/1643598