欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python脚本实现统计日志文件中的ip访问次数代码分享

时间:2021-04-18 09:50:25|栏目:Python代码|点击:

适用的日志格式:

106.45.185.214 - - [06/Aug/2014:07:38:59 +0800] "GET / HTTP/1.0" 200 10 "-" "-"
171.104.119.22 - - [06/Aug/2014:08:55:01 +0800] "GET / HTTP/1.0" 200 10 "-" "-"
27.31.238.242 - - [06/Aug/2014:09:43:19 +0800] "GET / HTTP/1.0" 200 10 "-" "-"
218.65.202.131 - - [06/Aug/2014:10:33:59 +0800] "GET / HTTP/1.0" 200 10 "-" "-"

以上为nginx的日志,本程序只适合用于IP在开头并用空格分开的这种格式。

实例代码:

import sys
 
class Log:
 
  def __init__(self, filename,dic,count):
    self.filename = filename
    self.dic=dic
    self.count=count
 
  def parse(self):
    i=1
    f=file(self.filename)
    while True:
      line=f.readline()
      if len(line)==0:
        break
      ip=line.split(' ')
      if ip[0] in dic:
        self.dic[ip[0]]=self.dic[ip[0]]+1
      else:
        self.dic[ip[0]]=i
    soredic=sorted(self.dic.items(), key=lambda d:d[1],reverse=True)
    counts=0;
    for item in soredic:
      if counts==int(self.count):
        break
      print("IP:%s  Total Times: %s"%(item[0],item[1]))
      counts=counts+1
    f.close()
 
if __name__=="__main__":
 
  if len(sys.argv)<3:
    print('usage:log.py log.log toptimes\nexample log.py log.log 20\ncode by iswin')
    sys.exit()
  dic={}
  log=Log(sys.argv[1],dic,sys.argv[2])
  log.parse()    

上一篇:Python使用import导入本地脚本及导入模块的技巧总结

栏    目:Python代码

下一篇:通过python-pptx模块操作ppt文件的方法

本文标题:python脚本实现统计日志文件中的ip访问次数代码分享

本文地址:http://www.codeinn.net/misctech/103775.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有