python监控进程状态,记录重启时间及进程号的实例


Posted in Python onJuly 15, 2019

本脚本为本人在性能测试过程中编写,用于对进程状态的监控,也可以用于日常的监控,适用性一般,扩展性还行

# -*- coding: UTF-8 -*-
# author=baird_xiang
import os
import time
import re
import copy

nginxRestart_num= -1
nginxReload_num= -1
logSender_num= -1
es_num= -1
nginxParent_pid=[]
nginxChild_pid=[]
logSender_pid=[]
es_pid=[]

nginxRestart_time =[]
nginxReload_time=[]
logSender_time=[]
es_time=[]
def get_restart(thread_name):
  global nginxRestart_num,nginxReload_num,logSender_num,es_num
  while True:
    try:
      for i in thread_name:
        if i=='nginx_restart':
          nP_pid = os.popen("sudo pgrep -lo nginx |grep -v grep|awk '{print $1}'").read()
          nP_time = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==1{print $9}'").read()
          nginx_path = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==1{print $11}'").read()
          date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
          nP_time_now = date + '-' + nP_time.split('\n')[0] 
          if nP_pid and (nP_pid not in nginxParent_pid) and (nginx_path=='/usr/sbin/nginx\n'):
              nginxParent_pid.append(nP_pid)
              nginxRestart_num=nginxRestart_num+1
          # if nP_time and (nP_time_now not in nginxRestart_time) and (color!='-c\n'):
              nginxRestart_time.append(nP_time_now)    
      
        elif i=='nginx_reload':
          nR_pid = os.popen("sudo pgrep -ln nginx|grep -v grep |awk '{print $1}'").read()
          nR_time = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==2{print $9}'").read()
          nginx_path = os.popen("sudo ps aux|grep nginx |grep -v grep|awk 'NR==1{print $11}'").read()
          date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
          nR_time_now = date + '-' + nR_time.split('\n')[0]
          if nR_pid and (nR_pid not in nginxChild_pid) and (nginx_path=='/usr/sbin/nginx\n') :
              nginxChild_pid.append(nR_pid)
              nginxReload_num=nginxReload_num+1-nginxRestart_num
          #if nR_time and (nR_time_now not in nginxReload_time) and (color!='-c\n'):
              nginxReload_time.append(nR_time_now)
        
        elif i=='log_sender':
          lS_pid = os.popen("sudo ps aux|grep log_sender |grep -v grep|awk 'NR==1{print $2}'").read()
          lS_time = os.popen("sudo ps aux|grep log_sender |grep -v grep|awk 'NR==1{print $9}'").read()
          color = os.popen("sudo ps aux|grep log_sender |grep -v grep|awk 'NR==1{print $12}'").read()
          wwwdate = os.popen("sudo ps aux|grep log_sender |grep -v grep|awk 'NR==1{print $1}'").read()
          date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
          lS_time_now = date + '-' + lS_time.split('\n')[0]
          if lS_pid and (color!='-c\n') and ( lS_pid not in logSender_pid ) and (wwwdate=='www-data\n'):
              logSender_pid.append(lS_pid)
              logSender_num=logSender_num+1
          #if lS_time and (lS_time_now not in logSender_time) and (color!='-c\n'):
              logSender_time.append(lS_time_now)
        elif (i=='elasticsearch') and (os.popen("sudo ps -ef |grep elasticsearch |grep -v grep|awk 'NR==1{print $2}'").read()):
          time.sleep(1)
          e_pid = os.popen("sudo ps aux|grep elasticsearch |grep -v grep|awk 'NR==1{print $2}'").read()
          e_time = os.popen("sudo ps aux|grep elasticsearch |grep -v grep|awk 'NR==1{print $9}'").read()
          color = os.popen("sudo ps aux|grep elasticsearch |grep -v grep|awk 'NR==1{print $12}'").read()
          elastic = os.popen("sudo ps aux|grep elasticsearch |grep -v grep|awk 'NR==1{print $1}'").read()
          date = time.strftime('%Y-%m-%d',time.localtime(time.time()))  
          e_time_now = date + '-' + e_time.split('\n')[0] 
          if e_pid and (color!='-c\n') and (e_pid not in es_pid) and (elastic =='elastic+\n'):
            es_pid.append(e_pid)
            es_num=es_num+1
         # if e_time and (e_time_now not in es_time) and (color!='-c\n') and (elastic =='elastic+\n'):
            es_time.append(e_time_now)
        else:
          pass
    except (OSError,IOError): #防止进入循环但是这个时候进程重启,导致popen读取不到进程信息就会出错
      pass   
def set_nginxRestart_txt():
  now_path = os.getcwd()
  file_name = now_path + '/nginxRestart_%s.txt'%(nginxRestart_time[-1])
  #写入文本
  file1 = open(file_name,'w')
  for i in range(1,len(nginxRestart_time)):
    file1.write('重启时间:'+nginxRestart_time[i]+'重启前父进程号: '+ nginxParent_pid[i-1]+'重启后父进程号: ' +nginxParent_pid[i] + '\n')
  
  file1.close()
  file2 = open(file_name,'a+')
  file2.write('nginx restart次数为: ' + str(nginxRestart_num) + '\n')
  file2.close()
def set_nginxReload_txt():
  now_path = os.getcwd()
  file_name = now_path + '/nginxReload_%s.txt'%(nginxReload_time[-1])
  #写入文本
  file1 = open(file_name,'w')
  for i in range(1,len(nginxReload_time)):
    file1.write('重启时间:'+nginxReload_time[i] + '\n')
  
  file1.close()
  file2 = open(file_name,'a+')
  file2.write('nginx reload次数为:' + str(nginxReload_num) + '\n')
  file2.close()
