信息、分析-统计nginx日志的python实现 -by小雨

本文是一篇关于信息、分析-的帖子

    老大置布的务任,要分析一个5G巨细的nginx log file,因为我的python也是刚学,所以探索了久很,才实现了这个需求,话废不多话,简略暴粗,直接上代码!

    功能分析:

    1、统计Top 100 拜访数次最多的ip,并表现地理位置信息!这个是用的淘宝的地址库返回的ip地理位置及运营商信息  淘宝ip地址库REST API

    注:这方地说明一下,log里录记的件文有的是段分发送给客户端,所以同一个ip可能只是拜访一次,但在log里表现了多条录记,在这里我就简略暴粗的把每一次都算作一个拜访录记!有待改良,其他学同也可以修改下,告诉我该应怎么识别多少条录记是一次整完的拜访!

    2、统计Top 100 量流最高ip,并表现地理位置信息!

    3、统计Top 100 拜访量流最高url表列! 

    4、log件文录记的总量流!

    上面上代码,有要需的学同直接拿去!这个脚本分析一个4G的log用时13分阁下,系统配置(16G内存)!

    (1)ip_location.py件文:利用淘宝ip地址库,返回ip地点家国,区域(份省),都会,运营商

ip_location.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# the script is used to query the location of every ip

import urllib
import json

#淘宝ip库接口
url = "http://ip.taobao.com/service/getIpInfo.php?ip="

def ip_location(ip):
        data = urllib.urlopen(url + ip).read()
        datadict=json.loads(data)

        for oneinfo in datadict:
                if "code" == oneinfo:
                        if datadict[oneinfo] == 0:
                return datadict["data"]["country"] + datadict["data"]["region"] + datadict["data"]["city"] + "\t\t" + datadict["data"]["isp"]

(2)logparser.py件文:实现统计功能,详细见代码内释注!实现方法都很低级,毕竟是新手,谅见!

#!/usr/local/python
# -*- coding: utf-8 -*-

import os
import time
import re
import sys
import ip_location

"""定义一个间时类,可以选取要分析的间时段,如果没有指定间时段,则分析部全log"""
class TimeParser(object):
    def __init__(self, re_time, str_time, period):
        self.__re_time = re.compile(re_time)
        self.__str_time = str_time
        self.__period = period

    def __get(self, line):
        t= re.search(self.__re_time, line).group(0)
        return time.mktime(time.strptime(t, self.__str_time))

    def inPeriod(self, line):
        t = self.__get(line)
        return (t > time.mktime(time.strptime(self.__period[0], self.__str_time))
                    and t < time.mktime(time.strptime(self.__period[1], self.__str_time)))

