跳至正文
  • 108 views
  • 2 min read

根据月份提取Linux dmesg日志(自编)

新浪微博 豆瓣 QQ 百度贴吧 QQ空间

#!/usr/bin/env python3
# _*_ encoding:utf-8 _*_

import sys, subprocess, time

def execute_cmd (cmd):
    p = subprocess.Popen(
        cmd,
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        return p.returncode, stderr
    return p.returncode, stdout, stderr


def crLnxDmesgList ():
    dmesgcmd = """ dmesg |grep -iE 'error|fail' """
    uptimecmd = """ uptime|awk 'gsub(",", "") {print $3,$4,$5}' """
    f = execute_cmd(dmesgcmd)[1].decode()
    u = execute_cmd(uptimecmd)[1].decode()
    dmesgList = []
    curTime = int(time.mktime(time.localtime()))
    upres = u
    if 'days' in upres:
        up1 = int(upres.split()[0]) * 3600 * 24
        up2 = upres.split()[2]
    else:
        up1 = 0
        up2 = upres.split()[0]
    if ":" in up2:
        up2_1 = int(up2.split(":")[0]) * 3600
        up2_2 = int(up2.split(":")[1]) * 60
    else:
        up2_1 = 0
        up2_2 = int(up2) * 60
    upTime = curTime - up1 - up2_1 - up2_2
    for line in f.splitlines():
        dmesg_dict = {}
        mtime = line.split()[0]

        if mtime != 'sd':
            msgTimeStamp = upTime + int(line.split(']')[0].replace(' ', '')[1:].split('.')[0])
            msgTimeArray = time.strftime('%Y%m', time.localtime(msgTimeStamp))
            msgTime = time.strftime('%Y-%m-%d %H:%M', time.localtime(msgTimeStamp))
            dmesg_dict['msgtime'] = msgTime
            dmesg_dict['timeArray'] = msgTimeArray
        else:
            print('[ERROR]:Time format error in dmesg output.')
            sys.exit(10)
        dmesg_dict['msg'] = line

        if dmesg_dict:
            dmesgList.append(dmesg_dict)

    newDmesgList = []
    [ newDmesgList.append(msg) for msg in dmesgList if msg not in newDmesgList ]

    return newDmesgList


def main(argv):
    if len(argv) == 2:
        argv1 = argv[1]
        if not argv1.isdigit() or len(argv1) != 6:
            print('[ERROR]:Pls input correct month info, such as 202107.')
            print('-' * 5)
            print('# {0} 202107'.format(sys.argv[0]))
            sys.exit(10)
        allMsg = crLnxDmesgList()
        if allMsg:
            for msg in allMsg:
                if str(argv[1]) == str(msg['timeArray']):
                    print('{0} {1}'.format(msg['msgtime'], msg['msg']))
    else:
        print('[ERROR]:Pls input month info, such as 202107.')
        print('-' * 5)
        print('# {0} 202107'.format(sys.argv[0]))
        sys.exit(10)


if __name__ == '__main__':
    main(sys.argv)

发表回复

联系站长