Home > Backend Development > Python Tutorial > python实现apahce网站日志分析示例

python实现apahce网站日志分析示例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 11:30:18
Original
1247 people have browsed it

维护脚本一例,写得有点乱,只是作为一个实例,演示如何快速利用工具快速达到目的:
应用到:shell与python数据交互、数据抓取,编码转换

代码如下:


#coding:utf-8
#!/usr/bin/python
'''
程序说明:apache access.log日志分析
 分析访问网站IP 来源情况
 日期:2014-01-06 17:01
 author:gyh9711

 程序说明:应用到:shell与python数据交互、数据抓取,编码转换
'''
import os
import json
import httplib
import codecs

LogFile='/var/log/apache2/access.log'
#日志
logMess='/tmp/acc.log'
if os.path.isfile(logMess):
 os.system('cp /dev/null %s'% logMess)
file=codecs.open(logMess,'w+',encoding='utf-8')

def cmd(cmd):
  return os.popen(cmd).readlines()
'''
def getIp(ip):
 return json.loads(os.popen("/usr/bin/curl http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip).readline())['data']
'''
conn = httplib.HTTPConnection('ip.taobao.com')
def getIpCountry(ip):
 conn.request('GET','/service/getIpInfo.php?ip=%s' % ip)
 r1=conn.getresponse()
 if r1.status == 200:
  return json.loads(r1.read())['data']
 else:
  return "Error"
#将access.log文件进行分析,并转为python数组
file.write(u"字段说明:ip   访问次数据  ip国家 城市的 isp号  省份  所在地区\n")
ipDb=[]
for i in cmd('''/usr/bin/awk '{print $1}' %s |sort |uniq -c''' % LogFile):
 ip = i.strip().split(' ')
 ipDb.append(ip)
#通过taobao 提供接口分析ip地址来源
for i in ipDb:
 _tmpD=getIpCountry(i[1])
 #格式说明:ip   访问次数据  ip国家 城市的 isp号  省份  所在地区
 out="%s%s%s%s%s%s%s"%(i[1].ljust(20),i[0].ljust(10),_tmpD['country'].ljust(20),_tmpD['city'].ljust(16),_tmpD['isp_id'].ljust(16),_tmpD['region'].ljust(16),_tmpD['area'].ljust(16))
 print out
 file.write("%s\n"%out)

conn.close()
file.close()

'''

'''

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template