配置文件:

###############################################################################
# Config file to monitor CHM processes, YAML format
#
# procTask DataFile Record fields:
#  Date Time Node Command PID PCPU VSZ(KB) RSS(KB) StartTime Info
#
# fileTask DataFile Record fields:
#  FileName CreateTime Size(KB) INFO
#
################################################################################common setting for monitor
logLevel: debug         # debug, info, warn, error, fatal, default: debug
logFile: monitor.log    # log filename, default: monitor.log
allProc: "ASM|asm|MGMT|mgmt|APX|apx|d\.bin|cssdagent|cssdmonitor|orarootagent.bin|oraagent.bin|scriptagent.bin|tnslsnr"
asmProc: "ASM|asm"
mgmtProc: "MGMT|mgmt"
apxProc: "APX|apx"
crsProc: "d\.bin|cssdagent|cssdmonitor|orarootagent.bin|oraagent.bin|scriptagent.bin|tnslsnr"# monitoring process settings
OCSSDProcTask:type: processTask     # processTask - process monitor task, fileTask - file monitor taskexec: true            # true - execute this task, false - don't execute this task, default trueprocess: ocssd.bin|ohasd.bin   # process name list to be monitored, seperated by '|', used by grep to selectnodes: [rws00fys, rws00fyt, rws00fyu, rws00fyv] #optioanl, default is local hostcheckInterval: 1      # interval seconds to check status, default: 1 secondsstatCount: 5          # count of checkInterval to statistic, default: 5cpuThreshold: 10      # cpu usage percent threshold, default: 10.0%memThreshold: 409600  # rss memory threshold, in KB, default: 400MBDataFile: procmonitor.datactions: ~# monitoring file settings: use regular expression to match filenames
OCSSDFileTask:type: fileTask        # processTask - process monitor task, fileTask - file monitor taskexec: true            # true - execute this task, false - don't execute this taskfile:                 # file to be monitored- '/u01/app/crsusr/diag/crs/<LOCAL_HOST>/crs/trace/ohasd[_0-9]*.trc'- '/u01/app/crsusr/diag/crs/<LOCAL_HOST>/crs/trace/ocssd[_0-9]*.trc'checkInterval: 60     # interval seconds to check status, default: 60 secondsstatCount: 5          # count of checkInterval to statistic, default: 5wrapTime: 600wrapCount: 20         # in wrapInterval seconds, no more than wrapCount files generatedDataFile: filemonitor.datactions: ~# monitoring process settings
CHAMProcTask:type: processTask     # processTask - process monitor task, fileTask - file monitor taskexec: false            # true - execute this task, false - don't execute this taskprocess: osysmond|ologgerd|mdb_pmon   # process name list to be monitored, seperated by '|', used by grep to selectnodes: [rws00fys, rws00fyt, rws00fyu, rws00fyv] #optioanl, default is local hostcheckInterval: 1      # interval seconds to check status, default: 1 secondsstatCount: 5          # count of checkInterval to statistic, default: 5cpuThreshold: 10      # cpu usage percent threshold, default: 10.0%memThreshold: 409600  # rss memory threshold, in KB, default: 400MBDataFile: procmonitor.datactions: ~CHAMFileTask:type: fileTask        # processTask - process monitor task, fileTask - file monitor taskexec: false            # true - execute this task, false - don't execute this taskfile:                 # file to be monitored- '/u01/app/crsusr/diag/crs/<LOCAL_HOST>/crs/trace/osysmond[_0-9]*.trc'- '/u01/app/crsusr/diag/crs/<LOCAL_HOST>/crs/trace/ologgerd[_0-9]*.trc'- '/u01/app/12.2.0/grid/crf/db/<LOCAL_HOST>/json/jsondump.log'checkInterval: 60     # interval seconds to check status, default: 60 secondsstatCount: 5          # count of checkInterval to statistic, default: 5wrapTime: 600wrapCount: 20         # in wrapInterval seconds, no more than wrapCount files generatedDataFile: filemonitor.datactions: ~