class ParseLog(object):

    def __init__(self, file, re_time, str_time, period):

        self.ip_dict = {}
        self.url_dict = {}
    try:
        self.domain, self.parsetime, self.suffix = file.split("_")
    except:
        self.domain = file.split(".")[0]
        self.parsetime = "unknown time" 
    
    #定义一个数函,用来统计量数和总量流,并存入到应相字典中
    def Count(self):

        #用TimeParser实例化CountTime
        CountTime = TimeParser(re_time, str_time, period)
        self.total_traffic = []

        """
        以下for循环分析每一行,如果这一行不含包间时,就跳过,如果含包间时信息,且在所分析间时段内,
        则统计ip和traffic,没有http_refer信息的行只录记ip,然后跳过!
        """

        with open(file) as f:
            for i, line in enumerate(f):
                try:
                    if CountTime.inPeriod(line):
                        ip = line.split()[0]
                        try:
                            traffic = re.findall(r'\d{3}\ [^0]\d+', line)[0].split()[1]
                        except IndexError:
                            traffic = 0
                        try:
                            url = re.findall(r'GET\ .*\.*\ ', line)[0].split()[1]
                        except IndexError:
                            url = "unknown"
                    else:
                        continue
                except AttributeError:
                    continue

                self.ip_dict.setdefault(ip, {
      'number':0, 'traffic':0})['number'] += 1
                self.ip_dict.setdefault(ip, {
      'number':0, 'traffic':0})['traffic'] += int(traffic)
                self.url_dict.setdefault(url, 0)
                self.url_dict[url] += int(traffic)
        
                if not i % 1000000:
                    print "have processed " + str(i) + " lines !"

            #统计总量流
                self.total_traffic.append(int(traffic))
            total = sum(self.total_traffic)

        #打印总量流巨细
        print "******************************************************************"
        print self.domain + " all the traffic in " + self.parsetime + " is below:"
        print "total_traffic: %s" % str(total/1024/1024)+"MB"

    """定义两个字典,分离存储ip的量数和量流信息"""
    def TopIp(self, number):

        self.Count()
        TopNumberIp = {}
        TopTrafficIp = {}

        #对字典值赋
        for ip in self.ip_dict.keys():
            TopNumberIp[ip] = self.ip_dict[ip]['number']
            TopTrafficIp[ip] = self.ip_dict[ip]['traffic']

        #按值从大到小的次序排序键
        SortIpNo = sorted(TopNumberIp.items(), key=lambda e: e[1], reverse=True)
        SortIpTraffic = sorted(TopTrafficIp.items(), key=lambda e: e[1], reverse=True)

        #出输连接数top 100 ip的相干信息到件文TopIpNo.txt中
        ipno = open('TopIpNo.txt', 'w+')
        ipno.write(u"ip地址\t\t\t拜访数次\t\t家国/区域/都会\t\t\t运营商\n")
        ipno.write("-------------------------------------------------------------------------------------------------\n")

        for i in range(number):
            try:
                ipno.write(SortIpNo[i][0]+"\t\t"+str(SortIpNo[i][1])+"\t\t\t"+ip_location.ip_location(SortIpNo[i][0])+"\n")
            except:
                continue
        ipno.write("-------------------------------------------------------------------------------------------------\n")
        ipno.close()

        #出输量流top 100 ip的相干信息到件文iptraffic.txt中
        iptr = open('iptraffic.txt', 'w+')
        iptr.write(u"ip地址\t\t\t总量流(MB)\t\t家国/区域/都会\t\t\t运营商\n")
        iptr.write("-------------------------------------------------------------------------------------------------\n")

        for i in range(number):
            try:
                iptr.write(SortIpTraffic[i][0]+"\t\t"+str(SortIpTraffic[i][1]/1024/1024))
        
        #记入地理信息
        iptr.write("\t\t\t"+ip_location.ip_location(SortIpTraffic[i][0])+"\n")
            except:
                continue
        iptr.write("-------------------------------------------------------------------------------------------------\n")
        iptr.close()

    def TopUrl(self, number):
        SortUrlTraffic = sorted(self.url_dict.items(), key=lambda e: e[1], reverse=True)

        #出输量流top 100 url相干信息到urltraffic.txt件文中
        urtr = open('urltraffic.txt', 'w+')
        urtr.write("Filename".ljust(75)+u"TotalTraffic(MB)"+"\n")
        urtr.write("-----------------------------------------------------------------------------------------\n")

        for i in range(number):
            try:
                urtr.write(SortUrlTraffic[i][0].ljust(80)+str(SortUrlTraffic[i][1]/1024/1024)+"\n")
            except:
                continue
        urtr.write("-----------------------------------------------------------------------------------------\n")
        urtr.close()



#间时的正则和格式,一般不要需改更
re_time='\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2}'
str_time='%d/%b/%Y:%H:%M:%S'

#定义分析的间时段
period=("16/Nov/2000:16:00:00", "16/Nov/2015:17:00:00")

#定义出输top number
number = 100

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'no logfile specified!'
        print "Usage: python logParser.py filename"
        time.sleep(2)
        sys.exit()
    else:
        file = sys.argv[1]
    lp = ParseLog(file, re_time, str_time, period)
    print 
    print "Start to parse the " + file + " struggling! please wait patiently!"
    print
    print "******************************************************************"
    time.sleep(2) 
    lp.TopIp(number)
    lp.TopUrl(number)

用法:python  logparser.py  要分析的log件文名

文章结束给大家分享下程序员的一些笑话语录: 古鸽是一种搜索隐禽,在中国快绝迹了…初步的研究表明,古鸽的离去,很可能导致另一种长着熊爪,酷似古鸽,却又习性不同的猛禽类——犤毒鸟

你可能感兴趣的:(信息,分析-)