脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python分析apache访问日志脚本分享

python分析apache访问日志脚本分享

2019-11-21 14:34python教程网 Python

这篇文章主要介绍了python分析apache访问日志脚本分享,本文直接给出实现代码,需要的朋友可以参考下

  1. #!/usr/bin/env python 
  2. # coding=utf-8 
  3.    
  4. #------------------------------------------------------ 
  5. # Name:     Apache 日志分析脚本 
  6. # Purpose:   此脚本只用来分析Apache的访问日志 
  7. # Version:   2.0 
  8. # Author:    LEO 
  9. # Created:   2013-4-26 
  10. # Modified:   2013-5-4 
  11. # Copyright:  (c) LEO 2013 
  12. #------------------------------------------------------ 
  13.    
  14. import sys 
  15. import time 
  16.    
  17. #该类是用来打印格式 
  18. class displayFormat(object): 
  19.    
  20.   def format_size(self,size): 
  21.     '''格式化流量单位''' 
  22.     KB = 1024     
  23.     MB = 1048576    
  24.     GB = 1073741824  
  25.     TB = 1099511627776 
  26.     if size >= TB : 
  27.       size = str(size / TB) + 'T' 
  28.     elif size < KB : 
  29.       size = str(size) + 'B' 
  30.     elif size >= GB and size < TB: 
  31.       size = str(size / GB) + 'G' 
  32.     elif size >= MB and size < GB : 
  33.       size = str(size / MB) + 'M' 
  34.     else : 
  35.       size = str(size / KB) + 'K' 
  36.     return size 
  37.    
  38.   formatstring = '%-15s %-10s %-12s %8s %10s %10s %10s %10s %10s %10s %10s' 
  39.    
  40.   def transverse_line(self) : 
  41.     '''输出横线''' 
  42.     print self.formatstring % ('-'*15,'-'*10,'-'*12,'-'*12,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10) 
  43.    
  44.   def head(self): 
  45.     '''输出头部信息''' 
  46.     print self.formatstring % ('IP','Traffic','Times','Times%','200','404','500','403','302','304','503'
  47.    
  48.   def error_print(self) : 
  49.     '''输出错误信息''' 
  50.     print 
  51.     print 'Usage : ' + sys.argv[0] + ' ApacheLogFilePath [Number]' 
  52.     print 
  53.     sys.exit(1) 
  54.    
  55.   def execut_time(self): 
  56.     '''输出脚本执行的时间''' 
  57.     print 
  58.     print "Script Execution Time: %.3f second" % time.clock() 
  59.     print 
  60.    
  61. #该类是用来生成主机信息的字典 
  62. class hostInfo(object): 
  63.      
  64.   host_info = ['200','404','500','302','304','503','403','times','size'
  65.    
  66.   def __init__(self,host): 
  67.     self.host = host = {}.fromkeys(self.host_info,0) 
  68.    
  69.   def increment(self,status_times_size,is_size): 
  70.     '''该方法是用来给host_info中的各个值加1''' 
  71.     if status_times_size == 'times'
  72.       self.host['times'] += 1 
  73.     elif is_size: 
  74.       self.host['size'] = self.host['size'] + status_times_size 
  75.     else
  76.       self.host[status_times_size] += 1 
  77.    
  78.   def get_value(self,value): 
  79.     '''该方法是取到各个主机信息中对应的值''' 
  80.     return self.host[value] 
  81.    
  82. #该类是用来分析文件 
  83. class fileAnalysis(object): 
  84.   def __init__(self): 
  85.     '''初始化一个空字典''' 
  86.     self.report_dict = {} 
  87.     self.total_request_times,self.total_traffic,self.total_200,  
  88.     self.total_404,self.total_500,self.total_403,self.total_302,  
  89.     self.total_304,self.total_503 = 0,0,0,0,0,0,0,0,0 
  90.    
  91.   def split_eachline_todict(self,line): 
  92.     '''分割文件中的每一行,并返回一个字典''' 
  93.     split_line = line.split() 
  94.     split_dict = {'remote_host':split_line[0],'status':split_line[-2],'bytes_sent':split_line[-1],} 
  95.     return split_dict 
  96.    
  97.   def generate_log_report(self,logfile): 
  98.     '''读取文件,分析split_eachline_todict方法生成的字典''' 
  99.     for line in logfile: 
  100.       try
  101.         line_dict = self.split_eachline_todict(line) 
  102.         host = line_dict['remote_host'
  103.         status = line_dict['status'
  104.       except ValueError : 
  105.         continue 
  106.       except IndexError : 
  107.         continue 
  108.    
  109.       if host not in self.report_dict : 
  110.         host_info_obj = hostInfo(host) 
  111.         self.report_dict[host] = host_info_obj 
  112.       else : 
  113.         host_info_obj = self.report_dict[host] 
  114.    
  115.       host_info_obj.increment('times',False)   
  116.       if status in host_info_obj.host_info :  
  117.         host_info_obj.increment(status,False)  
  118.       try
  119.         bytes_sent = int(line_dict['bytes_sent'])  
  120.       except ValueError: 
  121.         bytes_sent = 0 
  122.       host_info_obj.increment(bytes_sent,True) 
  123.     return self.report_dict 
  124.    
  125.   def return_sorted_list(self,true_dict): 
  126.     '''计算各个状态次数、流量总量,请求的总次数,并且计算各个状态的总量 并生成一个正真的字典,方便排序''' 
  127.     for host_key in true_dict : 
  128.       host_value = true_dict[host_key] 
  129.       times = host_value.get_value('times')  
  130.       self.total_request_times = self.total_request_times + times  
  131.       size = host_value.get_value('size')  
  132.       self.total_traffic = self.total_traffic + size  
  133.    
  134.       o200 = host_value.get_value('200'
  135.       o404 = host_value.get_value('404'
  136.       o500 = host_value.get_value('500'
  137.       o403 = host_value.get_value('403'
  138.       o302 = host_value.get_value('302'
  139.       o304 = host_value.get_value('304'
  140.       o503 = host_value.get_value('503'
  141.    
  142.       true_dict[host_key] = {'200':o200,'404':o404,'500':o500,'403':o403,'302':o302,'304':o304,  
  143.                   '503':o503,'times':times,'size':size} 
  144.    
  145.       self.total_200 = self.total_200 + o200 
  146.       self.total_404 = self.total_404 + o404 
  147.       self.total_500 = self.total_500 + o500 
  148.       self.total_302 = self.total_302 + o302 
  149.       self.total_304 = self.total_304 + o304 
  150.       self.total_503 = self.total_503 + o503 
  151.    
  152.     sorted_list = sorted(true_dict.items(),key=lambda t:(t[1]['times'],t[1]['size']),reverse=True) 
  153.     return sorted_list 
  154.    
  155. class Main(object): 
  156.   def main(self) : 
  157.     '''主调函数''' 
  158.     display_format = displayFormat() 
  159.     arg_length = len(sys.argv) 
  160.     if arg_length == 1 : 
  161.       display_format.error_print() 
  162.     elif arg_length == 2 or arg_length == 3: 
  163.       infile_name = sys.argv[1] 
  164.       try : 
  165.         infile = open(infile_name,'r'
  166.         if arg_length == 3 : 
  167.           lines = int(sys.argv[2]) 
  168.         else : 
  169.           lines = 0 
  170.       except IOError,e : 
  171.         print 
  172.         print e 
  173.         display_format.error_print() 
  174.       except ValueError : 
  175.         print 
  176.         print "Please Enter A Volid Number !!" 
  177.         display_format.error_print() 
  178.     else : 
  179.       display_format.error_print() 
  180.    
  181.     fileAnalysis_obj = fileAnalysis() 
  182.     not_true_dict = fileAnalysis_obj.generate_log_report(infile) 
  183.     log_report = fileAnalysis_obj.return_sorted_list(not_true_dict) 
  184.     total_ip = len(log_report) 
  185.     if lines : 
  186.       log_report = log_report[0:lines] 
  187.     infile.close() 
  188.    
  189.     print 
  190.     total_traffic = display_format.format_size(fileAnalysis_obj.total_traffic) 
  191.     total_request_times = fileAnalysis_obj.total_request_times 
  192.     print 'Total IP: %s  Total Traffic: %s  Total Request Times: %d' 
  193.        % (total_ip,total_traffic,total_request_times) 
  194.     print 
  195.     display_format.head() 
  196.     display_format.transverse_line() 
  197.    
  198.     for host in log_report : 
  199.       times = host[1]['times'
  200.       times_percent = (float(times) / float(fileAnalysis_obj.total_request_times)) * 100 
  201.       print display_format.formatstring % (host[0], 
  202.                          display_format.format_size(host[1]['size']), 
  203.                          times,str(times_percent)[0:5], 
  204.                          host[1]['200'],host[1]['404'], 
  205.                          host[1]['500'],host[1]['403'], 
  206.                          host[1]['302'],host[1]['304'],host[1]['503']) 
  207.                            
  208.     if (not lines) or total_ip == lines : 
  209.       display_format.transverse_line() 
  210.       print display_format.formatstring % (total_ip,total_traffic,  
  211.                          total_request_times,'100%'
  212.                          fileAnalysis_obj.total_200, 
  213.                          fileAnalysis_obj.total_404, 
  214.                          fileAnalysis_obj.total_500,  
  215.                          fileAnalysis_obj.total_403, 
  216.                          fileAnalysis_obj.total_302,  
  217.                          fileAnalysis_obj.total_304, 
  218.                          fileAnalysis_obj.total_503) 
  219.     display_format.execut_time() 
  220.    
  221. if __name__ == '__main__'
  222.   main_obj = Main() 
  223.   main_obj.main() 

延伸 · 阅读

精彩推荐