Apache/Nginx 访问日志分析脚本

脚本功能:

脚本采用python2.7编写,用来分析Apahce的访问日志 

 

脚本用法:

  
  
  
  
  1. 脚本名 Apache的访问日志 [想要显示的行数]

 

更新:

 

1.第二版:增加 显示指定的行数

2.增加Nginx日志分析脚本

 

脚本执行效果如下:

 

脚本内容如下:

nginx访问日志分析脚本

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

 

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

你可能感兴趣的:(apache,nginx,日志,分析)