一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

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() 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 褪色的憎恨 | 欧美日韩高清观看一区二区 | 成人综合久久综合 | 湿好紧太硬了我太爽了 | 男gay网站视频免费观看 | freehd182d动漫| 欧洲网色偷偷亚洲男人的天堂 | 爱情岛论坛亚洲自拍 | 完整秽淫刺激长篇小说 | 香蕉tv国产在线永久播放 | 精品无人区麻豆乱码无限制 | www日本在线观看 | 亚洲成年人免费网站 | 亚洲卡一卡2卡三卡4卡无卡三 | 久久热在线视频精品1 | 亚洲AV国产国产久青草 | 四虎永久免费地址 | 天堂在线观看中文字幕 | 国产精品成人网红女主播 | 成年性午夜免费视频网站不卡 | 国产无限免费观看黄网站 | 天堂在线国产 | 色老太bbbbb| 成人久久18免费网站 | 日本国产在线视频 | 日韩亚洲欧美一区二区三区 | 我们日本在线观看免费动漫下载 | 免费看美女被靠到爽的视频 | 91制片厂制作果冻传媒123 | 97精品国产自在现线免费 | 91专区| 日韩手机在线视频 | 动漫美女强行被吸乳做羞羞事 | 日本红怡院亚洲红怡院最新 | 国产精品欧美日韩一区二区 | 亚洲欧美优优色在线影院 | 国产经典一区二区三区蜜芽 | 日本在线视频免费看 | 疯狂激吻添下边小说 | 日韩色在线观看 | 爱爱小说漫画 |