运行代码

#!/usr/bin/env python"""
This script runs a sequence of commands on a remote host using SSH, it will monitor assigned
processes, it will report a warning if the process reboot or quit, or CPU/MEMORY exceed assigned
limits.
It also perform some simple system health checks such as open file descriptors number,
port status and memory usage etc."""import sys
import os
import platform
import time
from datetime import datetime,timedelta
import getopt
import getpass
import logging
import traceback
import subprocess
import yaml
import socket
import signal
import time
import threading
import reglobal LOGGER, OS_NAMETIME_OUT                    = 20
DEFAULT_LOGFILE             = "ractest.log";
DEFAULT_LOGLEVEL            = "debug"EXPR_NAME_ESC               = '\\'
EXPR_NAME_BEGIN             = '<'
EXPR_NAME_END               = '>'#platform.system()
#platform.release()
SYSTEM_LINUX                = 'Linux'
SYSTEM_SOLARIS              = 'SunOS'
SYSTEM_WINDOWS              = 'Windows'
SYSTEM_MACOS                = 'Darwin'
SYSTEM_AIX                  = 'AIX'
SYSTEM_HPUX                 = 'HPUX'LOCAL_HOST                  = socket.gethostname().split(".")[0]g_bRunApplication           = Truedef findString(file_name, value):file1 = file(file_name, 'r')for line in file1:if value in line:return lineelse:return Nonedef find_in_list(array_list, value):index = []i = 0for l in array_list:if cmp(l, value) == 0:index.append(i)i = i + 1return index    def strpTimeDelta(strDayTime):'''translate a format string to a timedelta object.strDayTime: string, format: [days-][hour:]minutes:secondsreturn a timedelta object by format string'''listDayTime = strDayTime.split('-')if (len(listDayTime) > 1):nDays = int(listDayTime[0])listTime = listDayTime[1].split(':')else:nDays = 0listTime = listDayTime[0].split(':')if (len(listTime) > 2):nHour = int(listTime[0])nMin = int(listTime[1])nSec = int(listTime[2])else:nHour = 0nMin = int(listTime[0])nSec = int(listTime[1])return timedelta(days=nDays, hours=nHour, minutes=nMin, seconds=nSec)# Run command over ssh or in local shell
def runSSHOneCmd(host, command):if (host != LOCAL_HOST):ssh_cmd = "ssh %s %s" % (host, command)else:ssh_cmd = "%s" % (command)proc = subprocess.Popen(ssh_cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)output = proc.communicate()#print "runSSHOneCmd: %s\nOutput: \n%s" % (ssh_cmd, output[0])lines = output[0].split('\n')#remove blank lineif len(lines) > 1 and not lines[-1].split():lines.pop()return lines      def readPropertyFile(strFileName, sep='=', comment_char='#'):"""Read the file passed as parameter as a properties file."""dictProps = {}with open(strFileName, "rt") as fPorpFile:for strLine in fPorpFile:strLine = strLine.strip()if strLine and not strLine.startswith(comment_char):tupKeyValue = strLine.split(sep)strKey = tupKeyValue[0].strip()strValue = sep.join(tupKeyValue[1:]).strip().strip('"') dictProps[strKey] = strValue return dictPropsdef parseString(strExp, dict = None):"""Parse the expressions in strExp, find expression value in dict and replace the expression with the valueExample: if LOCAL_HOST = "rws00fys", /u01/app/crsusr/diag/<LOCAL_HOST>/... will be parsed as:/u01/app/crsusr/diag/rws00fys/..."""if (dict is None):dict = {"LOCAL_HOST":LOCAL_HOST}#print "parseString0: %s, dict=%s" % (strExp, dict)nNormal = 0strResult = ""# find the first begin marknBegin = strExp.find(EXPR_NAME_BEGIN, nNormal)while (nBegin >= 0):if (nBegin >= 0 and strExp[nBegin-1] == EXPR_NAME_ESC):# escape of begin markstrResult += strExp[nNormal:nBegin-1]   # add string before ESC to resultstrResult += EXPR_NAME_BEGIN            # add escaped EXPR_NAME_BEGIN to result#print "parseString1: RESULT=%s" % (strResult)nNormal = nBegin+1nBegin = strExp.find(EXPR_NAME_BEGIN, nNormal)continue;# find end marknName = nBegin+1strName = ""nEnd = strExp.find(EXPR_NAME_END, nName)while (nEnd > 0 and strExp[nEnd-1] == EXPR_NAME_ESC):# escape of end markstrName += strExp[nName:nEnd-1]         # add string before ESC to namestrName += EXPR_NAME_END                # add escaped EXPR_NAME_END to namenName = nEnd+1nEnd = strExp.find(EXPR_NAME_END, nName)if (nEnd < 0):break;strName += strExp[nName:nEnd]strName = strName.replace(EXPR_NAME_ESC+EXPR_NAME_BEGIN, EXPR_NAME_BEGIN)strName = strName.replace(EXPR_NAME_ESC+EXPR_NAME_END, EXPR_NAME_END)strResult += strExp[nNormal:nBegin]#print "parseString2: NAME=%s" % (strName)if (strName is not None and len(strName) > 0):if strName not in dict:#print "parseString: '%s' not found." % (strName)#strResult += EXPR_NAME_BEGIN + strName + EXPR_NAME_ENDstrResult += strNameelse:strResult += str(dict[strName])#print "parseString3: RESULT=%s" % (strResult)# find next begin marknNormal = nEnd+1nBegin = strExp.find(EXPR_NAME_BEGIN, nNormal)# end of string parsestrResult += strExp[nNormal:]#print "parseString4: RESULT=%s" % (strResult)strResult = strResult.replace(EXPR_NAME_ESC+EXPR_NAME_BEGIN, EXPR_NAME_BEGIN)strResult = strResult.replace(EXPR_NAME_ESC+EXPR_NAME_END, EXPR_NAME_END)#print "parseString5: RESULT=%s" % (strResult)return strResultdef sigHandler(sig, frame):global g_bRunApplicationlogging.info("sigHandler: Caught signal: %s", sig)g_bRunApplication = Falselogging.info("sigHandler: g_bRunApplication: %s", g_bRunApplication)def exitWithUsage():print globals()['__doc__']os._exit(0)def initLogging(nLevel = logging.DEBUG, strLogFile = DEFAULT_LOGFILE):# create loggerstrScriptDir = os.path.dirname(os.path.realpath(__file__))#time_now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())#strLogFileName = os.path.join(strScriptDir, 'monitor_' + time_now + '.log')strLogFileName = os.path.join(strScriptDir, strLogFile)#strFmt = "%(asctime)-15s : %(levelname)s: %(filename)s-%(lineno)d: %(message)s"strFmt = "%(asctime)s : %(levelname)s: %(message)s"print "initLogging:\n filename = %s\n level = %d DEBUG=%d\n format = %s" % (strLogFileName, nLevel, logging.DEBUG, strFmt)logging.basicConfig(filename = strLogFileName, level = nLevel, format = strFmt)###############################################################################
# class RACAppBaseclass RACAppBase():def __init__(self):self.strLogFile = DEFAULT_LOGFILEself.nLogLevel = logging.DEBUGself.dictTask = {}def readConfig(self, strFileName):"""readConfig: read config items from config file file_nameconfig items:outFile:    log file name, default is DEFAULT_PROC_DATAFILEnodes:      node list to be monitored, if None, monitor local nodeprocess:    process command name list to be monitored, seperated by '|', can't be empty"""with open(strFileName, 'r') as stream:try:yamlObj = yaml.load(stream)except yaml.YAMLError as ex:print(ex)return False;self.strLogFile = yamlObj.get("logFile", DEFAULT_LOGFILE)strLogLevel = yamlObj.get("logLevel", DEFAULT_LOGLEVEL)if (strLogLevel == "info"):self.nLogLevel = logging.INFOelif (strLogLevel == "warn"):self.nLogLevel = logging.WARNelif (strLogLevel == "error"):self.nLogLevel = logging.ERRORelif (strLogLevel == "fatal"):self.nLogLevel = logging.FATALelse:self.nLogLevel = logging.DEBUGprint "Read Config file OK:\n logFile = %s\n logLevel = %s(%d)\n" % (self.strLogFile, strLogLevel, self.nLogLevel)return Truedef StartAllTasks(self):logging.info("Starting all tasks ...")logging.info("Start all tasks OK.")def StopAllTasks(self):logging.info("Stopping all tasks ...")logging.info("Stop all tasks OK.")#def main():
if __name__ == "__main__":#global g_bRunMonitorappTest = RACAppBase()#global g_bRunApplicationconfigFile = "process.yml"######################################################################## Parse the options, arguments, get ready, etc.######################################################################try:optlist, args = getopt.getopt(sys.argv[1:], 'h?f:', ['help','h','?'])except Exception, e:print str(e)exitWithUsage()if len(args) > 1:exitWithUsage()options = dict(optlist)if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:print "Help:"exitWithUsage()if '-f' in options:configFile = options['-f']#print "filename=", configFileif not configFile:print "The value of \'-f\' is empty, please enter a valid file name!!!"sys.exit(0)print "config file: %s" % (configFile)if not appTest.readConfig(configFile):print "Read config file '%s' failed!" % (configFile)sys.exit(-1)initLogging(appTest.nLogLevel, appTest.strLogFile)signal.signal(signal.SIGTERM, sigHandler)signal.signal(signal.SIGINT, sigHandler)logging.info("Begin testing racutil.")appTest.StartAllTasks()while g_bRunApplication:time.sleep(0.5)appTest.StopAllTasks()logging.info("End test racutil.")