def set_logsender_txt():
  now_path = os.getcwd()
  file_name = now_path + '/logsender_restart_%s.txt'%(logSender_time[-1])
  #写入文本
  file1 = open(file_name,'w')
  for i in range(1,len(logSender_time)):
    file1.write('重启时间:'+logSender_time[i]+'重启前进程号: '+ logSender_pid[i-1]+'重启后进程号: ' + logSender_pid[i] + '\n')
  
  file1.close()
  file2 = open(file_name,'a+')
  file2.write('logsender重启次数为: '+ str(logSender_num) + '\n')
  file2.close()
def set_es_txt():
  now_path = os.getcwd()
  file_name = now_path + '/esRestart_%s.txt'%(es_time[-1])
  #写入文本
  file1 = open(file_name,'w')
  for i in range(1,len(es_time)):
    file1.write('重启时间:'+es_time[i] +'重启前进程号: ' +es_pid[i-1] +'重启后进程号: ' + es_pid[i] +'\n')
  
  file1.close()
  file2 = open(file_name,'a+')
  file2.write('elasticsearch重启次数为: ' + str(es_num) + '\n')
  file2.close()
if __name__ =="__main__":
  thread_name=['nginx_restart','nginx_reload','log_sender','elasticsearch']
  try:
    get_restart(thread_name)
  except (KeyboardInterrupt,SystemExit):
    set_nginxRestart_txt()
    set_nginxReload_txt()
    set_logsender_txt()
    set_es_txt()

以上这篇python监控进程状态,记录重启时间及进程号的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中的实例方法、静态方法、类方法、类变量和实例变量浅析
Apr 26 Python
从零学python系列之数据处理编程实例(一)
May 22 Python
17个Python小技巧分享
Jan 23 Python
Python实现大文件排序的方法
Jul 10 Python
python中Switch/Case实现的示例代码
Nov 09 Python
windows环境下tensorflow安装过程详解
Mar 30 Python
python 读取文件并把矩阵转成numpy的两种方法
Feb 12 Python
Python中*args和**kwargs的区别详解
Sep 17 Python
Python3中configparser模块读写ini文件并解析配置的用法详解
Feb 18 Python
python selenium自动化测试框架搭建的方法步骤
Jun 14 Python
基于OpenCV的网络实时视频流传输的实现
Nov 15 Python
python中time包实例详解
Feb 02 Python
Python 获取windows桌面路径的5种方法小结
Jul 15 #Python
Python识别快递条形码及Tesseract-OCR使用详解
Jul 15 #Python
Python实现Mysql数据统计及numpy统计函数
Jul 15 #Python
通过python改变图片特定区域的颜色详解
Jul 15 #Python
用Python+OpenCV对比图像质量的几种方法
Jul 15 #Python
python3实现斐波那契数列(4种方法)
Jul 15 #Python
为什么从Python 3.6开始字典有序并效率更高
Jul 15 #Python
You might like
PHP封装的分页类与简单用法示例
2019/02/25 PHP
php高性能日志系统 seaslog 的安装与使用方法分析
2020/02/29 PHP
jQuery 使用手册(五)
2009/09/23 Javascript
JSQL SQLProxy 的 php 版本代码
2010/05/05 Javascript
常见效果实现之返回顶部(结合淡入、淡出、减速滚动)
2012/01/04 Javascript
jQuery照片伸缩效果不影响其他元素的布局
2014/05/09 Javascript
一个JavaScript递归实现反转数组字符串的实例
2014/10/14 Javascript
Underscore.js 1.3.3 中文注释翻译说明
2015/06/25 Javascript
javascript生成大小写字母
2015/07/03 Javascript
jquery实现点击展开列表同时隐藏其他列表
2015/08/10 Javascript
jQuery实现气球弹出框式的侧边导航菜单效果
2015/09/22 Javascript
通过Jquery.cookie.js实现展示浏览网页的历史记录超管用
2015/10/23 Javascript
利用原生JS自动生成文章标题树的实例
2016/08/22 Javascript
javascript cookie用法基础教程(概念,设置,读取及删除)
2016/09/20 Javascript
AngularJS使用ng-inlude指令加载页面失败的原因与解决方法
2017/01/19 Javascript
浅谈webpack 自动刷新与解析
2018/04/09 Javascript
优雅地使用loading(推荐)
2019/04/20 Javascript
vue中 v-for循环的用法详解
2020/02/19 Javascript
Vue微信公众号网页分享的示例代码
2020/05/28 Javascript
JS forEach跳出循环2种实现方法
2020/06/24 Javascript
VUE项目实现主题切换的多种方法
2020/11/26 Vue.js
python使用webbrowser浏览指定url的方法
2015/04/04 Python
python创建关联数组(字典)的方法
2015/05/04 Python
Python通过90行代码搭建一个音乐搜索工具
2015/07/29 Python
Python针对给定字符串求解所有子序列是否为回文序列的方法
2018/04/21 Python
详解python3类型注释annotations实用案例
2021/01/20 Python
彻底解决pip下载pytorch慢的问题方法
2021/03/01 Python
澳大利亚在线床零售商:Bedworks
2020/09/01 全球购物
销售人员中英文自荐信
2013/09/22 职场文书
经典而简洁的婚礼主持词
2014/03/13 职场文书
关于读书的活动方案
2014/08/14 职场文书
简单的离婚协议书范本
2014/11/16 职场文书
python 制作一个gui界面的翻译工具
2021/05/14 Python
Python编程中Python与GIL互斥锁关系作用分析
2021/09/15 Python
python基础之类方法和静态方法
2021/10/24 Python
Vue.js中v-for指令的用法介绍
2022/03/13 Vue.js