从dmesg命令中检查nfs相关错误-python

#! /usr/bin/python
# 通过在dmesg命令输出中查找匹配nfs: (.*)来定位nfs错误
# 由于dmesg命令输出不带时间戳,所以使用临时文件tmp_tag来定位上次已经检查过的行数
# 当tmp_tag不存在,或者tmp_tag中的内容非法(无法转换成数字)生成新的tmp_tag之后脚本就退出
# 以nagios插件的方式给出,修改print相关很容易改成其他方式

import subprocess
import re
import sys
import os.path

class Check_errorinfo_in_dmesg():
    def __init__(self,target_info):
        self.target_info=target_info
        self.dmesg_desc=''
        self.alert_infos={}
        self.now_rows=0
        self.last_rows=0
        self.tmp_tag='/tmp/'+os.path.basename(sys.argv[0])+'.tag'

    def get_dmesg_output(self):
        command=['dmesg']
        self.dmesg_desc=subprocess.Popen(command,stdout=subprocess.PIPE).stdout
        self.now_rows=len(self.dmesg_desc.readlines())
        self.dmesg_desc=subprocess.Popen(command,stdout=subprocess.PIPE).stdout

    def get_display_string(self):
        return_message=''
        for ip in self.alert_infos:
            return_message=return_message+ip+':'+str(self.alert_infos[ip])+' - '
        print(return_message)

    def exception_exit(self):
        with open(self.tmp_tag,'w') as tmp_file:
            tmp_file.write(str(self.now_rows))
        sys.exit(2)

    def normal_exit(self):
        with open(self.tmp_tag,'w') as tmp_file:
            tmp_file.write(str(self.now_rows))
        print('OK')
        sys.exit(0)

    def handle_lineno_in_tmpfile(self):
        try:
            with open(self.tmp_tag) as tmp_file:
                self.last_rows=tmp_file.read()
                self.last_rows=int(self.last_rows.strip())
        except Exception:
            self.normal_exit()
        if self.now_rows==self.last_rows:
            print('OK')
            sys.exit(0)
        if self.now_rows-self.last_rows<0:
            self.normal_exit()

    def check_errorinfo(self):
        self.get_dmesg_output()
        self.handle_lineno_in_tmpfile()
        target_re=re.compile(self.target_info)
        line_number=1
        for line_info in self.dmesg_desc:
            if line_number-self.last_rows<0:
                line_number+=1
                continue
            line_infos=target_re.search(line_info)
            if line_infos:
                line_info=line_info.strip()
                try:
                    self.alert_infos[line_infos.group(1)]+=1
                except KeyError:
                    self.alert_infos[line_infos.group(1)]=1
        if self.alert_infos:
            self.get_display_string()
            self.exception_exit()
        else:
            self.normal_exit()

if __name__ == '__main__':
    Check_errorinfo_in_dmesg('nfs: (.*)').check_errorinfo()

转载于:https://my.oschina.net/u/273053/blog/162485

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值