if __name__ == "__main__":
    #global g_bRunMonitor
    appTest = RACAppBase()

#global g_bRunApplication
    configFile = "process.yml"

######################################################################
    ## Parse the options, arguments, get ready, etc.
    ######################################################################
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'h?f:', ['help','h','?'])
    except Exception, e:
        print str(e)
        exitWithUsage()
        
    if len(args) > 1:
        exitWithUsage()

options = dict(optlist)
    if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
        print "Help:"
        exitWithUsage()

if '-f' in options:
        configFile = options['-f']
        #print "filename=", configFile
        if not configFile:
            print "The value of \'-f\' is empty, please enter a valid file name!!!"
            sys.exit(0)

python 编程 远程监控进程数据相关推荐

  1. Python:通过远程监控用户输入来获取淘宝账号和密码的实验(二)

    从今天早上产生了写个获取淘宝账号及密码的想法后,到现在,全天都在看书.调试程序,12小时内写了三篇相关博客,如下: <Python:通过获取淘宝账号和密码的实验,来看登陆方式选择的重要性> ...

  2. 无线远程模块的应用,手机APP远程监控PLC数据技术方案

    无线远程模块的应用,手机APP远程监控PLC数据技术方案 (巨控何工_原创) 无线远程模块用途:广泛,遍及智能交通.环境保护.政府工作.公共安全.智能消防.工业监测.环境监测.路灯照明管控.景观照明管 ...

  3. 用python编写daemon监控进程并自动恢复(附Shell版)

    因为hadoop集群中datanode是大量存在的,那么多机器,什么事都可能发生,最通常的大概就是进程挂掉了.所以为了省事,参考别人的代码写了这个监控进程的daemon.当然,稍加修改就可以用来监控别 ...

  4. 树莓派3B上用Python编程获取TSL2561光传感器数据

    在树莓派3B上用Python编程,通过I2C协议,利用TSL2561光照强度传感器获取环境光强 嵌入式萌新一枚,文章有解释不清或者错误的地方希望大佬能在评论区指正,感激不尽! 大概原理: 通过TSL2 ...

  5. 卓岚云远程监控污水处理数据

    1.概述 随着经济的发展,我国的污水排水量已越来越大,没有有效的水处理措施已造成地表水的严重污染,环境质量也呈现不断恶化趋势.目前全国各地对污染源和排污河渠的水质监测仍停留在手工监测阶段,时间覆盖率低 ...

  6. 基于python的远程监控_python远程监控

    最近用python写了一个远程监控的程序,主要功能有:1.获取系统信息 2.对屏幕进行截图,屏幕截图发送到邮箱 3.可以用摄像头获取图片,这些图片上传到七牛 4.开机自启动 # #coding by ...

  7. Python:通过远程监控用户输入来获取淘宝账号和密码的实验(一)

    在前面两篇文章中实现了将用户输入信息抓取到后,写入文件,把用户操作的截图也保存了下来,但些文件是在用户的机器上的,获取到并不容易,本次再次优化了下,将用户输入发送到监控者的电脑上,图片传送回来目前还没 ...

  8. 通过python+ftps远程备份企业数据

    一.需求分析 朋友公司有一台ERP服务器做了定时输出备份,设置输出的目录是D:\backup\年月日 目录,其中当前日期(类似20171011)这个是服务器定时备份时自动生成并输出到这个目录.想自动备 ...

  9. pdf百度云下载 python编程 从数据分析到数据科学_python零基础入门教程,不同方向的,这很重要...

    很多人都在学python,对于大多数的人来说,方向最重要的,它决定着你的结果! ​编程小十接触过很多想学python的人,相对于自己的学习目的来说,很多时候容易选择不太正确的方向. 下面我简单介绍一下 ...

