监控linux的系统资源和自定义进程的cpu 内存占用。
Posted 北风之神0509
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了监控linux的系统资源和自定义进程的cpu 内存占用。相关的知识,希望对你有一定的参考价值。
1 #coding=utf8 2 import time 3 import psutil 4 from pprint import pprint 5 6 from logger_until import LoggerUntil 7 logger = LoggerUntil(name="Monitor").getlog(logfilename=\'Monitor.log\', loglevel=2, add_StreamHandler=1) 8 9 need_monitor_procces_names = [ 10 \'touna0627.py\', 11 \'dailiip.py\', 12 \'redis-server\', 13 \'mongod\', 14 ] 15 16 17 class Monitor(object): 18 def __init__(self): 19 self.specified_process_list = self.get_specified_process() 20 21 def print_all_cmd_lines(self): 22 pass 23 24 def get_specified_process(self): 25 all_pids = psutil.pids() 26 process_list = [] 27 for pid in all_pids: 28 p = psutil.Process(pid) 29 p_cmdline = p.cmdline() 30 for argx in p_cmdline: 31 for name in need_monitor_procces_names: 32 if argx.find(name) > -1: 33 if p.status() != \'stopped\': 34 process_list.append(p) 35 36 p_pid_set = set() 37 process_list2 = [] 38 for p in process_list : 39 if p.pid not in p_pid_set: 40 process_list2.append(p) 41 p_pid_set.add(p.pid) 42 return process_list2 43 44 @staticmethod 45 def monitor_system(): 46 psutil.cpu_percent() 47 time.sleep(1) 48 mem = psutil.virtual_memory() 49 50 mem_total = mem.total/1000000 51 mem_available =mem.available/1000000 52 mem_percent = str(mem.percent) + \'%\' 53 54 cpu_count = psutil.cpu_count() 55 cpu_percent = psutil.cpu_percent() 56 57 msg = \'本机总内存是:{0}M , 本机可用内存是:{1}M, 本机内存使用率是:{2}, 本机cpu核数是:{3}, 本机cpu使用率是:{4}\'.format(mem_total, mem_available, mem_percent,cpu_count,cpu_percent) 58 logger.info(msg) 59 60 61 def monitor_specified_process(self): 62 for p in self.specified_process_list: 63 p.cpu_percent(None) 64 time.sleep(1) 65 for p in self.specified_process_list: 66 #p = psutil.Process(0) 67 """:type :psutil.Process""" 68 cmdline_str =\' \'.join(p.cmdline()).ljust(60,\' \') 69 p_cpu_percent_str = str(round(p.cpu_percent(),2)) +\'%\' 70 p_memory_percent_str = str(round(p.memory_percent(),2)) + \'%\' 71 p_strated_time = time.strftime(\'%Y-%m-%d %H:%M:%S\',time.localtime(p.create_time())) 72 p_pid_str = str(p.pid) 73 print p.status(),str(p.status()) 74 75 msg = \'进程\' + cmdline_str + \' 的pid是:\' + p_pid_str +\' cpu使用率是:\' + p_cpu_percent_str + \' 内存使用率是:\' + p_memory_percent_str \\ 76 +\' 进程的启动时间是:\' + p_strated_time 77 78 logger.info(msg) 79 80 81 def monitoring(): 82 while 1: 83 monitor = Monitor() 84 monitor.monitor_system() 85 monitor.monitor_specified_process() 86 87 time.sleep(10) 88 89 90 if __name__ == "__main__": 91 monitoring()
监控linux的系统资源和自定义进程。
填入要监控的进程 ,只要ps -ef的command中包含need_monitor_procces_names中的字符串就可以,也可以监控java njinx。
以上是关于监控linux的系统资源和自定义进程的cpu 内存占用。的主要内容,如果未能解决你的问题,请参考以下文章