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

yipeiwu_com5年前Python基础

维护脚本一例,写得有点乱,只是作为一个实例,演示如何快速利用工具快速达到目的:
应用到: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()

'''

'''

相关文章

简单谈谈Python中的元祖(Tuple)和字典(Dict)

前言 本文记录了对于Python的数据类型中元祖(Tuple)和字典(Dict)的一些认识,以及部分内置方法的介绍。下面话不多说,来看看详细的介绍吧。 元祖 Tuple 特点:元祖内的数...

python能做什么 python的含义

python能做什么?是什么意思? Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能...

Python 基于wxpy库实现微信添加好友功能(简洁)

Python 基于wxpy库实现微信添加好友功能(简洁)

Github:https://github.com/Lyo-hub/wxpy_AddFriend 本程序为基于wxpy库实现的。 1.打开cmd导入一下库。 2.修改库文件中ad...

pytorch的batch normalize使用详解

torch.nn.BatchNorm1d() 1、BatchNorm1d(num_features, eps = 1e-05, momentum=0.1, affine=True) 对于...

Pyramid Mako模板引入helper对象的步骤方法

原理是我们在pyramind的before render event 中插入我们的helper 1. 创建helper.py文件,在里面添加上我们常用的方法 2. 在__init__.p...