最新文章

  1. 第九天2017/04/18(3、重载/覆盖 PK 重写/重定义、父类子类混搭风、抽象类)
  2. 你不得不了解 Helm 3 中的 5 个关键新特性
  3. 第8章:Hadoop再探讨
  4. 机器学习中的数据预处理(sklearn preprocessing)
  5. Servlet使用适配器模式进行增删改查案例(jdbc.properties)
  6. AMD推出7nm高端显卡Radeon VII,直指英伟达RTX 2080
  7. JDK1.3安装出现/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory Done.
  8. 开发利器JRebel部署SpringBoot项目
  9. RCD:Residual Current Device,剩余电流装置
  10. centos6.6装mysql5.7_centos 6.5装mysql5.7
  11. pp助手苹果版_苹果一键刷机助手app免费版下载-一键刷机精灵下载手机版
  12. ARM DS5 项目build后无法找到axf文件
  13. 【H3C模拟器】VLAN单臂路由通信:用路由器实现和三层交换机实现
  14. 【解决篇】映美FP-530K+打印发票卡纸,色带安装问题
  15. java输入十个,键盘输入十个数,输出最大数
  16. 【深度学习】实时人眼 瞳孔追踪 系统
  17. WPS---EXCEL(十一)---将插入数据转化成柱状图
  18. Golang处理excel用流式写入,追加行数据
  19. 低成本2.4G SOC(NYA054E)灯控遥控芯片方案-CI2454/CI2451
  20. ayo开发笔记2016-5-3

热门文章

  1. CISAW安全集成考试有了新变化
  2. Linux第七章:6.管道 | 与 grep命令查找
  3. 腾讯云AI前端面试总结
  4. ale插件 vim_Vim插件之ale,LeaderF,completor.vim(win10)配置
  5. dwg怎么转成dxf格式?手机也能轻松操作
  6. phpEXCEL导出的数字太长,显示不完整
  7. 重构之美-跨越Web标准,触碰语义网[开门见山:Microformat]
  8. NIOS_II填坑之路——EPCS出现“Cannot open flash device”解决办法
  9. CentOS7.9下nginx的安装与配置(实现任意目录下均可直接执行 nginx 命令,以及开机自启动)
  10. 树莓派Raspberry